AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumarraystracing

~90s

Tracking two extremes at once

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 - mn
Show the answer and the worked solution

Correct answer: C.

24

Worked solution

  1. mn and mx both start at A[0] = 14.
  2. The smallest element in the array is 3, so mn ends at 3.
  3. The largest element is 27, so mx ends at 27.
  4. 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.

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.

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 - mn

Options

  1. 11
  2. 16
  3. 24
  4. 30
Show the answer and the worked solution

Correct answer: C. 24

Worked solution

  1. mn and mx both start at A[0] = 14.
  2. The smallest element in the array is 3, so mn ends at 3.
  3. The largest element is 27, so mx ends at 27.
  4. 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.

All Pseudocode questions · placement mock tests