Move every zero to the end of an array while preserving the order of other values

Read the full interview experience this question came from →

Quick Overview

An array manipulation exercise: move every zero in an integer list to the end while preserving the relative order of the non-zero values. It checks careful in-place updates with constant extra memory and correct handling of lists that contain no zeros or nothing but zeros.

Move every zero to the end of an array while preserving the order of other values

Company: Microsoft

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

Given a list of integers `nums`, move every `0` to the end of the list while keeping the non-zero values in their original relative order. Return the rearranged list. The interviewer expects the rearrangement to happen in place, using only a constant amount of extra memory beyond the input list. ### Function Signature ```python def move_zeroes(nums: List[int]) -> List[int]: ``` ### Rules - You may modify `nums` in place and return it; only the returned list is checked. - The non-zero values must appear in the same order as in the input, and every zero must come after all of them. - A list with no zeros, or with only zeros, comes back unchanged. ### Constraints - `1 <= len(nums) <= 10^4` - `-2^31 <= nums[i] <= 2^31 - 1` ### Examples Example 1 ```text Input: nums = [4, 0, 0, 7, -2, 0, 5] Output: [4, 7, -2, 5, 0, 0, 0] ``` Example 2 ```text Input: nums = [0, 0, 1] Output: [1, 0, 0] ``` Example 3 ```text Input: nums = [3, 1] Output: [3, 1] ```

Overview: An array manipulation exercise: move every zero in an integer list to the end while preserving the relative order of the non-zero values. It checks careful in-place updates with constant extra memory and correct handling of lists that contain no zeros or nothing but zeros.

Read the full Microsoft Software Engineer interview experience this question came from

Microsoft logo
Microsoft
Apr 3, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Given a list of integers nums, move every 0 to the end of the list while keeping the non-zero values in their original relative order. Return the rearranged list.

The interviewer expects the rearrangement to happen in place, using only a constant amount of extra memory beyond the input list.

Function Signature

def move_zeroes(nums: List[int]) -> List[int]:

Rules

  • You may modify nums in place and return it; only the returned list is checked.
  • The non-zero values must appear in the same order as in the input, and every zero must come after all of them.
  • A list with no zeros, or with only zeros, comes back unchanged.

Constraints

  • 1 <= len(nums) <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1

Examples

Example 1

Input: nums = [4, 0, 0, 7, -2, 0, 5]
Output: [4, 7, -2, 5, 0, 0, 0]

Example 2

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

Example 3

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