Skip to content

Commit

Permalink
Add a solution to Squares of a Sorted Array
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu committed Oct 12, 2022
1 parent 220c9e0 commit cc7ea56
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Array/SquaresSortedArray.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Question Link: https://leetcode.com/problems/squares-of-a-sorted-array/
* Primary idea: Two pointers. Compare absolute value and assign the bigger one to the right most index of the result.
* Time Complexity: O(n), Space Complexity: O(1)
*
*/

class SquaresSortedArray {
func sortedSquares(_ nums: [Int]) -> [Int] {
var left = 0, right = nums.count - 1, res = Array(repeating: 0, count: nums.count)
var square = 0, idx = nums.count - 1

while left <= right {

if abs(nums[left]) < abs(nums[right]) {
square = nums[right]
right -= 1
} else {
square = nums[left]
left += 1
}

res[idx] = square * square
idx -= 1
}

return res
}
}

0 comments on commit cc7ea56

Please sign in to comment.