Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #21: Merge Two Sorted Lists

In this guide, we solve Leetcode #21 Merge Two Sorted Lists in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list.

Quick Facts

  • Difficulty: Easy
  • Premium: No
  • Tags: Recursion, Linked List

Intuition

Linked list problems often require pointer manipulation rather than extra memory.

Two-pointer techniques expose cycles, midpoints, or reordering patterns.

Approach

Traverse with fast/slow pointers or reverse sublists when needed.

Maintain invariants carefully to avoid losing nodes.

Steps:

  • Traverse with pointers.
  • Reverse or split if required.
  • Reconnect nodes correctly.

Example

Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4]

Python Solution

# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists( self, list1: Optional[ListNode], list2: Optional[ListNode] ) -> Optional[ListNode]: if list1 is None or list2 is None: return list1 or list2 if list1.val <= list2.val: list1.next = self.mergeTwoLists(list1.next, list2) return list1 else: list2.next = self.mergeTwoLists(list1, list2.next) return list2

Complexity

The time complexity is O(m+n)O(m + n)O(m+n), and the space complexity is O(m+n)O(m + n)O(m+n). The space complexity is O(m+n)O(m + n)O(m+n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy