BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Data processing and features51 of 54 in topic

839. Merge two sorted linked lists

EasyData processing and features

Two shards return their results as singly linked lists already sorted by score, ascending. You want one sorted list without copying values into an array.

A node class is provided: ListNode(val, next=None) with fields val and next. Write merge_sorted(a, b) that takes the two head nodes (either can be None) and returns the head of one merged sorted list built by relinking the existing nodes. When values are equal, nodes from a come first.

Functiondef merge_sorted(a, b)

Example 1

Input: merging lists 1

Output: 3 -> 5 and 2 -> 4 gives 1 -> 2 -> 3 -> 4 -> 5

Example 2

Input: to_list(merge_sorted(build([1, 3, 5]), build([2, 4])))

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

Example 3

Input: to_list(merge_sorted(build([]), build([1, 2])))

Output: [1, 2]

Constraints

  • 0 <= length of each list <= 50,000
Hint 1

Start with dummy = tail = ListNode(0).

Hint 2

Take from a when values tie.

Hint 3

Attach the leftover list at the end.

Common mistakes
  • Losing the rest of a list by moving the pointer before linking.
  • Forgetting the leftover tail.
  • Returning the dummy node instead of dummy.next.
Understand the idea

Merging two sorted sequences is the core step of merge sort and of k-way merges of shard results. With linked lists you relink nodes instead of copying, which keeps memory O(1). The dummy head is a standard trick: it gives the loop a node to attach to before the real head is known.

Topics
Data processing and features
Similar questions
  • Standardise features without leaking test dataEasy
  • Scale features with the median and IQR so outliers do not dominateEasy
  • Encode hour of day and day of week as sine and cosine featuresEasy
  • Clip outliers using percentiles learned on the training set onlyEasy
All Data processing and features problems
Report
839 / 903
Python 3solution.pyPython idle
1
2
3
4
5
# ListNode(val, next=None) is provided
def merge_sorted(a, b):
# return the head of the merged list
pass
​
to_list(merge_sorted(build([1, 3, 5]), build([2, 4])))

This case uses generated data, so it runs as written. Press + to add your own case.

Run checks these cases in your browser, no sign-in needed. Submit checks all 6 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS