Data Structures & AlgorithmsModerateTCS Digital · Infosys SP
Partition a linked list around x: all nodes with value < x come first, then the rest, each part keeping its original relative order. What is printed?
Partition a linked list around x: all nodes with value < x come first, then the rest, each part keeping its original relative order. What is printed?
def partition(h, x):
ls = lt = N(0); gs = gt = N(0)
while h:
if h.v < x: lt.nx = h; lt = h
else: gt.nx = h; gt = h
h = h.nx
gt.nx = None
lt.nx = gs.nx
return ls.nx
print(vals(partition(build([18, 1, 17, 10, 14, 16, 19, 11]), 11)))- A. [18, 17, 14, 16, 19, 11, 10]
- B. [1, 10, 11, 18, 17, 14, 16, 19]
- C. [10, 1, 18, 17, 14, 16, 19, 11]
- D. [1, 10, 18, 17, 14, 16, 19, 11]
Correct answer: D. [1, 10, 18, 17, 14, 16, 19, 11]
Two dummy-headed chains collect < x and ≥ x nodes in scan order, then the first chain's tail points to the second chain. Setting gt.nx = None prevents a cycle. Output: [1, 10, 18, 17, 14, 16, 19, 11].
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
- Two ways of finding the middle of a linked list with slow/fast pointers. What is printed? python h = build([25, 47, 35, 52, 83, 28, 17…
- Evaluate the postfix expression 3 5 4 6 1 ÷ − + + (all divisions are exact). What is its value, and what is the maximum number of operands…
- Count palindromic substrings by expanding around all 2n − 1 centres, and also count DISTINCT palindromic substrings. What is printed?…
- Top-down merge sort (split at mid = n // 2, recurse, then merge, stopping comparisons when one side runs out) sorts [33, 53, 13, 42, 11…
- Assertion (A): Removing duplicates from a sorted array can be done in place in O(n) time with two pointers. Reason (R): In a sorted array…
- Assertion (A): Quick sort with the last element as pivot takes Θ(n²) time on an array that is already sorted. Reason (R): On sorted input…