9. Move Zeroes

9. Move Zeroes

Easy
61.0%
1.8k
arraytwo-pointers
Google, Amazon, Netflix, Meta (Facebook), Apple, Microsoft, Uber, Bloomberg, Airbnb, Stripe, Adobe, Salesforce, LinkedIn, Oracle

You’re interviewing for a backend or data engineering role at a FAANG-level company. The interviewer describes a real product scenario:

A high-traffic analytics or streaming platform processes event data in batches. Each batch contains numerical signals where a value of 0 represents a missing, delayed, or non-actionable event.

For downstream systems to work efficiently, all valid (non-zero) events must appear first, while zero values should be pushed to the end of the batch. The relative order of valid events must remain unchanged to preserve time-based meaning.

The data is stored in an integer array nums. The platform wants this cleanup to be done efficiently and in place, without allocating extra memory.

This is a common coding interview and DSA question might ask in Google, Amazon, Netflix, Meta, Apple, Microsoft, Uber, and Bloomberg interviews.

Your Task

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

You must perform this operation in place.

Input Format

  • nums: an array of integers

Output Format

  • Modify the array nums in place so that all zeroes are moved to the end
  • Return the modified array

Examples

Example 1:

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

Example 2:

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

Example 3:

Input: nums = [1, 2, 3, 4]
Output: [1, 2, 3, 4]

Constraints

  • 1 <= nums.length <= 100,000
  • -10^9 <= nums[i] <= 10^9
  • The array must be modified in place
  • Minimize the total number of operations

Loading editor...

[0,1,0,3,12]
[1,3,12,0,0]

Console Output

Click "Run Code" or "Submit" to see results

Your code will be evaluated by AI with instant feedback