Two Pointers Rearranging in place

163. Move Zeroes

Easy

You are given an integer array nums. Move every 0 to the end of the array. The other elements must keep the order they had.

Change nums itself. The function returns nothing; the answer is what nums holds after it finishes.

Aim for O(1) extra memory, without making a copy of the array.

Example 1

Input: nums = [0, 4, 0, 0, 9, 2]

Output: [4,9,2,0,0,0]

Explanation: The non-zero values 4, 9 and 2 move to the front in the order they had. The three zeros fill the last three places.

Example 2

Input: nums = [-7, 0, 3, -1]

Output: [-7,3,-1,0]

Explanation: Negative numbers are not zeros, so −7 and −1 stay with 3, in their original order.

Example 3

Input: nums = [7, 1, 0]

Output: [7,1,0]

Explanation: The only zero is already at the end, so nothing moves.

Check your understanding

Work out the answer for this input before you write any code.

nums = [0, 5, 0, -3, 7]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.