700234. Absolute List Sorting

Medium

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:

  1. Initialize an empty array or data structure sortedAbs to store the absolute values.
  2. Iterate over the linked list and extract each node's absolute value. Store these values in sortedAbs.
  3. Sort sortedAbs using any standard sorting algorithm (e.g., quicksort, mergesort).
  4. Initialize an empty linked list result to store the sorted nodes.
  5. Iterate over sortedAbs and reconstruct the original linked list by creating new nodes with their corresponding absolute values.
  6. 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

View on GeeksforGeeks
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;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.