I tried solving the LeetCode question like many others, trying to incorporate the O(n) time complexity requirement.
- Squares of a Sorted Array
Given an integer array
numssorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.Example
- 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].
I came up with the following:
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
n = len(nums)
i = 0
j = n -1
# binary search O(log n)
if nums[0] == 0 or nums[0]> 0:
for i in range(n):
nums[i] = nums[i]**2
return nums
elif nums[n-1] == 0 or nums[n-1] < 0:
nums.reverse()
for i in range(n):
nums[i] = nums[i]**2
return nums
k1 = 0
k = n-1
while i<j and k!=k1:
k1 = k
k = (i+j)//2
if nums[k] == 0:
break
elif nums[k] > 0:
j = k
else:
i = k
if abs(nums[k]) > abs(nums[k+1]):
k = k+1
# sorting this way should cost O(n) time
if k < (n-1)//2:
q = k+1
for s in range(k-1,-1,-1):
p = nums[s]
for l in range(s,q-1):
nums[l] = nums[l+1]
while q < n and abs(p) > abs(nums[q]):
nums[q-1] = nums[q]
q += 1
nums[q-1] = p
else:
q = k-1
for s in range(k+1,n):
p = nums[s]
for l in range(s-1,q,-1):
nums[l+1] = nums[l]
while q >= 0 and abs(p) > abs(nums[q]):
nums[q+1] = nums[q]
q -= 1
nums[q+1] = p
nums.reverse()
# this for-loop also costs O(n)
for i in range(n):
nums[i] = nums[i]**2
# therefore O(log n)+O(n)+O(n) -> O(n)
return nums
by manually calculating the time cost (and also the AI tool by LeetCode). I seem to get O(n) time complexity, but this code is incredibly slow. Is it due to the 'chunkiness' of it or something else? Feel free to point out any redundancies or inefficient lines.