Open Lockers After Multi-Pass Toggling

Medium · Statistics & Math · Software Engineer · Technical Screen

Problem Statement

A corridor contains n lockers labeled 1 through n, all initially closed. You walk down the corridor n times in numbered passes k = 1, 2, ..., n:

  • On pass 1, you flip every locker (1, 2, 3, ...), opening all of them.
  • On pass 2, you flip every 2nd locker (2, 4, 6, ...).
  • In general, on pass k, you flip every locker whose label is a multiple of k (k, 2k, 3k, ... up to n), turning closed lockers open and open lockers closed.
  • On pass n, you flip only locker n.

Implement:

def count_open_lockers(n: int) -> Dict[str, object]:

Return a dictionary {"count": total_open, "lockers": open_labels} where:

  • "count" is the total number of lockers that remain open after all n passes finish, and
  • "lockers" is the ascending list of 1-based integer labels of those open lockers.

Examples

Example 1

Input: n = 6
Output: {"count": 2, "lockers": [1, 4]}

Tracking the six lockers (C = closed, O = open) across each pass:

  • Initial: [C, C, C, C, C, C]
  • Pass 1: [O, O, O, O, O, O]
  • Pass 2: [O, C, O, C, O, C]
  • Pass 3: [O, C, C, C, O, O]
  • Pass 4: [O, C, C, O, O, O]
  • Pass 5: [O, C, C, O, C, O]
  • Pass 6: [O, C, C, O, C, C]

Only lockers 1 and 4 remain open at the end.

Example 2

Input: n = 25
Output: {"count": 5, "lockers": [1, 4, 9, 16, 25]}

Lockers 1, 4, 9, 16, 25 are toggled an odd number of times (1, 3, 3, 5, 3 times respectively) and finish open, including locker 25 itself.

Example 3

Input: n = 11
Output: {"count": 3, "lockers": [1, 4, 9]}

Lockers 1, 4, and 9 stay open, whereas prime-labeled locker 11 is opened on pass 1 and closed again on pass 11.

Constraints

  • 1 <= n <= 10^10

