GATE CS 2022 · Asymptotic Analysis & Recurrences

MCQ · 1 mark · Problem PROG-DIVC-0172

Consider the problem of reversing a singly linked list. For example, the list \(1\rightarrow2\rightarrow3\rightarrow4\rightarrow5\rightarrow6\rightarrow\text{NULL}\) should become \(6\rightarrow5\rightarrow4\rightarrow3\rightarrow2\rightarrow1\rightarrow\text{NULL}\).Which one of the following statements is TRUE about the time complexity of algorithms that solve the above problem in \(O(1)\) space?
  1. A
    The best algorithm for the problem takes \(\theta(n)\) time in the worst case.
  2. B
    The best algorithm for the problem takes \(\theta(n \log n)\) time in the worst case.
  3. C
    The best algorithm for the problem takes \(\theta(n^2)\) time in the worst case.
  4. D
    It is not possible to reverse a singly linked list in O(1) space.

Solve it on GATE DA practice →More Searching & Sorting Algorithms problems

Show the worked solution\[\boxed{\text{One pass with three pointers (previous, current, next) reverses every link}}\]Walking the list once and pointing each node back to its predecessor uses \(O(1)\) extra space and \(\Theta(n)\) time. No algorithm can do better in the worst case, since each of the \(n\) links must be changed.Answer: A

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com