ProgrammingHardInfosys · Cognizant
Array a = [1, 2, 1, 2, 3, 2, 1, 1] is processed left to right. The procedure below finds the length of the longest run of equal consecutive values. What is printed?
Array a = [1, 2, 1, 2, 3, 2, 1, 1] is processed left to right. The procedure below finds the length of the longest run of equal consecutive values. What is printed?
best = 1; run = 1
for i = 1 to n - 1
if a[i] == a[i-1] then run = run + 1 else run = 1
best = max(best, run)
end for
Print best- A. 2
- B. 7
- C. 3
- D. 1
Correct answer: A. 2
The only repeated pair is 1 1 at the end, so the longest run is 2. Counting changes instead of equal neighbours gives 7 or a different run length, counting distinct values gives 3, and starting the run at 0 gives 1.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Array a = [1, 1, 2, 2, 2, 3, 4, 4] is sorted. The two-pointer procedure below removes duplicates in place (keeping one copy of each value)…
- Array a = [4, 9, 1, 7, 3]. The procedure below finds the sum of all elements that are greater than the mean of the array. What is printed?…
- Array a = [2, 5, 7, 10, 12] is searched for the number of elements less than or equal to 7 by a binary search that finds the boundary…
- The procedure below counts the pairs (i, j) with i < j and a[i] + a[j] = 8, for the array a = [1, 5, 3, 3, 7, 4, 6, 2]. What is printed?…
- Array a = [4, 4, 6, 1, 1] has a value appearing more than once. The procedure below counts the values that appear exactly twice. What is…
- Array a = [5, -3, 5] is treated as circular. The maximum circular subarray sum (a contiguous block that may wrap around the end) is found…