Sort LL

Linked-List FAQs (Hard) Hard
  • Fun Fact: Sorting a list is one of the most common operations in software development
  • In real-world applications, the concept of sorting a linked list in a non-decreasing order is extensively used in contact lists apps
  • For instance, when you look up your contacts in any messenger app or social media platform, names are typically displayed in alphabetically sorted order, which is a non-decreasing order
  • Behind the scenes, this concept is implemented in their software’s architecture for managing and displaying contacts!

Given the head of a singly linked list. Sort the values of the linked list in non-decreasing order and return the head of the modified linked list.

Examples:

Input: head -> 5 -> 6 -> 1 -> 2 -> 1

Output: head -> 1 -> 1 -> 2 -> 5 -> 6

Explanation: 1 <= 1 <= 2 <= 5 <= 6

Input: head -> 6 -> 5 -> -1 -> -2 -> -3

Output: head -> -3 -> -2 -> -1 -> 5 -> 6

Explanation: -3 <= -2 <= -1 <= 5 <= 6

Input: head -> -1 -> -2 -> -3 -> -1

Constraints

  • 0 <= number of nodes in the linked list <= 1000
  • -104 <= ListNode.val <= 104

Hints

  • Before merging, we check each child linked list for cycles using Floyd’s Cycle Detection Algorithm. Find the Start of the Cycle and Break the Cycle.
  • Use a Min-Heap (O(N log k)) or Divide & Conquer (O(N log k)) to merge the sorted lists. Return the flattened sorted list.

Company Tags

MongoDB Optum Mastercard PwC Docker Reddit Epic Systems Etsy Siemens Healthineers Broadcom Flipkart GE Healthcare HashiCorp OYO Rooms Byju's Bungie American Express Alibaba eBay Philips Healthcare McKinsey & Company Micron Technology Seagate Technology AMD ARM Google Microsoft Amazon Meta Apple Netflix Adobe