4. Squares of a Sorted Array (#977) [EASY]

Kelly Tran
Nov 4, 2020

Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.

Example 1:

Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]

Example 2:

Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]

Note:

  1. 1 <= A.length <= 10000
  2. -10000 <= A[i] <= 10000
  3. A is sorted in non-decreasing order.

https://leetcode.com/problems/squares-of-a-sorted-array/

My solution: O(nlogn)

class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
return sorted([value**2 for value in A])

Note: sorted() in Python is O(nlogn)

O(n)

class Solution:
def sortedSquares(self, lst: List[int]) -> List[int]:
negative = [e ** 2 for e in lst if e < 0][::-1]
positive = [e ** 2 for e in lst if e >= 0]
res = []
i, j = 0, 0
while i < len(negative) and j < len(positive):
if negative[i] < positive[j]:
res.append(negative[i])
i += 1
else:
res.append(positive[j])
j += 1
while i < len(negative):
res.append(negative[i])
i += 1
while j < len(positive):
res.append(positive[j])
j += 1
return res

--

--