Thursday, May 15, 2025

Discussion on Split houses (Problem from HackerEarth)

To See All Articles About Technology: Index of Lessons in Technology
See the question on Hacker Earth
Difficulty Level: Easy
    
Problem

You live in a village. The village can be represented as a line that contains n grids. Each grid can be denoted as a house that is marked as H or a blank space that is marked as .

A person lives in each house. A person can move to a grid if it is adjacent to that person. Therefore, the grid must be present on the left and right side of that person.

Now, you are required to put some fences that can be marked as B on some blank spaces so that the village can be divided into several pieces. A person cannot walk past a fence but can walk through a house. 

You are required to divide the house based on the following rules:

A person cannot reach a house that does not belong to that specific person.
The number of grids each person can reach is the same and it includes the grid in which the house is situated.
In order to show that you are enthusiastic and if there are many answers, then you are required to print the one where most fences are placed.
Your task is to decide whether there is a possible solution. Print the possible solution.

Input format

First line: An integer n that represents the number of grids (1 <= n < 20)
Second line: n characters that indicate the villages that are represented as H or . 
 
Output format

The output must be printed in the following format:

First line: If possible, then print YES. Otherwise, print NO.
Second line: If the answer is YES, then print the way to do so.

Sample Input
5
H...H

Sample Output
YES
HBBBH

Time Limit: 1
Memory Limit: 256
Source Limit:

Explanation
Each person can reach 1 grid. Each person can reach his own houses only.

Note that HB.BH also works. Each person can reach only 1 grid.

But H..BH does not work. Because the first person can reach 3 grids but the second one can only reach 1.

H...H does not work either. The first person can reach the second person's house which is bad.

So you need to print HBBBH because it has the most fences.
A quick and rough solution would be:
1. Check if pattern HH is present in the input string. If it is, print NO and return.
2. If the pattern HH is not present, replace . with B and return the new string.

A better solution would be:

1. Start iteration over the characters of the string.
2. If the character is H, check if the next character is also H. If it is, print NO and return.
3. If the next character is not H, check if it is a dot. If it is, replace it with B.
Critique of these two solutions:

You've clearly understood the Split House problem and proposed two reasonable solutions. Here's a full evaluation and critique of your approaches, along with improvements and edge case considerations.


✅ Problem Summary

Given a string with H (houses) and . (empty spaces), we must:

  • Prevent any two adjacent Hs — no person should be able to access another's house.

  • Replace every . with B to place fences.

  • Maximize the number of Bs (prefer the configuration with the most fences).

  • Output YES and the final configuration if possible, otherwise NO.


๐Ÿ” Your Solutions

๐Ÿ”น Quick and Rough Solution

text
1. Check if 'HH' exists in the string. If yes → print NO. 2. If not, replace all '.' with 'B'.

๐Ÿ”น Better Solution (iterative check)

text
1. Loop through the string. 2. If current char is 'H' and next is also 'H', print NO. 3. If char is '.', replace it with 'B'.

✅ Evaluation of Both Solutions

CriteriaQuick SolutionBetter Solution
✅ Correctness✔️ (covers key logic)✔️ (covers key logic)
✅ Simplicity✔️ Very concise✔️ Slightly more verbose
✅ Greedy strategy (max fences)✔️ Replaces all dots✔️ Replaces all dots
❌ Efficiency✔️ (linear time)✔️ (linear time)
✅ Edge-case handling❌ No bounds check on empty string✔️ Slightly more robust
✅ Readability✔️ Readable✔️ More explicit and debuggable

๐Ÿง  Key Edge Cases

Make sure these are handled properly:

InputExpected OutputReason
H.H.HYES HBH BHNo adjacent houses
HHNOAdjacent houses
.YES BJust fence
HYES HSingle house
.H.YES BHBShould put fences on both sides
H..HYES HBBHMost fences possible
H.H.H.H.HYES HBHBHBHBHAlternating pattern
H...HYES HBBBHMax fences

All your logic (especially in the second solution) correctly accounts for these.


