Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Rotate a linked list to the right by k places (k may exceed the length).
Problem: Rotate a linked list to the right by k places (k may exceed the length).
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 rotate(head, k):
if not head: return head
n, tail = 1, head
while tail.next: tail = tail.next; n += 1
k %= n
if k == 0: return head
new_tail = head
for _ in range(n - k - 1): new_tail = new_tail.next
new_head = new_tail.next
new_tail.next = None; tail.next = head
return new_head
print(show(rotate(build([1, 2, 3, 4, 5]), 7)), show(rotate(build([8, 9]), 4)))What is printed?- A. [5, 1, 2, 3, 4] [8, 9]
- B. [4, 5, 1, 2, 3] [8, 9]
- C. [3, 4, 5, 1, 2] [8, 9]
- D. [4, 5, 1, 2, 3] [9, 8]
Correct answer: B. [4, 5, 1, 2, 3] [8, 9]
Measure the length n, reduce k mod n (7 mod 5 = 2, 4 mod 2 = 0), cut after node n − k and attach the old tail to the old head. Rotating right by 2 moves the last two nodes (4, 5) to the front. Without k %= n the loop would run a negative or huge number of steps; rotating by a multiple of n is the identity. O(n).
More Coding Interview Problems questions
- 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…
- Problem: Evaluate an expression of non-negative integers with + − / (no brackets, / truncates toward zero) in one pass with a stack…