Skip to main content

Sort Array By Absolute Value - Solution & Explanation

EasyPremiumFree on FleetCodeArrayMathTwo PointersSorting5 min readAsked at: Cognizant
Practice this problem

Problem Statement

You are given an integer array nums.

Rearrange elements of nums in non-decreasing order of their absolute value.

Return any rearranged array that satisfies this condition.

Note: The absolute value of an integer x is defined as:

  • x if x >= 0
  • -x if x < 0

 

Example 1:

Input: nums = [3,-1,-4,1,5]

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

Explanation:

  • The absolute values of elements in nums are 3, 1, 4, 1, 5 respectively.
  • Rearranging them in increasing order, we get 1, 1, 3, 4, 5.
  • This corresponds to [-1, 1, 3, -4, 5]. Another possible rearrangement is [1, -1, 3, -4, 5].

Example 2:

Input: nums = [-100,100]

Output: [-100,100]

Explanation:

  • The absolute values of elements in nums are 100, 100 respectively.
  • Rearranging them in increasing order, we get 100, 100.
  • This corresponds to [-100, 100]. Another possible rearrangement is [100, -100].

 

Constraints:

  • 1 <= nums.length <= 100
  • -100 <= nums[i] <= 100

Approach Overview

Problem Overview: Given an integer array, reorder the elements so they are sorted by their absolute values. The comparison is performed using abs(x) instead of the raw value. Negative and positive numbers with the same magnitude should maintain the correct relative ordering defined by the comparator.

Approach 1: Custom Sorting with Absolute Comparator (O(n log n) time, O(1)–O(n) space)

The most direct solution uses a sorting algorithm with a custom comparator. Instead of comparing two numbers directly, the comparator evaluates abs(a) and abs(b). Most languages support this through a custom comparison function or a key extractor such as key=abs in Python. The sorting algorithm repeatedly compares elements using their absolute values and reorders the array accordingly. Time complexity is O(n log n) because it relies on comparison-based sorting. Space complexity ranges from O(1) to O(n) depending on the language’s sort implementation.

This method works for all inputs and requires minimal code. It is also the approach used in most production code because modern sorting implementations are highly optimized. The logic remains simple: iterate through the array implicitly via the sorting routine, compare absolute values, and swap elements when needed. This approach is closely tied to the fundamentals of sorting and basic array manipulation.

Approach 2: Bucket by Absolute Value (O(n + k) time, O(k) space)

If the value range is small, you can group numbers by their absolute value using buckets or a hash map. First iterate through the array and compute abs(x) for each element. Store the element in a bucket keyed by that absolute value. Then iterate through the buckets in ascending key order and append elements back into the result array. The iteration step costs O(n), and ordering the buckets costs up to O(k) where k is the range of absolute values.

This method avoids comparison-based sorting and can be faster when the absolute value range is small relative to the input size. It relies on simple math operations and sequential iteration. The tradeoff is additional memory for buckets and slightly more implementation complexity.

Recommended for interviews: Custom sorting with an absolute-value comparator is the expected solution. It demonstrates clear understanding of sorting mechanics and comparator design while keeping the implementation concise. Mentioning the bucket strategy shows deeper algorithmic thinking, but the O(n log n) custom sort is typically what interviewers want to see first.

Solution

We can use a custom sorting function to sort the array, where the sorting criterion is the absolute value of each element.

The time complexity is O(n times log n), and the space complexity is O(log n), where n is the length of the array nums.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Custom Sorting with Absolute ComparatorO(n log n)O(1) to O(n)General case. Works for any integer range and is the simplest implementation.
Bucket by Absolute ValueO(n + k)O(k)Useful when the range of absolute values is small compared to n.

Video Solution

Sort Array By Absolute Value • Owen Wu • 66 views views

Frequently Asked Questions

Is Sort Array By Absolute Value easy or hard?
Sort Array By Absolute Value is generally classified as an Easy problem. The key idea is recognizing that the sorting condition depends on abs(x) rather than the number itself. Once you apply a custom comparator, the implementation becomes straightforward.
Sort Array By Absolute Value Python/Java solution
Python solutions typically call sort with key=abs. Java implementations use Arrays.sort with a custom Comparator that compares Math.abs(a) and Math.abs(b). The same idea applies in C++, Go, TypeScript, and Rust using their respective custom comparator features.
How to solve Sort Array By Absolute Value in O(n)?
An O(n) style approach is possible when the range of absolute values is limited. You can iterate through the array, group numbers into buckets keyed by abs(x), and then rebuild the array by scanning the buckets in order. The total complexity becomes O(n + k), where k is the range of absolute values.
What is the best approach for Sort Array By Absolute Value?
The best approach is custom sorting using a comparator that compares absolute values. Most languages allow a key function such as abs(x) or a custom comparator. This solution runs in O(n log n) time using the built-in sorting algorithm and requires minimal additional code.
Is Sort Array By Absolute Value asked at Google/Amazon/Meta?
Array sorting problems with custom comparators appear frequently in interviews at large tech companies such as Google, Amazon, and Meta. Variants test your ability to define custom ordering rules and apply built-in sorting efficiently.
What data structure is used in Sort Array By Absolute Value?
The main data structure is a simple array combined with a sorting algorithm. Some optimized variants use hash maps or bucket arrays to group numbers by their absolute values before reconstructing the sorted output.
What is the time complexity of Sort Array By Absolute Value?
The standard solution uses comparison-based sorting with a custom absolute-value comparator, which runs in O(n log n) time. Space complexity depends on the language implementation, typically O(1) to O(n). Alternative bucket-based solutions can achieve O(n + k) time when the absolute value range is small.

Ready to solve this problem?

Practice Sort Array By Absolute Value with our built-in code editor and test cases.

Practice on FleetCode