← Questions

Check an array is a permutation of 0 to n-1

0
TeslaCodingLast asked Sep 2025

A coding interview question asked in Tesla's technical phone screen, last asked Sep 2025. It tests arrays, in-place and cyclic sort.

Given an integer array nums of length n, decide whether it contains every integer from 0 to n - 1 exactly once. Do it in O(n) time with O(1) extra space.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • is_zero_based_permutation(nums: list[int]) -> bool
  • Values can be anything, including negatives and numbers >= n. You may rearrange nums in place.

Example

is_zero_based_permutation([3, 0, 2, 1])  ->  True
is_zero_based_permutation([2, 2, 0])     ->  False   # 2 twice, 1 missing
is_zero_based_permutation([0, 5, 1])     ->  False   # 5 is out of range
is_zero_based_permutation([])            ->  True

Constraints

  • 0 <= n <= 2 * 10^5.
  • O(1) extra space: no sets, dictionaries, boolean arrays or sorting.

Clarifying questions

  • May I modify the input, or must it be left unchanged (or restored)?
  • Is the empty array a valid permutation?
  • Can values be negative or very large?
  • Should the code be idiomatic Python (generator expressions, all) or close to C?

What a strong answer covers

  • Cyclic placement: for each index, while nums[i] != i, reject if the value is out of range or if its home nums[v] already holds v (a duplicate); otherwise swap it home. Every swap places one value for good, so the total work is O(n).
  • Why the out-of-range check must come before indexing with the value.
  • Alternatives and their limits: a sum check alone is fooled by [0, 0, 3]; XOR plus range checks is also fooled by duplicates; marking by negation needs care with 0.
  • Tests: empty, single [0], duplicates, out-of-range values, an already sorted array.

Follow-ups

  • Do it without modifying the input, still in O(1) extra space. What can and can't you guarantee?
  • Return the missing and the duplicated value when the check fails.
  • Implement power(base: float, exp: int) by repeated squaring in O(log |exp|), handling negative exponents, exp = 0 and the smallest 32-bit exponent.

Where it's asked

  • Tesla · Technical phone screen · Last asked Sep 202545 min · 10 to 20 minutes on your background, then one compact coding, debugging or design task in CoderPad that must run

What it tests

arrays · in-place · cyclic sort

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