Squares of a Sorted Array
Explore how to transform a sorted integer array into a sorted array of squared values using both naive and optimized two-pointer approaches. Understand the logic behind handling negative and positive values, and learn to analyze time and space complexities for each method to improve algorithm efficiency.
Statement
Given an integer array, sorted in non-decreasing order, return an array of the squares of each number, sorted in non-decreasing order.
Example
Consider an integer array, sorted in non-decreasing order:
The returned array looks like this:
Sample input
[-4, -1, 0, 3, 10]
Expected output
[0, 1, 9, 16, 100]
Try it yourself
Solution
Naive approach
Create an array of the squares of each element, and sort them. The time complexity of this approach is or ...