Leetcode 977. Squares of a Sorted Array
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]
Example 2:
Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Q: Can the input array contain duplicate numbers? A: Yes, the input array can contain duplicates.
Q: What is the range of the input array size? A: The problem doesn’t specify ranges, but typically LeetCode problems should handle sizes up to tens of thousands efficiently.
Q: Can we use extra space for memory? A: Yes, there is no constraint against using extra space.
Q: Should the algorithm handle negative numbers? A: Definitely, the example contains negative numbers.
Given the input array nums sorted in non-decreasing order:
nums.We can utilize a two-pointer approach since we know that the largest squares might be found:
left at the start of the array and right at the end of the array.nums.left and right.left or right) inward.This strategy ensures we fill the result array from the largest to the smallest value, essentially performing an efficient sort.
O(n) where n is the number of elements in nums, since we make a single pass through nums.O(n) for the result array.public class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int[] result = new int[n];
int left = 0, right = n - 1;
int pos = n - 1;
while (left <= right) {
int leftVal = nums[left] * nums[left];
int rightVal = nums[right] * nums[right];
if (leftVal > rightVal) {
result[pos] = leftVal;
left++;
} else {
result[pos] = rightVal;
right--;
}
pos--;
}
return result;
}
}
This implementation maintains optimal efficiency in terms of both time and space, ensuring that the problem constraints and requirements are effectively met.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?