Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

What is printed? (reverse a sublist of a linked list between positions m and n, 1-based)

What is printed? (reverse a sublist of a linked list between positions m and n, 1-based)
def rev_between(a, m, n):
    a = a[:]
    a[m - 1:n] = a[m - 1:n][::-1]
    return a
print(rev_between([1, 2, 3, 4, 5, 6], 2, 5), rev_between([7, 8], 1, 2))
  1. A. [1, 5, 4, 3, 2, 6] [8, 7]
  2. B. [1, 4, 3, 2, 5, 6] [8, 7]
  3. C. [1, 5, 4, 3, 2, 6] [7, 8]
  4. D. [5, 4, 3, 2, 1, 6] [8, 7]

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

Positions 2..5 (values 2, 3, 4, 5) are reversed in place, the rest untouched. In a real linked list this is done in one pass with a dummy head: find node m − 1, then repeatedly move the next node to the front of the sublist – O(n), O(1) space.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic