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 every2nd locker (2, 4, 6, ...). - In general, on pass
k, you flip every locker whose label is a multiple ofk(k, 2k, 3k, ...up ton), turning closed lockers open and open lockers closed. - On pass
n, you flip only lockern.
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 allnpasses finish, and"lockers"is the ascending list of1-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
Understand the locker game and output format
We have
nlockers numbered1throughn, all starting closed. We runnpasses: - Pass1: toggle every locker (1, 2, 3, ...). - Pass2: toggle every2nd locker (2, 4, 6, ...). - Passk: toggle everykth locker (k, 2k, 3k, ...). - Passn: toggle only lockern.Given any positive integer
n,count_open_lockers(n)must return a dictionary{"count": c, "lockers": [...]}containing the countcand the ascending list of open locker numbers.Start with a simulation to spot the pattern
Before jumping to math, let's watch what happens to
6lockers 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 allnrounds directly takesn/1 + n/2 + ... + n/nflips (aboutn * ln(n)steps andO(n)memory), which is fine forn = 100(482flips) yet far too slow forn = 10^10— and simulation alone does not explain why squares appear.Connect rounds to divisors
Focus on a single locker number
iand ask: which rounds flip lockeri?Round
kvisitsk, 2k, 3k, ..., so roundktouches lockeriif and only ifiis a multiple ofk— in other words,kis a divisor ofi(a whole number in1 .. ithat dividesiwith remainder0). Because we run all rounds from1up ton >= i, every divisor ofigets its own round.Since locker
istarts closed: -1toggle leaves it open, -2toggles return it to closed, -3toggles leave it open, and so on.Therefore, locker
iends open if and only ifihas an odd number of divisors.Pair up divisors to see why perfect squares win
Why do almost all numbers have an even number of divisors? Whenever a number
ddividesi, its partneri // dalso dividesi, becaused * (i // d) = i! Let's group the divisors of7,12, and16into 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 unlessd == i // d, which meansd * d == i. That happens if and only ifiis a perfect square, and for a perfect square only its square rootdpairs with itself — making the total divisor count2 * m + 1(odd)!This immediately explains two classic boundary cases: -
n = 1:1 = 1 * 1has1divisor (odd), so locker1stays open. -nis prime (like2,11, or97): a prime numberphas only the single pair(1, p)—2divisors — so lockerpopens in pass1and closes in passp.Generate perfect squares directly with integer math
Because the open lockers are simply
1^2, 2^2, 3^2, ...up ton, we do not even need to test every locker from1ton. We just countroot = 1, 2, 3, ...upward whileroot * root <= nand appendroot * root!Two small details keep the code rock solid: 1. Use inclusive
<=(root * root <= n), because whennitself is a square (such asn = 25 = 5 * 5), lockernis also open. 2. Multiply integers (root * root <= n) instead of calling floating-pointmath.sqrt(n), which loses precision on huge integers above2^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}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]}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)). Thewhile root * root <= nloop executes once for each integerrootfrom1tofloor(sqrt(n)), doingO(1)integer multiplication and list append per step — optimal whenever we must output allfloor(sqrt(n))open locker numbers. - Space:
O(sqrt(n)). We store only thefloor(sqrt(n))open locker numbers inopen_lockers(O(1)extra working variables beyond the required output list).
Edge cases
- Single locker (
n = 1): Toggled once in pass1, so{"count": 1, "lockers": [1]}. - Prime number of lockers (
n = 2, 11, 97): A prime number (an integer greater than1whose only divisors are1and itself) has2divisors, so lockernopens in pass1and closes in passn; only perfect squares strictly belownremain open. - Exact square boundary (
n = 16orn = 25): Becauseroot * root <= nuses inclusive<=, lockernitself is included (5 * 5 == 25). - One below a square (
n = 15orn = 24):root = 4(16 > 15) orroot = 5(25 > 24) stops cleanly one step earlier. - Huge
n(n = 10^10): Produces10^5squares 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
1opens lockerpand passpcloses it (2toggles = even). - Writing
root * root < ninstead ofroot * root <= n: Strict<drops locker25whenn = 25and returns4instead of5. - Using
int(math.sqrt(n))on very large integers: IEEE-754 64-bit floats have only 53 bits of precision, so forn = (10**8 + 1)**2 - 1(~10^16),int(math.sqrt(n))rounds up to100,000,001instead of100,000,000; always use integer arithmetic (root * root <= normath.isqrt(n)). - Off-by-one 0-based indexing in simulations: Lockers and passes start at
1, not0(range(step, n + 1, step)).
Alternative approaches
- Precompute count with
math.isqrt(n): Python'smath.isqrt(n)computes exactfloor(sqrt(n))in integer arithmetic;[k * k for k in range(1, math.isqrt(n) + 1)]produces the exact sameO(sqrt(n))list. - Full simulation (
O(n log n)time,O(n)space): Great as a 6-line brute-force sanity check intests.pyto verify smallnagainst 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
500passes are performed, locker500's final state depends only on whether500is a perfect square, which we check inO(1)time viamath.isqrt(500) ** 2 == 500. Since22^2 = 484and23^2 = 529,500is not a square and finishes closed (confirmed by prime factorization500 = 2^2 * 5^3, which has(2 + 1) * (3 + 1) = 12divisors, an even number). Note that if fewer than500passesR < 500were run, you would instead count how many divisors of500are<= 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^2withk^2 <= Nstays open, so the exact count isfloor(sqrt(N)). In Python, compute this inO(1)space without floating-point rounding error usingmath.isqrt(N)(for example,math.isqrt(25) == 5andmath.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 (
nota multiple of3) and got toggled an odd number of times (square), OR it started open (multiple of3) and got toggled an even number of times (nota square). That is the symmetric difference (or XOR, keeping items that belong to exactly one of the two sets "perfect squares" and "multiples of3"): since3is prime,k^2is divisible by3iffkis divisible by3, so withs = math.isqrt(N)there ares // 3numbers in1..Nthat are both squares and multiples of3, givings + (N // 3) - 2 * (s // 3)open lockers (5 + 8 - 2 * 1 = 11open lockers whenN = 25, because square9flips closed while the other7multiples of3stay open).
Follow-up questions
- How can you decide in constant time whether a single specific locker—say locker 500—ends up open or closed?
- What closed-form expression gives the exact count of open lockers for an arbitrary corridor length N without listing them?
- How does the final open count change if every locker whose index is divisible by 3 starts open while all others start closed?
Similar questions
- First-Player Strategy on an Even-Length Coin Line
- Peak Concurrent Active Loans
- Stock Trading Profit With Bounded Trades
- Handling an Inconclusive A/B Test Readout
- Ad Serving Economics, Mixture Variance, and Waiting Times
- Target Bankroll Probability with Biased Flips