Bulb Switcher Solution for Accenture

Company: Accenture · Difficulty: Medium · Topics: Math, Brain Teaser

Problem Statement

There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.

On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.

Find how many bulbs are on after n rounds.

Key Understanding:

Examples

Example 1:

Input: n = 3

Output: 1

Explanation:

Example 2:

Input: n = 1

Output: 1

Explanation:

Example 3:

Input: n = 0

Output: 0

Explanation:

Intuition

The key insight is to understand which bulbs will be toggled an odd number of times.

Mathematical Insight:

Why Perfect Squares Work:

Approach

Approach 1: Mathematical (Optimal)

Algorithm:

1. Count the number of perfect squares ≤ n

2. Return the count

Why This Works:

Approach 2: Simulation

Algorithm:

1. Create an array of n bulbs (all off)

2. For each round i from 1 to n:

3. Count bulbs that are on

Approach 3: Factor Counting

Algorithm:

1. For each bulb i from 1 to n:

2. Return count of bulbs with odd factors

Dry Run

Let's trace through Example 1: n = 3

Mathematical Approach:

Simulation Approach:

Factor Counting:

Key Insights

1. Perfect Squares: Only perfect squares have odd number of factors

2. Mathematical Solution: Count perfect squares ≤ n

3. Efficiency: O(1) time complexity with mathematical approach

4. Pattern Recognition: The result is floor(√n)

Edge Cases

1. n = 0: Return 0

2. n = 1: Return 1

3. Large n: Mathematical approach handles efficiently

4. Perfect Square n: Include n in count

Solution

⚠️ Disclaimer: Don't jump directly to the solution, try it out yourself first. Only look at the solution after you've given it a good attempt.

Solution 1: Mathematical (Optimal)

Time Complexity: O(1) - Constant time

Space Complexity: O(1) - Constant space

Solution 2: Simulation

Time Complexity: O(n²) - For each round, toggle bulbs

Space Complexity: O(n) - Array to store bulb states

Solution 3: Factor Counting

Time Complexity: O(n * √n) - For each bulb, find factors

Space Complexity: O(1) - Constant space

More Accenture coding questions