Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: Regroup a linked list so that all nodes at odd positions (1st, 3rd, …) come first, followed by the even positions, keeping relative order, in O(1) extra space.
Problem: Regroup a linked list so that all nodes at odd positions (1st, 3rd, …) come first, followed by the even positions, keeping relative order, in O(1) extra space.
class Node:
def __init__(self, v, nxt=None): self.v, self.next = v, nxt
def build(xs):
head = None
for x in reversed(xs): head = Node(x, head)
return head
def show(h):
out = []
while h: out.append(h.v); h = h.next
return out
def odd_even(head):
if not head: return head
odd, even = head, head.next
even_head = even
while even and even.next:
odd.next = even.next; odd = odd.next
even.next = odd.next; even = even.next
odd.next = even_head
return head
print(show(odd_even(build([10, 20, 30, 40, 50, 60, 70]))))What is printed?- A. [20, 40, 60, 10, 30, 50, 70]
- B. [10, 30, 50, 20, 40, 60, 70]
- C. [10, 30, 50, 70, 60, 40, 20]
- D. [10, 30, 50, 70, 20, 40, 60]
Correct answer: D. [10, 30, 50, 70, 20, 40, 60]
Two chains are built by relinking: odd takes every other node starting at the head, even starts at the second node; finally the odd chain's tail points to the saved even head. Positions 1, 3, 5, 7 hold 10, 30, 50, 70. Note it is about positions, not values. O(n) time, O(1) space.
More Coding Interview Problems questions
- Problem: Rotate a linked list to the right by k places (k may exceed the length). python class Node: def init(self, v, nxt=None): self.v…
- Problem: Each rescue boat carries at most two people and at most limit kg. Find the minimum number of boats (greedy: pair the heaviest…
- Problem: Count how many query words are subsequences of a long log string, using per-letter position lists and binary search (instead of…
- Problem: A candy-crush style cleaner repeatedly deletes any k equal adjacent letters (cascading) until none remain. A stack of (letter…
- Problem: Score a balanced bracket string: "()" = 1, AB = A + B, (A) = 2·A. Each innermost "()" at depth d contributes 2^d. python def…
- Problem: Delivery vans drive towards a depot at 20 km; a faster van that catches a slower one ahead must slow down and they arrive as one…