BackeasyArraysAmazonZomato

Sorted Squares Solution

Problem Statement

Given a sorted array of integers, compute the square of each element and return the resulting array in sorted order.

Example 1
Input
[-4, -1, 0, 3, 10]
Output
[0, 1, 9, 16, 100]

Explanation: Step-by-step: with input [-4, -1, 0, 3, 10], we square each element to get [16, 1, 0, 9, 100], then sort the array in ascending order, giving output [0, 1, 9, 16, 100]

Example 2
Input
[2, 3, 5, 7, 11]
Output
[4, 9, 25, 49, 121]

Explanation: Step-by-step: with input [2, 3, 5, 7, 11], we square each element to get [4, 9, 25, 49, 121], then sort the array in ascending order, giving output [4, 9, 25, 49, 121]

Constraints

  • 1 <= n <= 10^4
  • -10^4 <= arr[i] <= 10^4
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Sorted Squares — Problem Statement & Solution Guide

ArraysEasyTwo Pointers
TimeO(n log n)
|
SpaceO(n)

Problem Description

Given a sorted array of integers, compute the square of each element and return the resulting array in sorted order.

Examples

Example 1

Input

[-4, -1, 0, 3, 10]

Output

[0, 1, 9, 16, 100]

Explanation: Step-by-step: with input [-4, -1, 0, 3, 10], we square each element to get [16, 1, 0, 9, 100], then sort the array in ascending order, giving output [0, 1, 9, 16, 100]

Example 2

Input

[2, 3, 5, 7, 11]

Output

[4, 9, 25, 49, 121]

Explanation: Step-by-step: with input [2, 3, 5, 7, 11], we square each element to get [4, 9, 25, 49, 121], then sort the array in ascending order, giving output [4, 9, 25, 49, 121]

Constraints

  • 1 <= n <= 10^4
  • -10^4 <= arr[i] <= 10^4

Optimal Approach & Strategy

Two pointers at start and end. Compare absolute values, square the larger one, and place it at the end of a new result array. Move pointer inwards. Time O(N), Space O(N).

Brute Force Approach

Square all elements and then sort. Time O(N log N).

Verified Code Solutions

JavaScript Solution
Time: O(n log n)
function solution(nums) { return nums.map(x => x * x).sort((a, b) => a - b); }

Asked in Top Tech Interviews

AmazonZomato

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.