sortSquares

by evgkch

TypeScript

/*
Input: arr[] = [-5, -2, -1, 0, 4, 6]
Output: [0, 1, 4, 16, 25, 36]
Explanation: After squaring, the array becomes [25, 4, 1, 0, 16, 36].
After sorting, it becomes [0, 1, 4, 16, 25, 36].
*/
function sortSquares(arr: number[]) {
    const res: number[] = new Array(arr.length);

    let i = arr.length - 1,
        n = 0,
        p = arr.length - 1;

    //   n               p 
    //   v               v 
    // [-5, -2, 3, 4, 6, 7]
    while (n <= p) {
        const x = arr[n] * arr[n];
        const y = arr[p] * arr[p];
        if (x > y) {
            res[i--] = x;
            n++;
        }
        else {
            res[i--] = y;
            p--;
        }
    }

    return res;
}

console.log(sortSquares([0, 1, 4, 16, 25, 36]));