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- A. 8
- B. 4
- C. 3
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Array a = [4, 9, 1, 7, 3]. The procedure below finds the sum of all elements that are greater than the mean of the array. What is printed?…
- Array a = [2, 5, 7, 10, 12] is searched for the number of elements less than or equal to 7 by a binary search that finds the boundary…
- The procedure below counts the pairs (i, j) with i < j and a[i] + a[j] = 8, for the array a = [1, 5, 3, 3, 7, 4, 6, 2]. What is printed?…
- Array a = [4, 4, 6, 1, 1] has a value appearing more than once. The procedure below counts the values that appear exactly twice. What is…
- Array a = [5, -3, 5] is treated as circular. The maximum circular subarray sum (a contiguous block that may wrap around the end) is found…
- Sorted array a = [1, 3, 6, 6, 6, 9]. The lower-bound binary search below finds the first index whose value is at least x = 6. What is…