Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Merge two sorted linked lists into one sorted list.
Problem: Merge two sorted linked lists into one sorted list.
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 merge(a, b):
tail = dummy = Node(0)
while a and b:
if a.v <= b.v:
tail.next, a = a, a.next
else:
tail.next, b = b, b.next
tail = tail.next
tail.next = a or b
return dummy.next
print(show(merge(build([1, 4, 4, 9]), build([2, 4, 6]))))What is printed?- A. [1, 2, 4, 6, 9]
- B. [1, 2, 4, 4, 6, 9]
- C. [1, 2, 4, 4, 4, 6, 9]
- D. [1, 4, 4, 9, 2, 4, 6]
Correct answer: C. [1, 2, 4, 4, 4, 6, 9]
Standard splice with a dummy head; duplicates are kept, and whatever remains of one list is attached at the end with 'a or b'. O(m + n) time, O(1) extra space.
More Coding Interview Problems questions
- 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…
- Problem: The function below should check whether a singly linked list is a palindrome in O(1) extra space. python class Node: def…
- Problem: Return the height (number of nodes on the longest root-to-leaf path) of an org-chart tree. Trees are built by build(xs): a…