Tracking two extremes at once — Pseudocode Aptitude Question
Tracking two extremes at once: The array A is 0-indexed. What is printed? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 90 seconds
Question
The array A is 0-indexed. What is printed?
Integer A[0..5], i, mn, mx
Set A = {14, 3, 27, 3, 19, 8}
Set mn = A[0]
Set mx = A[0]
For i = 1 to 5
If A[i] < mn Then
Set mn = A[i]
End If
If A[i] > mx Then
Set mx = A[i]
End If
End For
Print mx - mnOptions
- 11
- 16
- 24
- 30
Show the answer and the worked solution
Correct answer: C. 24
Worked solution
- mn and mx both start at A[0] = 14.
- The smallest element in the array is 3, so mn ends at 3.
- The largest element is 27, so mx ends at 27.
- The value printed is 27 - 3 = 24.
Answer: 24.
The idea
Seeding both trackers from the first element is what makes a single pass correct for any data, positive or negative. The routine as a whole computes the range of the array.
Shortcut. mx − mn is just the largest minus the smallest element, so skip the loop: 27 − 3 = 24. The repeated 3 changes nothing.
Common trap. 11 is 14 − 3, what a candidate gets by leaving mx at its seed A[0] = 14 and letting only mn move.