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[6] = {-1, 0, 1, 2, -1, -4}
sort a // {-4, -1, -1, 0, 1, 2}
Integer c = 0
for (each i from 0 to 3)
if (i > 0 AND a[i] == a[i - 1]) continue
Integer l = i + 1, r = 5
while (l < r)
Integer s = a[i] + a[l] + a[r]
if (s < 0) l = l + 1
else if (s > 0) r = r - 1
else
c = c + 1
while (l < r AND a[l] == a[l + 1]) l = l + 1
l = l + 1
r = r - 1
end if
end while
end for
Print c- A. 3
- B. 1
- C. 2
- D. 4
Correct answer: C. 2
The sorted two-pointer scan counts DIFFERENT triples with sum 0, skipping repeated values: {−1, −1, 2} and {−1, 0, 1}. c = 2 (the two −1's do not create a second {−1, 0, 1}).
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? Integer a[3] = {5, -3, 5} Integer total = 0, curMax = 0, bestMax = a[0], curMin = 0…
- What will be the output of the following pseudocode? Integer n = 5, spaces = 0, stars = 0 for (each i from 1 to n) for (each j from 1 to n…
- What will be the output of the following pseudocode? (~ is bitwise NOT, & is AND, | is OR, >> is right shift) Integer x = 11 Integer a =…
- What will be the output of the following pseudocode? (^ is XOR, & is AND) Integer a = 10, b = 20, x, flips = 0 x = a ^ b while (x > 0) x =…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Function f(Integer n) if (n <=…
- What will be the output of the following pseudocode? Integer calls = 0 Procedure f(Integer n) calls = calls + 1 for (each i from 1 to n…