IAE Academy

GATE 2024 DA Q.39: solution and answer

GATE 2024 · DAQ.39 · 2 marks · MCQ

Consider the function computeS(X) whose pseudocode is given below:

computeS(X)
S[1] ← 1
for i ← 2 to length(X)
   S[i] ← 1
   if X[i-1] ≤ X[i]
         S[i] ← S[i] + S[i-1]
   end if
end for
return S

Which ONE of the following values is returned by the function computeS(X) for X = [6, 3, 5, 4, 10]?

  1. (A)

    [1, 1, 2, 3, 4]

  2. (B)

    [1, 1, 2, 3, 3]

  3. (C)

    [1, 1, 2, 1, 2]

  4. (D)

    [1, 1, 2, 1, 5]

See the question in the paper

Answer and solution

ANSWER

The function returns [1, 1, 2, 1, 2], which is option (C).

Official answer: CSource: Official answer key, GATE 2024 DA (IISc Bengaluru)

  1. The pseudo-code is:

    computeS(X)
    S[1] ← 1
    for i ← 2 to length(X)
       S[i] ← 1
       if X[i-1] ≤ X[i]
             S[i] ← S[i] + S[i-1]
       end if
    end for
    return S

    For each position , S[i] is first set to 1. It grows by S[i-1] only when X[i-1] <= X[i]. So S[i] is the length of the run of non-decreasing consecutive elements that ends at position . It restarts at 1 whenever X[i-1] > X[i].

  2. Input: (1-indexed), so length(X) = 5. Start with .

  3. : S[2] = 1. The test X[1] <= X[2] is , which is false. So .

  4. : S[3] = 1. The test X[2] <= X[3] is , which is true. So .

  5. : S[4] = 1. The test X[3] <= X[4] is , which is false. So .

  6. : S[5] = 1. The test X[4] <= X[5] is , which is true. So .

  7. The function returns , which is option (C).

KEY IDEA

S[i] is the length of the non-decreasing run ending at position i. The comparison is X[i-1] <= X[i], and S[i] is reset to 1 whenever it fails. The value added is S[i-1], which is the previous position's already-computed run length.

WATCH OUT FOR

Using S[i-1] + 1 unconditionally, or counting a run only when the sequence strictly increases, gives the wrong array. Another slip is forgetting that S[i] restarts at 1 after every descent (6 to 3, and 5 to 4). That slip leads to the cumulative-looking distractors in options (A), (B) and (D).

From the GATE 2024 DA paper. Every question of this paper · Download the full paper · All 10 Python questions, with notes

More Python questions