#977
Easy Algorithms Squares of a sorted array
Array Two Pointers Sorting
73.6% acceptance
Feb 25, 2026
10168
275
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn sorted_squares(nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut res = vec![0; n];
let (mut l, mut r) = (0usize, n - 1);
let mut pos = n;
while l <= r {
pos -= 1;
let (sl, sr) = (nums[l]*nums[l], nums[r]*nums[r]);
if sl > sr { res[pos] = sl; l += 1; } else { res[pos] = sr; if r == 0 { break; } r -= 1; }
}
res
}
}