> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/02-03-2022-977.md).

# 02/03/2022 977

Method:

Since the original array is already sorted, we can expect the max value would be in the two ends if the original arrays are squared. Then we can use two pointers left and right, and create the same size result array. Compare left and right squared values and put the bigger value into the result of the last index, decrement the index, and also change the left or right pointers accordingly.&#x20;

Time O(N)

Space O(N)

```
    class Solution { 
    public int[] sortedSquares(int[] nums) { 
    if(nums == null|| nums.length == 0) return nums; 
    int[] result = new int[nums.length]; 
    int left = 0; 
    int right = nums.length - 1; 
    int index = nums.length - 1;
     
    while(left <= right){ // need left <= right
        if(nums[left] * nums[left] > nums[right] * nums[right]){
            result[index--] = nums[left] * nums[left];
            left++;
        }else{
            result[index--] = nums[right] * nums[right];
            right--;
        }
    }
    return result;
}
```

}
