Learner Level

Implement the sortedSquaresTwoPointers method that returns squares of sorted values in sorted order.

The input contains a sorted integer array nums and its length size. Values may be negative, zero, or positive.

Your task is to square every value and return the squared values in sorted ascending order.

For example, [-4,-1,0,3,10] becomes squares [16,1,0,9,100], and the sorted result is [0,1,9,16,100].

Example 1
Input:
nums (int[]) = [-4,-1,0,3,10]
size (int) = 5
Return:
(int[]) [0,1,9,16,100]
Example 2
Input:
nums (int[]) = [-7,-3,2,3,11]
size (int) = 5
Return:
(int[]) [4,9,9,49,121]
Example 3
Input:
nums (int[]) = [0]
size (int) = 1
Return:
(int[]) [0]

Because the input is already sorted, the largest square will be created by either the leftmost negative value or the rightmost positive value.

Use two pointers: one at the beginning and one at the end. Compare the absolute values, place the larger square at the end of the result array, and move inward.

Fill the result array from right to left so the final array remains sorted.

Pseudocode:

function sortedSquaresTwoPointers(nums, size):
    left = 0
    right = size - 1
    position = size - 1
    result = array of size elements
    while left <= right:
        leftSquare = nums[left] * nums[left]
        rightSquare = nums[right] * nums[right]
        if leftSquare > rightSquare:
            result[position] = leftSquare
            left++
        else:
            result[position] = rightSquare
            right--
        position--
    return result
Run your code to see the result.