Skip to main content
Back to problems
#3667
Easy Algorithms

Sort array by absolute value

Array Math Two Pointers Sorting
86.2% acceptance
Mar 31, 2026
7
0
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

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn sort_by_absolute_value(mut nums: Vec<i32>) -> Vec<i32> {
    nums.sort_by_key(|&x| x.abs());
    nums
  }
}