Data Structures & AlgorithmsModerateWipro · Accenture pattern

What is printed? (move zeros to the end keeping order)

What is printed? (move zeros to the end keeping order)
a = [0, 1, 0, 3, 12, 0, 5]
w = 0
for r in range(len(a)):
    if a[r] != 0:
        a[w], a[r] = a[r], a[w]
        w += 1
print(a, w)
  1. A. [1, 3, 12, 5, 0, 0, 0] 3
  2. B. [1, 3, 12, 5, 0, 0, 0] 4
  3. C. [1, 3, 5, 12, 0, 0, 0] 4
  4. D. [5, 12, 3, 1, 0, 0, 0] 4

Correct answer: B. [1, 3, 12, 5, 0, 0, 0] 4

Swapping each non-zero into the write position keeps the relative order of the non-zeros and pushes zeros back. w ends at the number of non-zeros (4). O(n), O(1) extra space, one pass.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic