Given a string sequence containing a sequence of houses represented by the character ‘H’ and spaces represented by the character ‘.’ between the houses, the goal is to determine if it’s possible to place electric poles in such a way that each house has an electric pole adjacent to it. Each house can either have an electric pole on its left or right side or on both sides. However, poles cannot be placed directly adjacent to each other except with a house between them (i.e., “HPH” is valid but “HPPH” is not).
Function signature:
bool validWordOut(string sequence);
false
.true
since there’s no constraint violation.#include <iostream>
#include <string>
using namespace std;
bool validWordOut(string sequence) {
int n = sequence.length();
if (n == 0) return true; // An empty sequence is trivially valid
// Iterate through each character and apply the validation logic
for (int i = 0; i < n; ++i) {
if (sequence[i] == 'H') {
// Check the left and right sides for available spaces
bool leftValid = (i > 0 && sequence[i - 1] == '.');
bool rightValid = (i < n - 1 && sequence[i + 1] == '.');
if (!leftValid && !rightValid) {
return false; // No valid place for this 'H'
}
}
}
return true; // All houses can be provided with poles
}
int main() {
// Test cases
cout << validWordOut("H.H") << endl; // Expected output: 1 (true)
cout << validWordOut("HH") << endl; // Expected output: 0 (false)
cout << validWordOut("H..H") << endl; // Expected output: 1 (true)
cout << validWordOut(".") << endl; // Expected output: 1 (true)
cout << validWordOut("") << endl; // Expected output: 1 (true)
cout << validWordOut("H...H") << endl; // Expected output: 1 (true)
cout << validWordOut("H") << endl; // Expected output: 0 (false)
cout << validWordOut("H.H.H") << endl; // Expected output: 1 (true)
return 0;
}
The time complexity of this solution is O(n), where n
is the length of the sequence since we are iterating through the characters of the sequence exactly once to determine the validity of placement of poles.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?