ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode (recursively reversing a list)?

What will be the output of the following pseudocode (recursively reversing a list)?
Function reverseList(List lst)
    if (length(lst) <= 1)
        return lst
    end if
    return reverseList(lst[1 .. end]) + [lst[0]]
End Function

Print reverseList({1, 2, 3, 4, 5})
  1. A. [5, 4, 3, 2, 1]
  2. B. [1, 2, 3, 4, 5]
  3. C. [5, 1, 2, 3, 4]
  4. D. [1, 5, 4, 3, 2]

Correct answer: A. [5, 4, 3, 2, 1]

Each call peels off the first element and appends it AFTER the recursively reversed remainder, building the list in fully reversed order: [5, 4, 3, 2, 1].

More Pseudocode and Code Tracing questions

Exams that ask this topic