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- A. 0 0 1 3 12
- B. 1 3 12 0 0
- C. 1 3 12
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- For the array a = [7, 2, 4, 9, 1, 5] the procedure below computes the sum of the minimum of every contiguous window of length 2 (windows…
- The array a = [3, 1, 2, 4] is sorted in ascending order by selection sort, and the procedure below counts the total number of element…
- Array a = [1, 2, 3, 5, 4] is checked by the procedure below, which performs bubble sort with an early-exit flag (a pass with no swaps ends…
- Array a = [3, 8, 5, 6, 7] has its odd values summed by the procedure below, and the result is printed. What is printed? total = 0 for each…
- Array a = [0, 2, 2, 3, 5]. The procedure below counts the positions i (0-based) where a[i] equals i. What is printed? count = 0 for i = 0…
- For the array a = [1, 2, 3, 4, 5, 6], the procedure below counts the contiguous subarrays of length 3 whose sum is divisible by 3. What is…