← Questions

Find the bug in a loop condition

0
AppleCodingLast asked Mar 2026

A coding interview question asked in Apple's technical phone screen, last asked Mar 2026. It tests debugging and python.

A short Python program hangs or returns wrong results, and the cause is a loop's termination condition. Find the faulty condition, explain why it misbehaves and fix it. Talk through how you debug it systematically, not only the fix.

Example

A program of the kind you might be handed:

def count_steps(n: int, step: int) -> int:
    """How many times can step be subtracted until n runs out?"""
    count = 0
    while n != 0:
        n -= step
        count += 1
    return count
count_steps(9, 3)   ->  3
count_steps(10, 3)  ->  never returns   # n goes 10, 7, 4, 1, -2, ... and skips 0

Changing the condition to while n > 0 makes count_steps(10, 3) return 4 and leaves count_steps(9, 3) at 3.

Constraints

  • You may run the program, add prints or logging, use a debugger and write tests.
  • Fix the root cause, not the symptom (a timeout or an iteration cap is not a fix).

Clarifying questions

  • What should the function return, and for which inputs does it fail?
  • Does it hang, or finish with a wrong answer?
  • Are the inputs ever negative, zero or non-integers?
  • Can I add tests before changing the code?

What a strong answer covers

  • Reproduce first with the smallest failing input, then watch the loop variable each iteration (print, logging or a breakpoint).
  • The usual mistakes: != where < or > is needed, an off-by-one bound (< vs <=, range(len(x) - 1)), a variable that is never updated or updated on the wrong branch, modifying a list while iterating over it, floating-point equality in the condition.
  • State the loop invariant and why the fixed condition must eventually become false.
  • Regression tests at the boundaries: exact multiples, remainders, zero, and negative input.

Follow-ups

  • What should count_steps do when step is 0 or negative?
  • The loop is a binary search that hangs on two elements: how do you find it?
  • How would you catch this class of bug in code review or with a linter?

Where it's asked

  • Apple · Technical phone screen · Last asked Mar 2026

What it tests

debugging · python

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding