Check an array is a permutation of 0 to n-1
I was asked this
No reports yet. Sign in to say where you were asked it.
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 rearrangenumsin 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 homenums[v]already holdsv(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 = 0and 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
