How I Sorted Squares of a Sorted Array in Python
Introduction:
While practicing Python problems, I came across a question where I had to square each element of a sorted array and return the result in sorted order. At first, it looked easy, but negative numbers made it a bit tricky. In this blog, I will explain how I solved it step by step.
Problem Statement:
We are given an array sorted in non-decreasing order. We need to return a new array containing the squares of each number, also sorted in non-decreasing order.
Example:
Input: nums = [-4, -1, 0, 3, 10]
Output: [0, 1, 9, 16, 100]
Input: nums = [-7, -3, 2, 3, 11]
Output: [4, 9, 9, 49, 121]
My Idea:
If I directly square the numbers, negative values become positive, which may disturb the order. So I used a two-pointer approach. I compare the absolute values from both ends and place the larger square at the end of the result array.
Code:
class Solution:
def sortedSquares(self, nums):
n = len(nums)
result = [0] * n
left = 0
right = n - 1
pos = n - 1
while left <= right:
if abs(nums[left]) > abs(nums[right]):
result[pos] = nums[left] * nums[left]
left += 1
else:
result[pos] = nums[right] * nums[right]
right -= 1
pos -= 1
return result
Explanation:
I used two pointers, one at the beginning and one at the end of the array. I compared the absolute values of both ends. The larger value gives a bigger square, so I placed it at the end of the result array. Then I moved the pointer accordingly and continued the process.
Common Mistake:
While running this code, I got an error like this:
NameError: global name 'Solution' is not defined
or
AttributeError: 'list' object has no attribute 'split'
Why This Happens:
These errors happen when we do not follow the correct format required by coding platforms. Using input() and split() works in local systems but not in platforms like LeetCode. Also, missing the Solution class causes errors.
Wrong Approach:
nums = list(map(int, input().split()))
Correct Approach:
Always define the class and function properly and return the result instead of printing.
What I Learned:
This problem helped me understand how to handle negative numbers in arrays. I also learned the importance of following the correct format in coding platforms and using efficient techniques like two pointers.
Conclusion:
Sorting squares of an array becomes easy with the right approach. The two-pointer method makes it efficient and avoids unnecessary sorting. This problem improved my problem-solving skills and understanding of arrays.
Comments
Post a Comment