ProgrammingVery hardCAT · MBA placement
Sorted array a = [1, 2, 3, 5, 8, 9] and limit L = 10. Count the pairs of distinct positions i < j with a[i] + a[j] <= L using two pointers: if a[i] + a[j] <= L, all pairs (i, k) with i <= k < j are valid, so add j - i and move i up; otherwise move j down. What is printed?
Sorted array a = [1, 2, 3, 5, 8, 9] and limit L = 10. Count the pairs of distinct positions i < j with a[i] + a[j] <= L using two pointers: if a[i] + a[j] <= L, all pairs (i, k) with i <= k < j are valid, so add j - i and move i up; otherwise move j down. What is printed?
i = 0; j = n - 1; count = 0
while i < j
if a[i] + a[j] <= L then count = count + (j - i); i = i + 1
else j = j - 1
end while
Print count- A. 7
- B. 9
- C. 3
- D. 10
Correct answer: B. 9
The valid pairs are (1,2), (1,3), (1,5), (1,8), (1,9), (2,3), (2,5), (2,8), (3,5), which is 9. A strict inequality drops the pairs summing to exactly 10, counting one pair per i undercounts, and adding a stray 1 is an off-by-one error.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The string s = "aaabbbcc" is cut down so that no two adjacent letters are equal, by deleting characters. The greedy keeps a character when…
- A binary string s = "1100101" is to be made alternating. Two targets are possible: "0101010..." and "1010101...", each the same length as…
- Count how many copies of the word BALLOON can be formed from the letters of "lloolldnaubbalo" (each letter used at most once per copy)…
- Children have ratings r = [1, 0, 2, 2, 1]. Each child gets at least one candy, and a child with a higher rating than a neighbour gets more…
- Let x = 0. For i from 1 to 10: if i mod 3 == 0 then x = x + i, otherwise x = x - 1. What is printed? x = 0 for i = 1 to 10 if i mod 3 == 0…
- A rope of length L is cut into two parts of lengths floor(L/2) and L - floor(L/2) whenever its length is 2 or more; the cost of a cut is…