The GATE Grind

GATE 2024 DA – Question 39

Programming, Data Structures and Algorithms · Programming in Python · 2 marks · Multiple choice

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. [1, 1, 2, 3, 4]
  2. [1, 1, 2, 3, 3]
  3. [1, 1, 2, 1, 2]
  4. [1, 1, 2, 1, 5]

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (C) [1, 1, 2, 1, 2]

Explanation

$S[1] = 1$. For $i = 2$: $6 \le 3$ is false, so $S[2] = 1$. For $i = 3$: $3 \le 5$ is true, so $S[3] = 1 + S[2] = 2$. For $i = 4$: $5 \le 4$ is false, so $S[4] = 1$. For $i = 5$: $4 \le 10$ is true, so $S[5] = 1 + S[4] = 2$. The result is $[1, 1, 2, 1, 2]$.