ProgrammingHardTCS NQT · Accenture

What is printed?

What is printed?
def dedupe(a):
    if not a:
        return 0
    k = 1
    for i in range(1, len(a)):
        if a[i] != a[k - 1]:
            a[k] = a[i]
            k += 1
    return k
arr = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
n = dedupe(arr)
print(n, arr[:n], arr[n:])
  1. A. 5 [0, 1, 2, 3, 4] [2, 3, 3, 4, 4]
  2. B. 5 [0, 1, 2, 3, 4] [2, 2, 3, 3, 4]
  3. C. 4 [0, 1, 2, 3] [2, 3, 3, 4, 4]
  4. D. 5 [0, 1, 2, 3, 4] [0, 0, 1, 1, 1]

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

The write index k moves only when a new value appears, and cells after k keep their old contents. So arr[5:] still shows 2, 2, 3, 3, 4 after the in-place pass.

More Python Programming questions

Exams that ask this topic