LeetCode Problem - Link


Solving Squares of a Sorted Array was pretty easy, I encountered this in the Arrays 101 course of LeetCode's Explore cards. It was straightforward, first I looped through an array by multiplying every number with itself resulting in an array of unsorted squared numbers. Which later need to be sorted in another pass.


Sequential Approach

I implemented the selection sort myself for practice, and although all cases pass, it's not very performant

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortedSquares = function (nums) {
    let squaredArr = nums.map((num) => {
        return num * num
    })


    // now we sort this array in increasing order
    // Selection sort
    for (var i = 0; i < squaredArr.length; i++) {
        for (var j = i + 1; j < squaredArr.length; j++) {
            if (squaredArr[i] > squaredArr[j]) {
                let temp = squaredArr[j]
                squaredArr[j] = squaredArr[i]
                squaredArr[i] = temp;
            }
        }
    }
    return squaredArr
};



A slightly faster approach

A much smaller chunk of code because we're using JavaScript's sort method. Makes me realize how slow the selection sort is compared to well-optimized sort function of JavaScript

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortedSquares = function (nums) {
    let squaredArr = nums.map((num) => {
        return num * num
    })
    // now we sort this array in increasing order
    return squaredArr.sort((a,b)=>{return a-b})
};