Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Return the middle node of a linked list (the second middle when the length is even).
Problem: Return the middle node of a linked list (the second middle when the length is even).
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 middle(h):
slow = fast = h
while fast and fast.next:
slow, fast = slow.next, fast.next.next
return slow.v
print(middle(build([1, 2, 3, 4, 5])), middle(build([1, 2, 3, 4, 5, 6])))What is printed?- A. 3 3
- B. 2 3
- C. 3 5
- D. 3 4
Correct answer: D. 3 4
fast moves two steps per slow step, so slow is halfway when fast runs out. For 6 nodes fast stops at None after 3 moves, leaving slow on 4 – the second middle. Using 'while fast.next and fast.next.next' would give the first middle (3). O(n), one pass.
More Coding Interview Problems questions
- Problem: Remove the k-th node from the end of a list in one pass. python class Node: def init(self, v, nxt=None): self.v, self.next = v…
- Problem: Merge two sorted linked lists into one sorted list. python class Node: def init(self, v, nxt=None): self.v, self.next = v, nxt…
- Problem: Detect whether a linked list has a cycle and return the value where the cycle starts (None if acyclic). python class Node: def…
- Problem: Reverse the nodes of a linked list k at a time; a final group with fewer than k nodes stays as is. python class Node: def…
- Problem: Add two numbers whose digits are stored in reverse order in linked lists. python class Node: def init(self, v, nxt=None): self.v…
- Problem: An LRU cache of capacity c must support get(key) and put(key, value) in O(1) each, evicting the least recently used key. Which…