Taro Logo

Sort Array By Absolute Value

Easy
Asked by:
Cognizant
0 views
Topics:
ArraysTwo Pointers

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected behavior for elements that share the exact same absolute value (e.g., how should -5 and 5 be ordered relative to each other)?
  2. Can the input array contain extreme values like the minimum and maximum possible 32-bit integers, where taking the absolute value might cause integer overflow?
  3. Should the sorting be performed in-place modifying the original array, or should I return a new sorted array?
  4. How should the algorithm handle edge cases such as an empty array or a single-element array?
  5. Are all elements guaranteed to be standard integers, or could we encounter floating-point numbers or null/undefined values?

Brute Force Solution

Approach

Imagine you have a collection of numbers that can be either positive or negative, and your goal is to rearrange them from smallest to largest based on how far away they are from zero, regardless of their sign. The brute force approach achieves this by exhaustively comparing every possible pairing of numbers to find their distances from zero and sorting them accordingly.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire group of numbers.
  2. Pick the first number and calculate its distance from zero, ignoring whether it is positive or negative.
  3. Compare that distance to the distance of every other number in the group one by one.
  4. Every time you find a number that has a smaller distance from zero than the one you are currently holding, swap their positions in your mind.
  5. Continue this exhaustive process of comparing and swapping until you have checked every single number against every other number.
  6. Once you have finished checking all possible pairs, the numbers will naturally fall into order from the closest to zero to the farthest away from zero.

Code Implementation

def sort_array_by_absolute_value(input_numbers):
    number_count = len(input_numbers)

    # Exhaustively compare every possible pair to ensure every number is evaluated against all others
    for outer_index in range(number_count):
        for inner_index in range(outer_index + 1, number_count):
            current_distance = abs(input_numbers[outer_index])
            comparison_distance = abs(input_numbers[inner_index])

            # Swap positions if the later number is closer to zero than our current reference number
            if comparison_distance < current_distance:
                temporary_holder = input_numbers[outer_index]
                input_numbers[outer_index] = input_numbers[inner_index]
                input_numbers[inner_index] = temporary_holder

    # Return the fully mutated array once all exhaustive comparisons and swaps are complete
    return input_numbers

Big(O) Analysis

Time Complexity
O(n²) – For each of the n numbers in the input array, the algorithm exhaustively compares its absolute value against the absolute value of every other number in the group. For the first element, we perform n comparisons, for the second element n-1 comparisons, and so on. This nested process of comparing and swapping pairs leads to approximately n * n / 2 total operations. Dropping the constant factor simplifies the final Big O time complexity to O(n²).
Space Complexity
O(1) – The brute force approach described relies entirely on in-place comparisons and swapping of the elements within the existing collection. No additional data structures, temporary lists, or recursive calls are created during the process. The extra memory consumed remains constant regardless of the input size N, consisting solely of a few primitive variables used for tracking indices. Therefore, the auxiliary space complexity simplifies to O(1).

Optimal Solution

Approach

This problem requires rearranging an array of integers so that their absolute values appear in non-decreasing order. In Python, this can be efficiently achieved by sorting the list with a custom key function. Using Python's stable sort ensures elements with identical absolute values are arranged validly while satisfying the example outputs.

Here's how the algorithm would work step-by-step:

  1. Make a copy of the input list of integers to avoid mutating the original input.
  2. Apply the built-in sort method using the absolute value function as the sorting key.
  3. Rely on the stability of Python's Timsort to maintain relative ordering for ties.
  4. Return the rearranged list sorted by non-decreasing absolute values.

Code Implementation

def sort_array_by_absolute_value(nums: list[int]) -> list[int]:
    # Create a copy of the input list to preserve the original structure
    sorted_numbers = list(nums)
    # Sort the numbers in non-decreasing order using their absolute value as the key
    sorted_numbers.sort(key=abs)
    # Return the newly sorted list of integers
    return sorted_numbers

Big(O) Analysis

Time Complexity
O(n log n) – Sorting an array of length n using Python's built-in Timsort algorithm takes O(n log n) comparisons in the worst and average cases.
Space Complexity
O(n) – Creating a duplicate list of size n and the auxiliary memory required by Timsort together use O(n) space.

Edge Cases

Empty or null array input
How to Handle:
Return the empty or null array immediately since no sorting is required.
Array with a single element
How to Handle:
Return the single-element array as it is already trivially sorted.
Array with mixed positive and negative numbers having the same absolute value
How to Handle:
Use a stable sorting algorithm to preserve the original relative order of identical absolute values.
Array containing multiple zeros
How to Handle:
Treat all zeros with absolute value zero and preserve their relative positions via stable sort.
Array with extreme boundary values like minimum and maximum integer limits
How to Handle:
Compute absolute values using wider integer types to prevent integer overflow bugs.
Extremely large arrays with millions of elements
How to Handle:
Utilize an efficient comparison-based sorting algorithm with O(n log n) time complexity.
Array with all identical elements
How to Handle:
Perform the sort without altering the original sequence due to the stability property.
Pre-sorted or reverse-sorted arrays
How to Handle:
Ensure the sorting algorithm handles these distributions efficiently without worst-case degradation.