700234. Absolute List Sorting
Absolute List Sorting
Slug: absolute-list-sorting
Difficulty: Medium
Topic Tags: Linked List, Data Structures
Company Tags: Amazon, OYO Rooms
Summary
Given a singly linked list where each node contains an integer value and its corresponding absolute value, the task is to sort the list based on these absolute values. This problem requires understanding of linked lists and basic sorting algorithms.
Detailed Explanation
To solve this problem, we'll start by iterating over the linked list and storing each node's absolute value in a separate array or data structure. Then, we'll sort this array using any standard sorting algorithm (e.g., quicksort, mergesort). Once the array is sorted, we can iterate over it again to reconstruct the original linked list in the correct order.
Here's a step-by-step breakdown of the solution:
- Initialize an empty array or data structure
sortedAbsto store the absolute values. - Iterate over the linked list and extract each node's absolute value. Store these values in
sortedAbs. - Sort
sortedAbsusing any standard sorting algorithm (e.g., quicksort, mergesort). - Initialize an empty linked list
resultto store the sorted nodes. - Iterate over
sortedAbsand reconstruct the original linked list by creating new nodes with their corresponding absolute values. - Return the sorted linked list.
Time complexity: O(n log n) due to sorting, where n is the number of nodes in the linked list.
Space complexity: O(n) for storing the absolute values in sortedAbs.
Optimized Solutions
Java
public ListNode absoluteListSorting(ListNode head) {
if (head == null) return null;
// Step 1: Extract and store absolute values
List<Integer> sortedAbs = new ArrayList<>();
while (head != null) {
int absVal = Math.abs(head.val);
sortedAbs.add(absVal);
head = head.next;
}
// Step 2: Sort the array of absolute values
Collections.sort(sortedAbs);
// Step 3: Reconstruct the linked list in the correct order
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
for (int absVal : sortedAbs) {
int sign = Math.signum(head.val); // Determine the original sign
ListNode newNode = new ListNode(absVal * sign);
curr.next = newNode;
curr = curr.next;
}
return dummy.next;
}