← Uber bank

Uber · Question 13 · Linked Lists

Merge two sorted linked lists

Linked ListsPythoncode⏱ O(n+m)💾 O(1)
Product-based

Problem

Merge and return a single sorted linked list.

Approach

Use two pointers to compare elements.

Time O(n+m)Space O(1)

How it works

  1. 1Compare the two heads and attach the smaller node.
  2. 2Advance the used list and the tail.
  3. 3Attach the leftover list and return dummy.next.

Sample input / output

Input:
3
1 2 4
3
1 3 4
Output:
[1, 1, 2, 3, 4, 4]

Constraints

0 <= nodes <= 50; -100 <= Node.val <= 100; both lists sorted.

Solution — read it, then walk it

Time O(n+m)Space O(1)Loops 3Branches 3Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeat↻ repeat↻ repeatyesnoSTARTl1, l2dummy = ListNode(0)current = dummywhile l1 and l2if l1.val < l2.valcurrent.next = l1l1 = l1.nextELSEcurrent.next = l2l2 = l2.nextcurrent = current.nextcurrent.next = l1 if l1else l2RETURN dummy.nextCLASS ListNodeDEFINE __init__(self,val=0, next=None)self.val = valself.next = nextDEFINE build_list(values)dummy = tail = ListNode()for v in valuestail.next = ListNode(v)tail = tail.nextRETURN dummy.nextDEFINE to_list(head)out = []while headout.append(head.val)head = head.nextRETURN outDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it)); a =[int(next(it)) for _ inrange(n)]m = int(next(it)); b =[int(next(it)) for _ inrange(m)]print(to_list(mergeTwoLists(build_list(a),build_list(b))))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/39

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits