ProgrammingHardTCS NQT · Accenture
Two sorted arrays a = [1, 4, 7] and b = [2, 3, 8, 9] are merged by the two-pointer procedure below, and the procedure prints the 4th element (1-based) of the merged array. What is printed?
Two sorted arrays a = [1, 4, 7] and b = [2, 3, 8, 9] are merged by the two-pointer procedure below, and the procedure prints the 4th element (1-based) of the merged array. What is printed?
i = 0; j = 0; out = empty
while i < len(a) and j < len(b)
if a[i] <= b[j] then append a[i]; i++ else append b[j]; j++
append the remaining elements
Print out[3]- A. 3
- B. 7
- C. 8
- D. 4
Correct answer: D. 4
Merged order is 1, 2, 3, 4, 7, 8, 9, so the 4th element is 4. Printing index 2 gives 3, sorting and taking index 4 gives 7, and the 6th element is 8.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The procedure below repeatedly replaces x by the sum of its decimal digits, starting from x = 2^15, until x is a single digit, and prints…
- An array holds the values [3, 0, 2, 0, 1] (positions 0 to 4). The procedure below computes the water trapped above each position as…
- The Fibonacci sequence 1, 1, 2, 3, 5, ... is generated by the loop below, and the procedure prints how many terms are less than or equal…
- The string "aabcccdddd" is compressed by the procedure below, which replaces each run of equal letters by the letter followed by the run…
- The procedure below scans the word "leetcode" from the left and prints the index of the first letter that occurs exactly once in the word…
- The procedure below counts the integers n with 1 <= n <= 60 that are not divisible by 2, 3 or 5 (coprime to 30). What is printed? count =…