← Google bank

Google · Question 24 · Linked Lists

Merge Two Sorted Lists

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

Problem

Merge two sorted linked lists and return a sorted merged list.

Approach

Iteratively pick smaller node from either list.

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

How it works

  1. 1Use a dummy node to start the merged list.
  2. 2Compare the heads of l1 and l2, append the smaller.
  3. 3Move pointers accordingly until one list ends.
  4. 4Append the remaining nodes and return the merged list.

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 = tail = ListNode()while l1 and l2if l1.val < l2.valtail.next = l1l1 = l1.nextELSEtail.next = l2l2 = l2.nexttail = tail.nexttail.next = l1 or 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/38

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