ProgrammingHardTCS NQT · Accenture pattern
What will be the output of the following pseudocode (moving all zeros to the end while preserving the relative order of non-zero elements, in place)? (Arrays are indexed from 0.)
What will be the output of the following pseudocode (moving all zeros to the end while preserving the relative order of non-zero elements, in place)? (Arrays are indexed from 0.)
Integer arr[5] = {0, 1, 0, 3, 12}
Integer write = 0
for (each read from 0 to 4)
if (arr[read] != 0)
swap(arr[write], arr[read])
write = write + 1
end if
end for
Print arr- A. [1, 3, 12, 0, 0]
- B. [0, 0, 1, 3, 12]
- C. [1, 0, 3, 0, 12]
- D. [0, 1, 3, 12, 0]
Correct answer: A. [1, 3, 12, 0, 0]
Every non-zero element is swapped forward into the 'write' position in order encountered (1, 3, 12), pushing the zeros naturally to the back: [1, 3, 12, 0, 0].
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode (length of the longest substring without repeating characters, sliding window)?…
- What will be the output of the following pseudocode (number of bits needed to represent n in binary)? Function bitsNeeded(Integer n)…
- What will be the output of the following pseudocode (counting trailing zero bits in the binary representation of n)? (All variables are…
- What will be the output of the following pseudocode (recursively reversing a list)? Function reverseList(List lst) if (length(lst) <= 1)…
- What will be the output of the following pseudocode (counting set bits for every number from 0 to n using a DP recurrence)? (>> is right…
- What will be the output of the following pseudocode (reversing the order of words in a sentence)? String s = "the sky is blue" List words…