Step-by-step walkthrough

  1. Understand the locker game and output format

    We have n lockers numbered 1 through n, all starting closed. We run n passes: - Pass 1: toggle every locker (1, 2, 3, ...). - Pass 2: toggle every 2nd locker (2, 4, 6, ...). - Pass k: toggle every kth locker (k, 2k, 3k, ...). - Pass n: toggle only locker n.

    Given any positive integer n, count_open_lockers(n) must return a dictionary {"count": c, "lockers": [...]} containing the count c and the ascending list of open locker numbers.

  2. Start with a simulation to spot the pattern

    Before jumping to math, let's watch what happens to 6 lockers round by round (C = closed, O = open):

    Locker #:    1   2   3   4   5   6
    Initially:   C   C   C   C   C   C
    Round 1:     O   O   O   O   O   O   (multiples of 1)
    Round 2:     O   C   O   C   O   C   (multiples of 2)
    Round 3:     O   C   C   C   O   O   (multiples of 3)
    Round 4:     O   C   C   O   O   O   (multiples of 4)
    Round 5:     O   C   C   O   C   O   (multiples of 5)
    Round 6:     O   C   C   O   C   C   (multiples of 6)
    Final:       O   .   .   O   .   .   -> open lockers: [1, 4]
    

    If you run a small simulation for n = 20, the open lockers are [1, 4, 9, 16] — every perfect square! Simulating all n rounds directly takes n/1 + n/2 + ... + n/n flips (about n * ln(n) steps and O(n) memory), which is fine for n = 100 (482 flips) yet far too slow for n = 10^10 — and simulation alone does not explain why squares appear.

  3. Connect rounds to divisors

    Focus on a single locker number i and ask: which rounds flip locker i?

    Round k visits k, 2k, 3k, ..., so round k touches locker i if and only if i is a multiple of k — in other words, k is a divisor of i (a whole number in 1 .. i that divides i with remainder 0). Because we run all rounds from 1 up to n >= i, every divisor of i gets its own round.

    Since locker i starts closed: - 1 toggle leaves it open, - 2 toggles return it to closed, - 3 toggles leave it open, and so on.

    Therefore, locker i ends open if and only if i has an odd number of divisors.

  4. Pair up divisors to see why perfect squares win

    Why do almost all numbers have an even number of divisors? Whenever a number d divides i, its partner i // d also divides i, because d * (i // d) = i! Let's group the divisors of 7, 12, and 16 into factor pairs:

    Locker  7 (prime):   (1, 7)                  -> 2 distinct divisors (even) -> CLOSED
    Locker 12:           (1, 12)  (2, 6)  (3, 4) -> 6 distinct divisors (even) -> CLOSED
    Locker 16 (square):  (1, 16)  (2, 8)  (4, 4) -> 5 distinct divisors (odd)  -> OPEN
                                           ^^^^
                                  4 pairs with itself, contributing 1 divisor instead of 2!
    

    Every pair (d, i // d) adds two distinct divisors unless d == i // d, which means d * d == i. That happens if and only if i is a perfect square, and for a perfect square only its square root d pairs with itself — making the total divisor count 2 * m + 1 (odd)!

    This immediately explains two classic boundary cases: - n = 1: 1 = 1 * 1 has 1 divisor (odd), so locker 1 stays open. - n is prime (like 2, 11, or 97): a prime number p has only the single pair (1, p) — 2 divisors — so locker p opens in pass 1 and closes in pass p.

  5. Generate perfect squares directly with integer math

    Because the open lockers are simply 1^2, 2^2, 3^2, ... up to n, we do not even need to test every locker from 1 to n. We just count root = 1, 2, 3, ... upward while root * root <= n and append root * root!

    Two small details keep the code rock solid: 1. Use inclusive <= (root * root <= n), because when n itself is a square (such as n = 25 = 5 * 5), locker n is also open. 2. Multiply integers (root * root <= n) instead of calling floating-point math.sqrt(n), which loses precision on huge integers above 2^53.

    def count_open_lockers(n: int) -> Dict[str, object]:
        # open_lockers: ascending list of open locker numbers [1, 4, 9, ...] up to n.
        # Locker i is toggled once per divisor of i; divisors pair up as (d, i // d),
        # so only perfect squares (where d == i // d) have an odd number of toggles.
        open_lockers: List[int] = []
    
        # Enumerate integer square roots 1, 2, 3, ... directly instead of testing all n lockers.
        root = 1
        # Use inclusive '<=' so n itself is included when n is a perfect square (e.g., n = 100),
        # and integer multiplication so large n never suffers floating-point sqrt rounding.
        while root * root <= n:
            open_lockers.append(root * root)
            root += 1
    
        return {"count": len(open_lockers), "lockers": open_lockers}
    
  6. Trace the examples

    Example 1 (n = 6):
      root = 1 -> 1 * 1 = 1 <= 6   -> open_lockers = [1]
      root = 2 -> 2 * 2 = 4 <= 6   -> open_lockers = [1, 4]
      root = 3 -> 3 * 3 = 9 > 6    -> stop!
      Result: {"count": 2, "lockers": [1, 4]}
    
    Example 2 (n = 25):
      root = 1..5 -> squares 1, 4, 9, 16, 25 (all <= 25)
      root = 6    -> 6 * 6 = 36 > 25 -> stop!
      Result: {"count": 5, "lockers": [1, 4, 9, 16, 25]}
    
    Example 3 (n = 11):
      root = 1..3 -> squares 1, 4, 9 (all <= 11)
      root = 4    -> 4 * 4 = 16 > 11 -> stop!
      Result: {"count": 3, "lockers": [1, 4, 9]}
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def count_open_lockers(n: int) -> Dict[str, object]:
        # open_lockers: ascending list of open locker numbers [1, 4, 9, ...] up to n.
        # Locker i is toggled once per divisor of i; divisors pair up as (d, i // d),
        # so only perfect squares (where d == i // d) have an odd number of toggles.
        open_lockers: List[int] = []
    
        # Enumerate integer square roots 1, 2, 3, ... directly instead of testing all n lockers.
        root = 1
        # Use inclusive '<=' so n itself is included when n is a perfect square (e.g., n = 100),
        # and integer multiplication so large n never suffers floating-point sqrt rounding.
        while root * root <= n:
            open_lockers.append(root * root)
            root += 1
    
        return {"count": len(open_lockers), "lockers": open_lockers}
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of every locker as a light switch that starts off (closed): flipping a switch an even number of times returns it to off, while flipping it an odd number of times leaves it on (open). Round k flips locker i precisely when k is a divisor of i (a whole number that divides i evenly with zero remainder). Almost every divisor d has a distinct partner i // d because d * (i // d) = i — for example, 12 splits into (1, 12), (2, 6), and (3, 4) (6 flips -> closed). The only way a number ends up with an odd number of divisors is when one factor pairs with itself (d == i // d), which is the exact definition of a perfect square (i = d * d).

Why not just simulate all n rounds in an array? Toggling every multiple in rounds 1 through n performs n/1 + n/2 + ... + n/n flips — a harmonic series (the sum 1 + 1/2 + 1/3 + ... + 1/n, which grows like ln(n)) totaling O(n log n) time and O(n) memory. While n = 100 takes only 482 flips, n = 10^10 would require roughly 230 billion flips and gigabytes of RAM, and raw simulation misses the mathematical insight the interviewer is explicitly asking for.

Here is how divisor pairing plays out across n = 6 lockers:

Locker 1: (1, 1)         -> 1 distinct divisor  (odd)  -> OPEN
Locker 2: (1, 2)         -> 2 distinct divisors (even) -> closed
Locker 3: (1, 3)         -> 2 distinct divisors (even) -> closed
Locker 4: (1, 4), (2, 2) -> 3 distinct divisors (odd)  -> OPEN
Locker 5: (1, 5)         -> 2 distinct divisors (even) -> closed
Locker 6: (1, 6), (2, 3) -> 4 distinct divisors (even) -> closed

Open lockers up to 6: [1, 4], count = 2

Complexity

Let n be the total number of lockers (and rounds).

  • Time: O(sqrt(n)). The while root * root <= n loop executes once for each integer root from 1 to floor(sqrt(n)), doing O(1) integer multiplication and list append per step — optimal whenever we must output all floor(sqrt(n)) open locker numbers.
  • Space: O(sqrt(n)). We store only the floor(sqrt(n)) open locker numbers in open_lockers (O(1) extra working variables beyond the required output list).

Edge cases

  • Single locker (n = 1): Toggled once in pass 1, so {"count": 1, "lockers": [1]}.
  • Prime number of lockers (n = 2, 11, 97): A prime number (an integer greater than 1 whose only divisors are 1 and itself) has 2 divisors, so locker n opens in pass 1 and closes in pass n; only perfect squares strictly below n remain open.
  • Exact square boundary (n = 16 or n = 25): Because root * root <= n uses inclusive <=, locker n itself is included (5 * 5 == 25).
  • One below a square (n = 15 or n = 24): root = 4 (16 > 15) or root = 5 (25 > 24) stops cleanly one step earlier.
  • Huge n (n = 10^10): Produces 10^5 squares in milliseconds using exact integer multiplication, with zero array simulation.

Common mistakes

  • Guessing that prime-numbered lockers stay open: Beginners often think primes are "rarely touched," forgetting that pass 1 opens locker p and pass p closes it (2 toggles = even).
  • Writing root * root < n instead of root * root <= n: Strict < drops locker 25 when n = 25 and returns 4 instead of 5.
  • Using int(math.sqrt(n)) on very large integers: IEEE-754 64-bit floats have only 53 bits of precision, so for n = (10**8 + 1)**2 - 1 (~10^16), int(math.sqrt(n)) rounds up to 100,000,001 instead of 100,000,000; always use integer arithmetic (root * root <= n or math.isqrt(n)).
  • Off-by-one 0-based indexing in simulations: Lockers and passes start at 1, not 0 (range(step, n + 1, step)).

Alternative approaches

  • Precompute count with math.isqrt(n): Python's math.isqrt(n) computes exact floor(sqrt(n)) in integer arithmetic; [k * k for k in range(1, math.isqrt(n) + 1)] produces the exact same O(sqrt(n)) list.
  • Full simulation (O(n log n) time, O(n) space): Great as a 6-line brute-force sanity check in tests.py to verify small n against the mathematical formula.

Follow-up questions

  • How can you decide in constant time whether a single specific locker—say locker 500—ends up open or closed? Assuming at least 500 passes are performed, locker 500's final state depends only on whether 500 is a perfect square, which we check in O(1) time via math.isqrt(500) ** 2 == 500. Since 22^2 = 484 and 23^2 = 529, 500 is not a square and finishes closed (confirmed by prime factorization 500 = 2^2 * 5^3, which has (2 + 1) * (3 + 1) = 12 divisors, an even number). Note that if fewer than 500 passes R < 500 were run, you would instead count how many divisors of 500 are <= R.
  • What closed-form expression gives the exact count of open lockers for an arbitrary corridor length N without listing them? Every perfect square 1^2, 2^2, ..., k^2 with k^2 <= N stays open, so the exact count is floor(sqrt(N)). In Python, compute this in O(1) space without floating-point rounding error using math.isqrt(N) (for example, math.isqrt(25) == 5 and math.isqrt(11) == 3).
  • How does the final open count change if every locker whose index is divisible by 3 starts open while all others start closed? The passes still toggle each locker once per divisor (odd toggles iff perfect square), so a locker finishes open in two cases: it started closed (not a multiple of 3) and got toggled an odd number of times (square), OR it started open (multiple of 3) and got toggled an even number of times (not a square). That is the symmetric difference (or XOR, keeping items that belong to exactly one of the two sets "perfect squares" and "multiples of 3"): since 3 is prime, k^2 is divisible by 3 iff k is divisible by 3, so with s = math.isqrt(N) there are s // 3 numbers in 1..N that are both squares and multiples of 3, giving s + (N // 3) - 2 * (s // 3) open lockers (5 + 8 - 2 * 1 = 11 open lockers when N = 25, because square 9 flips closed while the other 7 multiples of 3 stay open).

Follow-up questions

Similar questions

More Tekion interview questions

All 4 Tekion questions →