Quick Overview

This question evaluates understanding of linked list manipulation, algorithmic reasoning for merging sorted sequences, and the ability to analyze time and space complexity while handling edge cases such as empty lists and duplicate values.

Merge two sorted linked lists

Company: HubSpot

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Onsite

Given the heads of two singly linked lists sorted in non-decreasing order, merge them into a single sorted singly linked list and return its head. Implement both iterative and recursive solutions, analyze time and space complexity, and handle edge cases such as empty lists and duplicate values.

Quick Answer: This question evaluates understanding of linked list manipulation, algorithmic reasoning for merging sorted sequences, and the ability to analyze time and space complexity while handling edge cases such as empty lists and duplicate values.

Given two singly linked lists sorted in non-decreasing order, merge them into a single sorted linked list and return its head. The lists are provided to your function as arrays of the node values in order (e.g. the list 1 -> 2 -> 4 is given as [1, 2, 4]); return the merged sequence as an array of values in non-decreasing order. The merge should be stable with respect to equal values and must correctly handle edge cases such as one or both lists being empty and duplicate values appearing in either list. Follow-up (discuss, not graded): implement the merge both iteratively (splice nodes with a dummy head, O(1) extra space) and recursively (O(m+n) call-stack space), and analyze the time and space complexity of each. Example 1: list1 = [1, 2, 4], list2 = [1, 3, 4] -> [1, 1, 2, 3, 4, 4] Example 2: list1 = [], list2 = [] -> [] Example 3: list1 = [], list2 = [0] -> [0]

Constraints

  • 0 <= len(list1), len(list2) <= 5000
  • -10^4 <= node value <= 10^4
  • Both list1 and list2 are sorted in non-decreasing order

Examples

Input: ([1, 2, 4], [1, 3, 4])

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

Explanation: Standard interleave; the two equal 1s and two equal 4s are all preserved, with list1's value taken first on ties.

Input: ([], [])

Expected Output: []

Explanation: Both lists empty -> the merged list is empty.

Hints

  1. Walk both lists with two pointers, always taking the smaller current value next. Use <= (not <) when values are equal so the merge is stable and duplicates are kept.
  2. When one list is exhausted, append the entire remainder of the other list — it is already sorted.
  3. For the in-place iterative version on real nodes, use a dummy head node so you never special-case the first element; for the recursive version, return the smaller head and recurse on the rest.

Loading coding console...