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))- A. [1, 5, 4, 3, 2, 6] [8, 7]
- B. [1, 4, 3, 2, 5, 6] [8, 7]
- C. [1, 5, 4, 3, 2, 6] [7, 8]
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (min-heap array after inserts) python import heapq h = [] for x in [9, 4, 7, 1, 8, 2]: heapq.heappush(h, x) print(h…
- What is printed? (queue using a fixed array without wrap-around) python N = 4; q = [None] N; front = rear = 0; log = [] def enq(x): global…
- A warehouse scores a shelf by adding, over every contiguous run of boxes, the weight of the lightest box in the run. Two monotonic-stack…
- A monotonic deque reports the maximum of every window of 3 readings and counts deque removals. What is printed? python from collections…
- atmost(s, k) counts substrings with at most k distinct letters using a sliding window and a frequency map. What is printed? python def…
- A KMP prefix (failure) table and an overlapping-occurrence counter. What is printed? python def prefix(p): pi = [0] len(p) for i in…