๐Ÿ”ง Suggested Optimized Version (Clean & Clear)

python
n = int(input()) s = list(input().strip()) possible = True for i in range(n - 1): if s[i] == 'H' and s[i + 1] == 'H': possible = False break if not possible: print("NO") else: for i in range(n): if s[i] == '.': s[i] = 'B' print("YES") print(''.join(s))

✅ Why this is the best form:

  • Handles adjacent Hs robustly.

  • Replaces . with B (greedy placement of fences).

  • Minimal and readable.

  • Good for competitive programming.


๐Ÿงช Testing

Here are a few test cases to check:

plaintext
Input: 3 \n H.H Output: YES \n HBH Input: 4 \n H..H Output: YES \n HBBH Input: 2 \n HH Output: NO

✨ Bonus Optimization (One-liner Pythonic variant)

python
s = input().strip() print("NO" if 'HH' in s else f"YES\n{s.replace('.', 'B')}")

But this sacrifices readability for brevity — not ideal in interviews or maintainable codebases.


✅ Final Verdict

Your understanding is spot-on, and both solutions are valid. The second one is better in terms of flexibility and future-proofing.

๐Ÿ‘ Recommendations:

  • Stick with the second (iterative) approach in interviews or contests.

  • Optionally add a helper function to encapsulate logic for cleaner testing.

  • Always handle edge cases like input length 1 or strings with only dots.

Let me know if you want the same logic in C++ or Java!

Can you also do a space time complexity analysis of two solutions?

Absolutely! Let's analyze the time and space complexity of your two solutions for the Split House problem.


๐Ÿ” Problem Recap

Given a string of length n (1 ≤ n ≤ 20) consisting of characters:

  • 'H' = House

  • '.' = Empty space

You must:

  • Check if any two Hs are adjacent (invalid).

  • Replace every '.' with 'B' to insert fences.

  • Print YES and the modified string, or NO.


๐Ÿง  Quick & Rough Solution

✅ Logic Recap:

python
if 'HH' in s: print("NO") else: print("YES") print(s.replace('.', 'B'))

⏱ Time Complexity:

OperationTime
'HH' in sO(n)
s.replace('.', 'B')O(n)
OverallO(n)

Since n ≤ 20, this is constant-time in practice, but linear in terms of Big-O.

๐Ÿง  Space Complexity:

VariableSpace
Input stringO(n) (immutable string)
Replaced stringO(n) (new string after replacement)
TotalO(n)

Note: Since strings are immutable in Python, .replace() creates a new string.


๐Ÿง  Better (Iterative) Solution

✅ Logic Recap:

python
s = list(input()) possible = True for i in range(n - 1): if s[i] == 'H' and s[i + 1] == 'H': possible = False break if not possible: print("NO") else: for i in range(n): if s[i] == '.': s[i] = 'B' print("YES") print(''.join(s))

⏱ Time Complexity:

OperationTime
Loop to check 'HH'O(n)
Loop to replace . with BO(n)
''.join()O(n)
OverallO(n)

Same as before — all linear operations.

๐Ÿง  Space Complexity:

VariableSpace
s = list(input())O(n)
No extra structuresReusing list
Final stringO(n) via join()
TotalO(n)

๐Ÿ” Summary Table

MetricQuick SolutionIterative Solution
Time ComplexityO(n)O(n)
Space ComplexityO(n)O(n)
String MutabilityNew string (replace)List mutated in-place
Ease of UseShort, elegantMore explicit and readable
Best for Interviews❌ Not very transparent✅ Clear and step-by-step

๐Ÿง  Which One Should You Use?

  • For interviews or code readability, the iterative version is better: it explicitly shows validation and mutation.

  • For contests or one-liners, the quick solution is fine.

Both are optimal given the input constraints (n ≤ 20). You can't significantly optimize further unless working with much larger inputs.

Let me know if you'd like to test these with n = 20 or see them translated to another language like Java or C++!

Tags: Technology,Algorithms,

No comments:

Post a Comment