Solving Leetcode Interviews in Seconds with AI: Squares of a Sorted Array
Introduction
In this blog post, we will explore how to solve the LeetCode problem "977" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Example 1: 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]. Example 2: Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121] Constraints: 1 <= nums.length <= 104 -104 <= nums[i] <= 104 nums is sorted in non-decreasing order. Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?
Explanation
Here's an efficient solution to the problem, focusing on the O(n) requirement:
- Two Pointers: Utilize two pointers, one at the beginning and one at the end of the input array.
- Compare and Place: Compare the absolute values of the elements pointed to by the pointers. The larger square is placed at the end of the result array.
Move Pointers: Move the pointers inwards based on which element's square was larger.
Runtime Complexity: O(n), Storage Complexity: O(n)
Code
def sortedSquares(nums):
"""
Squares the elements of a sorted array and returns a new sorted array of the squares.
Args:
nums: A list of integers sorted in non-decreasing order.
Returns:
A list of integers, the squares of the input, sorted in non-decreasing order.
"""
n = len(nums)
result = [0] * n
left = 0
right = n - 1
index = n - 1
while left <= right:
if abs(nums[left]) > abs(nums[right]):
result[index] = nums[left] ** 2
left += 1
else:
result[index] = nums[right] ** 2
right -= 1
index -= 1
return result