FastPrepSquares of a Sorted Array

Squares of a Sorted Array

Instacart logoInstacartâ—Ź EasyFULLTIMEPHONE SCREEN

Problem statement

You are given an integer array nums sorted in non-decreasing order. Return an array of the squares of every number, also sorted in non-decreasing order.

Keep every square, including repeats. The result has the same length as nums.

Follow-up: squaring and then sorting takes O(n log n) time. Can you do it in O(n)?

Function

sortedSquares(nums: int[]) → int[]

Examples

Example 1

nums = [-4,-1,0,3,10]return = [0,1,9,16,100]

The squares are 16, 1, 0, 9, 100. Sorted, they are [0,1,9,16,100].

Example 2

nums = [-7,-3,2,3,11]return = [4,9,9,49,121]

The squares are 49, 9, 4, 9, 121. Sorted, they are [4,9,9,49,121]. The value 9 appears twice because both -3 and 3 square to it.

Example 3

nums = [-5,-3,-3,-1]return = [1,9,9,25]

Every number is negative, so the squares 25, 9, 9, 1 come out in reverse. Sorted, they are [1,9,9,25].

Constraints

  • 1 <= nums.length <= 1000
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in non-decreasing order.

More Instacart problems

See Instacart hiring insights
Saved
public int[] sortedSquares(int[] nums) {
    // Write your code here.
}
Checking account…