LeetCode solutions

1019. Squares of a Sorted Array

My accepted C++ solution to LeetCode problem 1019, Squares of a Sorted Array, running in 0ms.

  • Difficulty: Easy
  • C++
  • Runtime 0ms
  • Memory 30.3MB

Read the problem on LeetCode View on GitHub

C++

Accepted on LeetCode — runtime 0ms, memory 30.3MB, accepted 2025-12-27.

cpp
class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int n = nums.size();
        vector<int> result(n);
        int l = 0, r = n - 1, idx = n - 1;
        while (l <= r) {
            int left = nums[l] * nums[l];
            int right = nums[r] * nums[r];
            if (left > right) {
                result[idx--] = left;
                l++;
            } else {
                result[idx--] = right;
                r--;
            }
        }
        return result;
    }
};

Source