Arena / Problems /

977. Squares of a Sorted Array

Easy 0/10 Thrones Claimed
Prev Next

Problem Specification

LeetCode #977

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

Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?

Example 1
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation:

After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].

Example 2
Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Constraints
  • 1 <= nums.length <= 10000
  • 10000 <= nums[i] <= 10000
  • nums is sorted in non-decreasing order.
Topics & Algorithms
⚔️

Vacant Java Throne

No developer has claimed the Java throne for LeetCode #977 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Not Using `sort()` by Anonymous Developer
0
Approach Intuition:
  • The smallest number in the array is inside the array, and it needs to be traversed to find it, which is not very convenient.
  • But if we think in reverse, can we prioritize other numbers more conveniently? So which numbers should be prioritized?

    Click to view the answer

    The answer is to prioritize the numbers at both ends of the array because they are the largest.

class Solution {
    public int[] sortedSquares(int[] nums) {
        var results = new int[nums.length];
        var left = 0;
        var right = nums.length - 1;
        var index = right;

        while (left <= right) {
            if (Math.abs(nums[left]) <= nums[right]) {
                results[index] = nums[right] * nums[right];
                right -= 1;
            } else {
                results[index] = nums[left] * nums[left];
                left += 1;
            }

            index -= 1;
        }

        return results;
    }
}
#2 Using `sort()` by Anonymous Developer
0
class Solution {
    public int[] sortedSquares(int[] nums) {
        for (var i = 0; i < nums.length; i++) {
            nums[i] *= nums[i];
        }

        Arrays.sort(nums);

        return nums;
    }
}
⚔️

Vacant Python Throne

No developer has claimed the Python throne for LeetCode #977 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Not Using `sort()` by Anonymous Developer
0
Approach Intuition:
  • The smallest number in the array is inside the array, and it needs to be traversed to find it, which is not very convenient.
  • But if we think in reverse, can we prioritize other numbers more conveniently? So which numbers should be prioritized?

    Click to view the answer

    The answer is to prioritize the numbers at both ends of the array because they are the largest.

class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        results = [None] * len(nums)
        left = 0
        right = index = len(nums) - 1

        while left <= right:
            if abs(nums[left]) <= nums[right]:
                results[index] = nums[right] ** 2
                right -= 1
            else:
                results[index] = nums[left] ** 2
                left += 1

            index -= 1

        return results
#2 Using `sort()` by Anonymous Developer
0
class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        results = [num ** 2 for num in nums]

        results.sort()

        return results
⚔️

Vacant C++ Throne

No developer has claimed the C++ throne for LeetCode #977 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Not Using `sort()` by Anonymous Developer
0
Approach Intuition:
  • The smallest number in the array is inside the array, and it needs to be traversed to find it, which is not very convenient.
  • But if we think in reverse, can we prioritize other numbers more conveniently? So which numbers should be prioritized?

    Click to view the answer

    The answer is to prioritize the numbers at both ends of the array because they are the largest.

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        auto results = vector<int>(nums.size());
        auto left = 0;
        int right = nums.size() - 1;  // Should not use 'auto' here because 'auto' will make this variable become `unsigned long` which has no `-1`.
        auto index = right;

        while (left <= right) {
            if (abs(nums[left]) <= nums[right]) {
                results[index] = nums[right] * nums[right];
                right -= 1;
            } else {
                results[index] = nums[left] * nums[left];
                left += 1;
            }

            index -= 1;
        }

        return results;
    }
};
#2 Using `sort()` by Anonymous Developer
0
class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        for (auto i = 0; i < nums.size(); i++) {
            nums[i] *= nums[i];
        }

        sort(nums.begin(), nums.end());

        return nums;
    }
};
⚔️

Vacant Javascript Throne

No developer has claimed the Javascript throne for LeetCode #977 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Not Using `sort()` by Anonymous Developer
0
Approach Intuition:
  • The smallest number in the array is inside the array, and it needs to be traversed to find it, which is not very convenient.
  • But if we think in reverse, can we prioritize other numbers more conveniently? So which numbers should be prioritized?

    Click to view the answer

    The answer is to prioritize the numbers at both ends of the array because they are the largest.

