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[5] = {1, 3, 5, 4, 2}, n = 5
Integer i = n - 2
while (i >= 0 AND a[i] >= a[i + 1]) i = i - 1
if (i >= 0)
Integer j = n - 1
while (a[j] <= a[i]) j = j - 1
swap(a[i], a[j])
end if
reverse a[i + 1 .. n - 1]
Print a[0], a[1], a[2], a[3], a[4]- A. 1 5 3 4 2
- B. 1 4 5 3 2
- C. 1 3 5 2 4
- D. 1 4 2 3 5
Correct answer: D. 1 4 2 3 5
This is 'next permutation'. The rightmost rise is 3 < 5 (i = 1); the smallest larger value to its right is 4; swapping gives 1 4 5 3 2, and reversing the tail gives 1 4 2 3 5 — the next arrangement in dictionary order.
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[9] = {3, 2, 3, 1, 2, 4, 5, 5, 6}, k = 4 sort a…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Function canSplit(Integer a[]…
- What will be the output of the following pseudocode? Integer g[3][3] = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}} for (each i from 0 to 2) for…
- What will be the output of the following pseudocode? Function rob(Integer a[], Integer lo, Integer hi) Integer inc = 0, exc = 0, t for…
- What will be the output of the following pseudocode? Integer cost[3] = {10, 15, 20} Integer a = 0, b = 0, c // cheapest cost to stand on…
- What will be the output of the following pseudocode? Pair iv[11] = {(1,4), (3,5), (0,6), (5,7), (3,9), (5,9), (6,10), (8,11), (8,12)…