Menu
CoddyTech

Squares of a Sorted Array

You get an array of integers nums sorted in non-decreasing order. It may hold negative values. Square every value and return the squares as a new array, also sorted in non-decreasing order.

Function

sortedSquares(nums: integer-array) → integer-array
numsinteger-array
the sorted array of integers, negatives allowed
Returnsinteger-array
the square of every value, sorted in non-decreasing order

Constraints

  • 1 ≤ nums.length ≤ 4000
  • -104 ≤ nums[i] ≤ 104
  • nums is sorted in non-decreasing order.

Examples

Input
nums = [-6, -2, 1, 3, 7]
Output
[1, 4, 9, 36, 49]
Explanation
The squares in the original order are 36, 4, 1, 9 and 49. The negative values -6 and -2 give large squares, so sorting moves 36 near the end: [1, 4, 9, 36, 49].

lock icon+14 hidden tests on Submit

challenge icon

Follow-up

Squaring and sorting takes O(n log n). Can you do it in O(n)?

Reset code
def sortedSquares(nums):
    # Write code here
Test cases

Case 1

Case 2

Input

nums = [-6, -2, 1, 3, 7]

Expected

[1, 4, 9, 36, 49]