Home › Interview Questions › How would you move all zeros to the end of an arra…

How would you move all zeros to the end of an array using a two-pointer approach in one pass, achieving O(n) time and O(1) space?

🟡 Medium Coding Junior level
1Times asked
Sep 2026Last seen
Sep 2026First seen

💡 Model Answer

You can solve this in a single pass by maintaining two pointers: a read pointer that scans the array and a write pointer that tracks the position to place the next non-zero element. Initialize write = 0. For each index read from 0 to n-1, if nums[read] != 0, swap nums[write] and nums[read] (or assign nums[write] = nums[read] and set nums[read] = 0 if you want to avoid swapping zeros). Then increment write. This keeps the relative order of non-zero elements and pushes zeros to the end. Time complexity O(n), space O(1).

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