My first instinct was to scan left to right and greedily place a tank as far right as possible whenever I hit an uncovered house.
Use a greedy strategy: scan the string from left to right, and when you encounter an uncovered house, place a tank on the nearest available empty plot to its right if possible, otherwise on the left. This minimizes the number of tanks because each tank can cover at most one house, and placing it as far right as possible leaves more options for subsequent houses.
Pro tip: Clarify that each tank covers exactly one house (since it can only be adjacent to one house), so the problem reduces to matching each house to a distinct adjacent empty plot. Then mention that a greedy left-to-right assignment with a preference for the right neighbor is optimal and runs in O(n) time.
Restate the problem: each tank covers exactly one house, tanks can only be placed on empty plots, and each empty plot can hold at most one tank. The goal is to cover all houses with the minimum number of tanks, or return -1 if impossible.
For each house from left to right, if it's not already covered, place a tank on the nearest available empty plot to its right. If no right plot is available, place it on the left. This greedy choice is safe because placing a tank to the right never hurts future houses more than placing it to the left.
Iterate through the string, maintaining a count of tanks and a way to mark covered houses (e.g., a boolean array or by modifying the string). For each house, check if it's covered; if not, try to place a tank on the right, else on the left, and increment the count.
If a house has no adjacent empty plot available (both left and right are either houses or already occupied by tanks), then it's impossible to cover all houses, so return -1.
The algorithm runs in O(n) time and O(1) extra space if we modify the string in place. Discuss edge cases: empty string, no houses, consecutive houses, and houses at the ends of the string.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.