FastPrepOpen Lockers After Toggle Passes
Problem · Math

Open Lockers After Toggle Passes

Learn this problem
EasyTekion logoTekionFULLTIMEPHONE SCREEN

Problem statement

There are n lockers in a hallway, numbered 1 through n. Every locker starts closed.

You make exactly n passes. On pass i (1 <= i <= n), toggle every locker whose number is a multiple of i: a closed locker opens and an open locker closes.

Return how many lockers are open after the final pass.

What the interview report shared

The report asked how many of 100 initially closed lockers remain open after 100 toggle passes, and called the exercise a bulb-switcher variation.

Function

openLockers(n: int) → int

Examples

Example 1

n = 100return = 10

After 100 passes, a locker stays open only when it is toggled an odd number of times. That happens exactly for the perfect squares 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, so 10 lockers are open.

Example 2

n = 3return = 1

Pass 1 opens lockers 1, 2, 3. Pass 2 closes locker 2. Pass 3 closes locker 3. Only locker 1 remains open.

Constraints

  • 1 <= n <= 10^6.

More Tekion problems

drafts saved locally
public int openLockers(int n) {
  // Write your code here.
}
n100
expected10
checking account