ProgrammingHardTCS NQT · Accenture

The array [0, 1, 0, 3, 12] has its zeros moved to the end while keeping the order of the other values, by a two-pointer pass that writes non-zero values forward. What is the resulting array printed as a list of values?

The array [0, 1, 0, 3, 12] has its zeros moved to the end while keeping the order of the other values, by a two-pointer pass that writes non-zero values forward. What is the resulting array printed as a list of values?
w = 0
for r = 0 to n - 1
    if a[r] != 0 then a[w] = a[r]; w = w + 1
fill positions w..n-1 with 0
Print a
  1. A. 0 0 1 3 12
  2. B. 1 3 12 0 0
  3. C. 1 3 12
  4. D. 1 3 12 3 12

Correct answer: B. 1 3 12 0 0

The non-zero values keep their order and move forward, so the result is 1 3 12 0 0. Sorting puts zeros first, dropping zeros shortens the output, and not filling the tail leaves stale values from the original array.

More Pseudocode and Code Tracing questions

Exams that ask this topic