DEV Community

codingpineapple
codingpineapple

Posted on

3

LeetCode 977. Squares of a Sorted Array (javascript solution)

Description:

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

// Two pointer
var sortedSquares = function(A) {
    let result = [];
    // Left and right pointer
    let l = 0;
    let r = A.length - 1;
    // Position to add squared number to A
    let p = r;

    // Add the higher number to the array and then decrease the pointer
    while (l <= r) {
        if (A[l] ** 2 > A[r] ** 2) {
            result[p--] = A[l++] ** 2;
        } else {
            result[p--] = A[r--] ** 2;
        }
    }

    return result;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay