Prepin
Log in

Shift all zeros in an array to the end.

Approach / Explanation

This question pertains to arrays within data structures and requires knowledge of how to manipulate elements in an array. The task involves relocating all zeros in the array to the end while preserving the original order of the other elements. To approach this problem, it’s effective to follow a step-by-step process: Start with a variable count initialized to 0, which will keep track of the number of non-zero elements. Loop through the array; for each non-zero element encountered, place it at the position indicated by count and then increment count . Once this step is complete, count will indicate the index of the first zero element (or the end of the array if there are no zeros). Use another loop to go to the end of the array and fill in the remaining positions with zeros.

Suggested Answer

Below is an example of Python code that illustrates the steps outlined earlier: def move_zeros_to_end ( arr ) : count = 0 # Steps 1 and 2: Loop through the array, replacing the number at the 'count' index with any non-zero elements found for i in range ( len ( arr ) ) : if arr [ i ] != 0 : arr [ count ] = arr [ i ] count += 1 # Steps 3 and 4: After moving all non-zero elements to the front, set 'count' as the index of the first zero and fill the rest of the array with zeros. while count < len ( arr ) : arr [ count ] = 0 count += 1 return arr

Alternative Answer

Here is an example of Javascript code that utilizes a similar technique: function moveZerosToEnd ( arr ) { let count = 0 ; for ( let i = 0 ; i < arr . length ; i ++ ) { // If the element is not 0, copy its value to the current 'count' position and increase 'count' if ( arr [ i ] !== 0 ) { arr [ count ] = arr [ i ] ; count ++ ; } } // Fill the remaining part of the array with 0's for ( let i = count ; i < arr . length ; i ++ ) { arr [ i ] = 0 ; } return arr ; }

Question Details

Difficulty & Category

Medium
algorithms

Companies

Meta (Facebook)

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

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