Move all zeroes to the end of the array while preserving the relative order of the non-zero elements.
Problem
Given an integer array, reorder it in place so that all 0 values are moved to the end while the relative order of the non-zero values remains unchanged.
You must modify the array directly and avoid using extra space proportional to the input size.
Goal
After the transformation:
- every non-zero element should appear before every zero
- the non-zero elements should stay in their original order
- the array length must remain the same
Input Format
- A list of integers
nums - The array may contain positive, negative, and zero values
Output Format
- Modify
numsin place - Return nothing, or return the modified array depending on the language convention
Constraints
- Elements may be any 32-bit signed integers
- Aim for time and extra space
Example 1
Input
nums = [0,1,0,3,12]
Output
[1,3,12,0,0]
Explanation
The non-zero values 1, 3, and 12 keep their original order, and the zeroes are moved to the end.
Example 2
Input
nums = [0,0,1]
Output
[1,0,0]
Explanation
Only one non-zero value exists, so it is placed first and the zeroes follow.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.