Tutorialspoint
Problem
Solution
Submissions

Merge Two Sorted Lists into a Single Sorted List

Certification: Basic Level Accuracy: 24.74% Submissions: 97 Points: 10

Write a Python program that merges two sorted lists of integers into a single sorted list.

Example 1
  • Input: list1 = [1, 3, 5, 7], list2 = [2, 4, 6, 8]
  • Output: [1, 2, 3, 4, 5, 6, 7, 8]
  • Explanation:
    • Step 1: Initialize two pointers, one for each list.
    • Step 2: Compare elements at current pointers and add the smaller one to result.
    • Step 3: Move the pointer for the list whose element was just added.
    • Step 4: Repeat until all elements from both lists are processed.
    • Step 5: Return the merged sorted list.
Example 2
  • Input: list1 = [10, 20, 30], list2 = [5, 15, 25]
  • Output: [5, 10, 15, 20, 25, 30]
  • Explanation:
    • Step 1: Initialize two pointers, one for each list.
    • Step 2: Compare elements at current pointers and add the smaller one to result.
    • Step 3: Move the pointer for the list whose element was just added.
    • Step 4: Repeat until all elements from both lists are processed.
    • Step 5: Return the merged sorted list.
Constraints
  • 0 ≤ len(list1), len(list2) ≤ 10^5
  • Both input lists are already sorted in ascending order
  • Time Complexity: O(n+m) where n and m are the lengths of the input lists
  • Space Complexity: O(n+m) for storing the result
ArraysFunctions / MethodsPointers and ReferencesEYSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use two pointers, one for each list, and compare elements
  • Built-in sorted() function: return sorted(list1 + list2)
  • Merge sort approach: compare elements from both lists and append the smaller one to the result

Steps to solve by this approach:

 Step 1: Initialize an empty result list and pointers for both input lists.
 Step 2: Compare elements from both lists while both pointers are within bounds.
 Step 3: Add the smaller element to the result list and increment its pointer.
 Step 4: After one list is exhausted, append any remaining elements from the first list.
 Step 5: Append any remaining elements from the second list.
 Step 6: Return the merged sorted list.

Submitted Code :