ProgrammingModerateTCS NQT · Accenture

Array a = [1, 1, 2, 2, 2, 3, 4, 4] is sorted. The two-pointer procedure below removes duplicates in place (keeping one copy of each value) and prints the new length. What is printed?

Array a = [1, 1, 2, 2, 2, 3, 4, 4] is sorted. The two-pointer procedure below removes duplicates in place (keeping one copy of each value) and prints the new length. What is printed?
if n == 0 then print 0
w = 0
for r = 1 to n - 1
    if a[r] != a[w] then w = w + 1; a[w] = a[r]
end for
Print w + 1
  1. A. 8
  2. B. 4
  3. C. 3
  4. D. 5

Correct answer: B. 4

The distinct values 1, 2, 3, 4 give a new length of 4. Printing the original length 8, the write index w (which is one less), and the distinct count plus one each give other values.

More Pseudocode and Code Tracing questions

Exams that ask this topic