ProgrammingVery hardAmazon OA · Goldman Sachs OA
What will be the output of the following pseudocode? (Arrays are indexed from 0)
What will be the output of the following pseudocode? (Arrays are indexed from 0)
Integer a[4] = {3, 4, -1, 1}, n = 4
for (each i from 0 to n - 1)
while (a[i] >= 1 AND a[i] <= n AND a[a[i] - 1] != a[i])
swap(a[i], a[a[i] - 1])
end while
end for
Integer ans = n + 1
for (each i from 0 to n - 1)
if (a[i] != i + 1)
ans = i + 1
break
end if
end for
Print ans- A. 5
- B. 2
- C. 1
- D. 4
Correct answer: B. 2
The swaps put each value v in 1..n at index v − 1, giving {1, −1, 3, 4}. The first index whose value is wrong is 1, so the smallest missing positive is 2.
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? (Arrays are indexed from 0) Integer a[3] = {1, 3, 8}, b[4] = {2, 7, 9, 10}, c[7]…
- What will be the output of the following pseudocode? Integer m[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}} for (each i from 0 to…
- What will be the output of the following pseudocode? (/ is integer division) String tok[9] = {"-", "", "+", "2", "3", "4", "/", "8", "2"}…
- What will be the output of the following pseudocode? Stack s = empty, mins = empty Procedure push2(Integer x) push(s, x) if (mins is empty…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer a[8] = {1, 3, -1, -3, 5, 3, 6, 7}, k = 3 Deque d…
- What will be the output of the following pseudocode? (& is AND, >> is right shift) Integer x = 23, t = 0 while ((x & 1) == 1) t = t + 1 x…