Squares of a Sorted Array
LeetCode 1019 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example 1:
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
Example 2:
Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Constraints:
- `1 10^4`
- `-10^4 <= nums[i] <= 10^4`
- `nums` is sorted in **non-decreasing** order.
Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?
Topics: Array, Two Pointers, Sorting
Approachβ
Two Pointersβ
Use two pointers to traverse the array, reducing the search space at each step. This avoids the need for nested loops, bringing complexity from O(nΒ²) to O(n) or O(n log n) if sorting is involved.
When to use
Array is sorted or can be sorted, and you need to find pairs/triplets that satisfy a condition.
Solutionsβ
Solution 1: C# (Best: 152 ms)β
| Metric | Value |
|---|---|
| Runtime | 152 ms |
| Memory | 48.7 MB |
| Date | 2022-01-13 |
Solution
public class Solution {
public int[] SortedSquares(int[] nums) {
int[] result = new int[nums.Length];
int l = 0, r = nums.Length-1;
int counter = nums.Length -1;
while(l <=r)
{
if(Math.Abs(nums[l])>Math.Abs(nums[r]))
{
result[counter] = nums[l] * nums[l];
l++;
}
else
{
result[counter] = nums[r] * nums[r];
r--;
}
counter--;
}
return result;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Two Pointers | $O(n)$ | $O(1)$ |
| Sort + Process | $O(n log n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Ask: "Can I sort the array?" β Sorting often enables two-pointer techniques.