Move Zeroes

Easy
Two Pointers

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Example 1

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]

Example 2

Input: nums = [0]
Output: [0]

Constraints

  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
Show Hints (3)
Hint 1: Use two pointers: one to iterate through the array, one to track where the next non-zero should go.
Hint 2: When you find a non-zero element, swap it with the element at the slow pointer position.
Hint 3: This maintains the relative order of non-zero elements while pushing zeros to the end.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?