Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Move all zero readings to the end of the array in place while keeping the order of the non-zero readings.

Problem: Move all zero readings to the end of the array in place while keeping the order of the non-zero readings.
def move_zeros(a):
    w = 0
    for x in a:
        if x != 0:
            a[w] = x; w += 1
    for i in range(w, len(a)):
        a[i] = 0
    return a
print(move_zeros([0, 5, 0, 0, 3, 8, 0, 1]))
What is printed?
  1. A. [0, 0, 0, 0, 5, 3, 8, 1]
  2. B. [5, 3, 8, 1]
  3. C. [1, 8, 3, 5, 0, 0, 0, 0]
  4. D. [5, 3, 8, 1, 0, 0, 0, 0]

Correct answer: D. [5, 3, 8, 1, 0, 0, 0, 0]

A write pointer w copies each non-zero value to the next free slot (stable), then the tail is filled with zeros. Order 5, 3, 8, 1 is preserved. O(n) time, O(1) extra space; swapping from both ends would be O(n) too but breaks the relative order.

More Coding Interview Problems questions

Exams that ask this topic