Program to make a bulb switcher using binary string using Python

Suppose we have n bulbs in a room, numbered from 0 to n-1 and arranged in a row from left to right. Initially, all bulbs are turned off (0-state). We need to achieve a target configuration represented by a binary string where '1' means the bulb is on and '0' means it's off.

The bulb switcher has a special flipping operation:

  • Select any bulb index i

  • Flip each bulb from index i to index n-1 (flip all bulbs from position i to the end)

We need to find the minimum number of flips required to achieve the target configuration.

Example Walkthrough

For target = "0101", we need 3 flips:

  • Start: "0000" (all bulbs off)

  • Flip from index 1: "0111"

  • Flip from index 2: "0100"

  • Flip from index 3: "0101" (target achieved)

Algorithm

The key insight is that we only need to flip when the current bulb state differs from what we expect based on our current configuration. We track the expected state and count transitions:

  • Initialize count = 0 and expected_state = '0'

  • For each bulb in the target string:

    • If current bulb differs from expected_state, increment count and update expected_state

  • Return the total count

Implementation

def solve(target):
    count = 0
    expected_state = '0'  # All bulbs start as off
    
    for bulb in target:
        if bulb != expected_state:
            count += 1
            expected_state = bulb
    
    return count

# Test with the given example
target = "0101"
result = solve(target)
print(f"Target: {target}")
print(f"Minimum flips needed: {result}")
Target: 0101
Minimum flips needed: 3

Additional Examples

def solve(target):
    count = 0
    expected_state = '0'
    
    for bulb in target:
        if bulb != expected_state:
            count += 1
            expected_state = bulb
    
    return count

# Test with multiple examples
test_cases = ["1011", "0000", "1111", "1010"]

for target in test_cases:
    result = solve(target)
    print(f"Target: {target} ? Flips needed: {result}")
Target: 1011 ? Flips needed: 3
Target: 0000 ? Flips needed: 0
Target: 1111 ? Flips needed: 1
Target: 1010 ? Flips needed: 3

How It Works

The algorithm works because each flip operation affects all bulbs from the selected position to the end. We simulate this by tracking what the current "effective state" should be at each position. When we encounter a mismatch, we know a flip is needed at that position.

Bulb Switcher Example: Target "0101" Initial: 0 0 0 0 Flip from 1: 0 1 1 1 Flip from 2: 0 1 0 0 Flip from 3: 0 1 0 1 Legend: OFF (0) ON (1)

Conclusion

The bulb switcher problem can be solved efficiently by tracking state transitions. Each time the target differs from our expected state, we need one flip operation. This greedy approach gives us the minimum number of flips required.

Updated on: 2026-03-25T21:00:21+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements