Skip to content
RED SAGSkills

Push Zeros to the End

Given an array nums, return an array where all the zeros have been moved to the end while the non-zero values keep their original relative order.

Example 1

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

Example 2

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

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Hint 1

Keep a write pointer for the next non-zero slot.

Hint 2

After copying the non-zero values forward, fill the rest with zeros.

Good practice for: Frontend Developer, Backend Developer, Full Stack Developer, Mobile App Developer, Game Developer, Automation Test Engineer

Run checks your code on 2 sample tests. Submit runs all 6 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.