Prepin
Log in

Shift all zeros in the array to the end.

Approach / Explanation

This interview question involves the fundamental manipulation of data structures, particularly arrays. You are provided with an array of numbers that contains some zeros. The objective is to create a function or method that rearranges the array so that all the zeros are moved to the end, while keeping the order of the non-zero elements unchanged. This is a frequently encountered issue in computer science and software engineering. It may present various forms or require different solutions based on the programming language or additional requirements. To address this problem, consider the following important points: Be familiar with how to iterate over an array. Understand how to swap elements within an array. Grasp the concept of preserving the relative order of elements in an array.

Suggested Answer

A potential solution to this issue involves using a pointer to monitor the location where the next non-zero element should be inserted. Begin at the start of the array; if the current element is non-zero, move it to the tracked position and advance the position tracker. Below is a Python implementation of this approach: def moveZeros ( arr ) : pos = 0 for i in range ( len ( arr ) ) : if arr [ i ] != 0 : arr [ pos ] = arr [ i ] pos += 1 while pos < len ( arr ) : arr [ pos ] = 0 pos += 1 return arr This code snippet starts the position counter at 0. It goes through the array, moving each non-zero value to the current position and increasing the counter. Once the loop finishes, any remaining positions are filled with zeros.

Alternative Answer

Another approach involves utilizing a two-pointer technique: one pointer is used to traverse the array, while the other pointer only advances when a non-zero element is encountered. Below is a JavaScript example demonstrating this solution: function moveZeros ( arr ) { let index = 0 ; for ( let i = 0 ; i < arr . length ; i ++ ) { if ( arr [ i ] != 0 ) { arr [ index ++ ] = arr [ i ]; } } for ( let i = index ; i < arr . length ; i ++ ) { arr [ i ] = 0 ; } return arr ; } In this JavaScript function, the index variable acts as a pointer indicating where the next non-zero number should be placed. The function iterates through the array, and whenever it identifies a non-zero number, it assigns that number to the current index location and then increments the index. Subsequently, all remaining positions in the array are filled with zeros.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.