Flip Coins Until All Heads - aloalgo

Flip Coins Until All Heads

Medium

You have a row of coins, each showing either heads ('H') or tails ('T'). You can perform an operation: choose any coin and flip it. When you flip a coin at index i, it also flips its adjacent coins at i-1 (if i > 0) and i+1 (if i < n-1). The goal is to make all coins show heads ('H') using the minimum number of flips. Determine this minimum number. If it's impossible to make all coins heads, return -1.

Example 1

Input
"HHT"
Output
2
Explanation:

To make 'HHT' into 'HHH', we can flip the first coin (index 0). This changes 'HHT' -> 'TTH' (coins 0 and 1 flipped). Then, flip the second coin (index 1). This changes 'TTH' -> 'HHH' (coins 0, 1, and 2 flipped). Total 2 flips.

Example 2

Input
"TTT"
Output
1
Explanation:

To make 'TTT' into 'HHH', we can flip the middle coin (index 1). This changes 'TTT' -> 'HHH' (coins 0, 1, and 2 flipped). Total 1 flip.

Example 3

Input
"HT"
Output
-1
Explanation:

No sequence of flips can turn 'HT' into 'HH'. If we flip coin 0, it becomes 'TH'. If we flip coin 1, it becomes 'HH' (by flipping 0 and 1) but that doesn't mean it's possible. After careful consideration, it's impossible to achieve all 'H'.

Loading...
Input
"HHT"
Output
2

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!