DEV Community

VARUN
VARUN

Posted on

CA 18 - Squares of a Sorted Array



1.Problem Understanding
Given sorted array needs to square that sorted array and give the squared sorted array as a output

Example
nums = [-4, -1, 0, 3, 10]
Output:
[0, 1, 9, 16, 100]

2.Approach
Square all elements
Sort the array
def sortedSquares(nums):
return sorted([x*x for x in nums])

3.Idea
Largest square comes from:
either leftmost (negative)
or rightmost (positive)

(-10)^2 = 100
10^2 = 100

4.Optimal Approach
Use:
left = 0
right = n-1
Compare:
abs(nums[left]) vs abs(nums[right])
Place larger square at the end

5.Example
nums = [-4, -1, 0, 3, 10]

Step:

compare 4 vs 10 → put 100
compare 4 vs 3 → put 16
compare 1 vs 3 → put 9
compare 1 vs 0 → put 1
put 0

Final:

[0, 1, 9, 16, 100]

6.Algorithm
Initialize result array of size n
Use two pointers
Fill result from end → start
Compare absolute values
Move pointers accordingly

Top comments (0)