EasyArraysAI interview only
Move Zeroes
Asked atmetaamazonmicrosoftapplebloomberggoogle
01 · Problem
You are given an integer array nums. Shift every 0 to the end of the array while keeping the non-zero values in the same relative order they started in.
Return the rearranged array. Aim to do the rearrangement in place, without allocating a second array.
02 · Examples
Example 01
Input
nums = [0,1,0,3,12]
Output
[1,3,12,0,0]
The non-zero values 1, 3, 12 keep their order and both zeros move to the back.
Example 02
Input
nums = [0]
Output
[0]
A single zero is already at the end.
Example 03
Input
nums = [4,0,5,0,0,6]
Output
[4,5,6,0,0,0]
4, 5 and 6 stay in order; the three zeros collect at the end.
03 · Constraints
- 011 <= nums.length <= 104
- 02-231 <= nums[i] <= 231 - 1
- 03The returned array must have the same length as the input
04 · Optimal complexity
- Time
- O(n)
- Space
- O(1)
05 · Two ways to work on it
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.