HomeInterview QuestionsMove all zeros to the end of a list of numbers.

Move all zeros to the end of a list of numbers.

🟡 Medium Coding Mid level
1Times asked
Jul 2026Last seen
Jul 2026First seen

💡 Model Answer

A common in‑place solution uses a two‑pointer technique. Keep a write index that points to the next position where a non‑zero element should go. Iterate through the list with a read index. Whenever you encounter a non‑zero value, assign it to the write index and increment the write index. After the loop, all non‑zeros are at the front in their original order, and the write index marks the boundary. Fill the remaining positions from the write index to the end with zeros. This runs in O(n) time and uses O(1) extra space. In Python, you can implement it as:

def move_zeros(nums):
    write = 0
    for read in range(len(nums)):
        if nums[read] != 0:
            nums[write] = nums[read]
            write += 1
    for i in range(write, len(nums)):
        nums[i] = 0

The algorithm preserves the relative order of non‑zero elements (stable) and is efficient for large lists.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500