Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Move Zeros While Preserving Order
00:00
5 left

Move Zeros While Preserving Order

MediumPython

Problem

How would you write code to move all zeros in an array or list to the right while keeping non-zero order?

Implement move_zeros(nums) to modify the input list in place and return it; non-zero values must retain their relative order. For example, [0, 1, 0, 3, 12] becomes [1, 3, 12, 0, 0], while [1, 2, 3] remains unchanged. Assume nums contains integers, may be empty, and has length at most 10^3; target O(n) time and O(1) extra space.

Constraints

  • 0 <= nums.length <= 10^3
  • -10^9 <= nums[i] <= 10^9
  • The input list must be modified in place
  • The relative order of non-zero values must be preserved

Function Signature

def move_zeros(nums):
Interviewer

Your question is Move Zeros While Preserving Order. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.