Mark As Completed Discussion

Good evening! Here's our prompt for today.

Write an algorithm to merge two sorted linked lists and return it as a new sorted list. The new list should be constructed by joining the nodes of the input lists.

Description

You may assume the following node definition:

1class Node:
2    def __init__(self, val):
3        self.value = val
4        self.next = None
5
6list1 = Node(1)
7list1.next = Node(2)
8
9print(list1.value, '->', list1.next.value)

Write a method called mergeSortedLists that would be invoked as such in the following example:

1# List 1: list1 = [1, 5, 6]
2# List 2: list2 = [2, 3, 4]
3
4merged_list = merge_sorted_lists(list1, list2)
5# Output: [1, 2, 3, 4, 5, 6]

As you can see, the linked lists are merged in an ascending sorted order.

Constraints

  • Length of the linked lists <= 100000
  • The values in the nodes will be in the range -1000000000 and 1000000000
  • Expected time complexity : O(n)
  • Expected space complexity : O(n) considering the call stack in recursion

Try to solve this here or in Interactive Mode.

How do I practice this challenge?

PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Here's a video of us explaining the solution.

To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

Here's how we would solve this problem...

How do I use this guide?

Access all course materials today

The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.

Returning members can login to stop seeing this.