var sortedSquares = function (nums) {
  const results = Array(nums.length).fill(null)
  let left = 0
  let right = nums.length - 1
  let index = right

  while (left <= right) {
    if (Math.abs(nums[left]) <= nums[right]) {
      results[index] = nums[right] * nums[right]
      right -= 1
    } else {
      results[index] = nums[left] * nums[left]
      left += 1
    }

    index -= 1
  }

  return results
};
#2 Using `sort()` by Anonymous Developer
0
var sortedSquares = function (nums) {
  return _.sortBy(
    nums.map((num) => num * num)
  )
};
⚔️

Vacant C# Throne

No developer has claimed the C# throne for LeetCode #977 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Not Using `sort()` by Anonymous Developer
0
Approach Intuition:
  • The smallest number in the array is inside the array, and it needs to be traversed to find it, which is not very convenient.
  • But if we think in reverse, can we prioritize other numbers more conveniently? So which numbers should be prioritized?

    Click to view the answer

    The answer is to prioritize the numbers at both ends of the array because they are the largest.

public class Solution
{
    public int[] SortedSquares(int[] nums)
    {
        var results = new int[nums.Length];
        int left = 0;
        int right = nums.Length - 1;
        int index = right;

        while (left <= right)
        {
            if (Math.Abs(nums[left]) <= nums[right])
            {
                results[index] = nums[right] * nums[right];
                right -= 1;
            }
            else
            {
                results[index] = nums[left] * nums[left];
                left += 1;
            }

            index -= 1;
        }

        return results;
    }
}
#2 Using `sort()` by Anonymous Developer
0
public class Solution
{
    public int[] SortedSquares(int[] nums)
    {
        for (int i = 0; i < nums.Length; i++)
            nums[i] *= nums[i];

        Array.Sort(nums);

        return nums;
    }
}
⚔️

Vacant Go Throne

No developer has claimed the Go throne for LeetCode #977 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Not Using `sort()` by Anonymous Developer
0
Approach Intuition:
  • The smallest number in the array is inside the array, and it needs to be traversed to find it, which is not very convenient.
  • But if we think in reverse, can we prioritize other numbers more conveniently? So which numbers should be prioritized?

    Click to view the answer

    The answer is to prioritize the numbers at both ends of the array because they are the largest.

func sortedSquares(nums []int) []int {
    results := make([]int, len(nums))
    left := 0
    right := len(nums) - 1
    index := right

    for left <= right {
        if math.Abs(float64(nums[left])) <= float64(nums[right]) {
            results[index] = nums[right] * nums[right]
            right -= 1
        } else {
            results[index] = nums[left] * nums[left]
            left += 1
        }

        index -= 1
    }

    return results
}
#2 Using `sort()` by Anonymous Developer
0
func sortedSquares(nums []int) []int {
    for i, _ := range nums {
        nums[i] *= nums[i]
    }

    sort.Sort(sort.IntSlice(nums))

    return nums
}
⚔️

Vacant Ruby Throne

No developer has claimed the Ruby throne for LeetCode #977 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Not Using `sort()` by Anonymous Developer
0
Approach Intuition:
  • The smallest number in the array is inside the array, and it needs to be traversed to find it, which is not very convenient.
  • But if we think in reverse, can we prioritize other numbers more conveniently? So which numbers should be prioritized?

    Click to view the answer

    The answer is to prioritize the numbers at both ends of the array because they are the largest.

def sorted_squares(nums)
  results = Array.new(nums.length)
  left = 0
  right = nums.size - 1
  index = right

  while left <= right
    if nums[left].abs <= nums[right]
      results[index] = nums[right] * nums[right]
      right -= 1
    else
      results[index] = nums[left] * nums[left]
      left += 1
    end

    index -= 1
  end

  results
end
#2 Using `sort()` by Anonymous Developer
0
def sorted_squares(nums)
  nums.map { |num| num ** 2 }.sort
end
⚔️

Vacant Rust Throne

No developer has claimed the Rust throne for LeetCode #977 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

⚔️

Vacant Swift Throne

No developer has claimed the Swift throne for LeetCode #977 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

⚔️

Vacant Kotlin Throne

No developer has claimed the Kotlin throne for LeetCode #977 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.