OA. free
Free
Accenture Core Computer Science Core Computer Science Medium

Q11 /20 There is a staircase of n steps and you are on the bottom of the staircase, on the...

Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.

There is a staircase of n steps and you are on the bottom of the staircase, on the 0-th step. You can go up any of 1, 2, or 3 steps at a time. Let us consider the problem of counting the number of step-taking patterns that will put you on exactly the n-th step from the bottom.

For instance, if there are n = 4 steps, there are 7 patterns as follows. Each number is the number of steps you take at one time.

  • 1, 1, 1, 1.
  • 2, 1, 1.
  • 1, 2, 1.
  • 1, 1, 2.
  • 2, 2.
  • 1, 3.
  • 3, 1.

For this problem, you implemented a function solve as follows.
Note that all the variables are multiple precision integers.

function rec(i):
  if i == 0:
    return 1
  else:
    ans = 0
    if i >= 1:
      ans += rec(i-1)
    if i >= 2:
      ans += rec(i-2)
    if i >= 3:
      ans += rec(i-3)
    return ans

function solve(n):
  return rec(n)

However, the program is too slow and it does not return the answer for n = 1000 even if you wait a whole day. You want to speed up the program so that it returns the answer in one second even if n is in the range between 1000 and 10000.

Which one of the following correctly states the reason the function is too slow and the solution to fix the slowness?

Choose one option.
Show answer & explanation
Answer: C. Although rec(i) always returns the same value, it is recomputed each time it is called due to overlapping subproblems. Store computed values and reuse them (memoization) to speed up the program.

The function exhibits exponential time complexity O(3^n) because it recalculates the same subproblems repeatedly. For example, rec(5) calls rec(4), rec(3), and rec(2), but rec(4) also calls rec(3) and rec(2), leading to massive redundant computation. Memoization (storing and reusing previously computed values) reduces this to O(n) time, making it feasible for n = 1000. Options A and B are incorrect: the if statements are not the bottleneck, and multiple precision integers are actually needed since the result grows exponentially and would overflow standard integer types.

Step-by-step Derivation:
Time complexity analysis:

  • Without memoization: T(n) = T(n-1) + T(n-2) + T(n-3) → O(3^n) ≈ 3^1000 ≈ 10^477 operations (infeasible)
  • With memoization: Each rec(i) computed once, cached result reused → O(n) operations ≈ 1000 operations (feasible in <1ms)

Example for n=4 without memoization:
rec(4) calls: rec(3), rec(2), rec(1)
rec(3) calls: rec(2), rec(1), rec(0) [rec(2) computed again]
rec(2) calls: rec(1), rec(0) [rec(1) computed again]

With memoization, rec(2) and rec(1) are computed once and reused, reducing redundant calls exponentially.