WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Coding Interview Essentials Β· Array and String Problems Β· question 40 of 120

How would you move all zeros in an array to the end?

πŸ“• Buy this interview preparation book: 120 Coding Interview Essentials questions & answers β€” PDF + EPUB for $5

Moving all zeros in an array to the end can be achieved through an algorithmic technique called "two-pointer technique". Following the steps below will accomplish this:

1. Initialize two pointers β€˜iβ€˜ and β€˜jβ€˜ to 0.

2. Run a while-loop until β€˜iβ€˜ reaches the end of the array.

3. If the array[i] is non-zero, swap the array[i] and array[j] and increment both β€˜iβ€˜ and β€˜jβ€˜.

4. If the array[i] is 0, increment β€˜iβ€˜ only.

Here’s corresponding Python code and explanation:

def move_zeros_to_end(arr):
    n = len(arr)

    j = 0  # Count of non-zero elements
    for i in range(n):
        # If element at index i is non-zero, then replace the element
        # at index j with this element
        if arr[i] != 0:
            # Swap
            arr[j], arr[i] = arr[i], arr[j]
            # increment count of non-zero elements
            j += 1

    return arr

You could call the function with your array, like so:

arr = [1, 0, 2, 0, 3, 0, 0, 4, 5]
print(move_zeros_to_end(arr))

This would result in:

Output: [1, 2, 3, 4, 5, 0, 0, 0, 0]

The time complexity of the above algorithm is O(n) because the array is traversed once only. The space complexity is O(1), no extra space is used. Plus, this is an in-place algorithm which means original order of non-zero elements is maintained.

Here’s a step-by-step illustration of how the algorithm works for the following input: [1, 0, 2, 0, 3, 0, 0, 4, 5] i and j both start at index 0.

arr: [1, 0, 2, 0, 3, 0, 0, 4, 5]
         i
         j

Since β€˜arr[i]β€˜ is not zero, β€˜arr[j]β€˜ and β€˜arr[i]β€˜ are swapped and both β€˜iβ€˜ and β€˜jβ€˜ are incremented. Now our array and pointers both look like this:

arr: [1, 0, 2, 0, 3, 0, 0, 4, 5]
             i
             j

Since β€˜arr[i]β€˜ is zero, only the β€˜iβ€˜ pointer will be incremented and thus the following state:

arr: [1, 0, 2, 0, 3, 0, 0, 4, 5]
                 i
             j

The process continues similarly, with β€˜iβ€˜ and β€˜jβ€˜ pointers incrementing under different conditions until β€˜iβ€˜ reaches the end of the array, with final result of β€˜[1, 2, 3, 4, 5, 0, 0, 0, 0]β€˜.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview β€” then scores it.
πŸ“ž Practice Coding Interview Essentials β€” free 15 min
πŸ“• Buy this interview preparation book: 120 Coding Interview Essentials questions & answers β€” PDF + EPUB for $5

All 120 Coding Interview Essentials questions Β· All topics