Skip to content

Commit 7f760a7

Browse files
VanshVansh
authored andcommitted
added lc 0977
1 parent 7d94375 commit 7f760a7

File tree

1 file changed

+315
-0
lines changed

1 file changed

+315
-0
lines changed
Lines changed: 315 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,315 @@
1+
---
2+
id: squares-of-a-sorted-array
3+
title: Squares of a sorted array
4+
sidebar_label: 977. Squares of a Sorted Array
5+
6+
tags:
7+
- Array
8+
- Vector
9+
10+
description: "This is a solution to the squares of a sorted array problem on LeetCode."
11+
---
12+
13+
## Problem Description
14+
Given an integer array `nums` sorted in **non-decreasing** order, return an array of ***the squares of each number*** *sorted in non-decreasing order.*
15+
16+
### Examples
17+
18+
**Example 1:**
19+
```
20+
Input: nums = [-4,-1,0,3,10]
21+
Output: [0,1,9,16,100]
22+
Explanation: After squaring, the array becomes [16,1,0,9,100].
23+
After sorting, it becomes [0,1,9,16,100].
24+
```
25+
26+
**Example 2:**
27+
```
28+
Input: nums = [-7,-3,2,3,11]
29+
Output: [4,9,9,49,121]
30+
31+
```
32+
33+
34+
### Constraints
35+
- `1 <= nums.length <= 10^4`
36+
- `-10^4 <= nums[i] <= 10^4`
37+
- `nums` is sorted in **non-decreasing** order.
38+
39+
**Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
40+
41+
42+
## Solution for Sqaures of a Sorted Array
43+
### Approach
44+
#### Brute Force
45+
- **Square Each Element**: Iterate through the array and square each element.
46+
47+
- **Sort the Resulting Array**: Sort the array of squares.
48+
49+
**Implementation:**
50+
```python
51+
def sortedSquares(nums):
52+
# Step 1: Square each element
53+
squared_nums = [num ** 2 for num in nums]
54+
55+
# Step 2: Sort the array of squares
56+
squared_nums.sort()
57+
58+
return squared_nums
59+
60+
# Example usage
61+
nums = [-4, -1, 0, 3, 10]
62+
print(sortedSquares(nums)) # Output: [0, 1, 9, 16, 100]
63+
```
64+
65+
**Complexity:**
66+
- Time Complexity: `O(nlogn)` due to the sorting step, where `n` is the number of elements in `nums`.
67+
- Space Complexity: `O(n)` for storing the sqaured numbers.
68+
69+
**Corner Cases:**
70+
- Empty array: Should return an empty array.
71+
- All non-negative or all non-positive numbers: Should still work correctly without special handling.
72+
73+
#### Optimized Approach
74+
- **Two-pointer Technique**: Utilize two pointers, one at the beginning (`left`) and one at the end (`right`) of the array.
75+
- **Compare and Insert**: Compare the absolute values of the elements pointed by `left` and `right`. Insert the square of the larger absolute value at the end of the result array and move the corresponding pointer inward.
76+
- **Continue Until Pointers Meet**: Repeat the comparison and insertion until the pointers meet.
77+
78+
**Implementation:**
79+
80+
```python
81+
def sortedSquares(nums):
82+
n = nums.length
83+
result = [0] * n
84+
left, right = 0, n - 1
85+
position = n - 1
86+
87+
while left <= right:
88+
if abs(nums[left]) > abs(nums[right]):
89+
result[position] = nums[left] ** 2
90+
left += 1
91+
else:
92+
result[position] = nums[right] ** 2
93+
right -= 1
94+
position -= 1
95+
96+
return result
97+
98+
# Example usage
99+
nums = [-4, -1, 0, 3, 10]
100+
print(sortedSquares(nums)) # Output: [0, 1, 9, 16, 100]
101+
102+
```
103+
104+
**Complexity:**
105+
- Time Complexity: `O(n)` because we are traversing the array only once with the two-pointer technique.
106+
- Space Complexity: `O(n)` for the result array.
107+
108+
**Corner Cases:**
109+
- Empty array: Should return an empty array.
110+
- All non-negative or all non-positive numbers: Handled naturally by the two-pointer technique without special cases.
111+
- Array with single element: Both approaches handle this case correctly.
112+
113+
114+
<Tabs>
115+
<TabItem value="Solution" label="Solution">
116+
117+
#### Implementation
118+
119+
```jsx live
120+
function Solution(arr) {
121+
var sortedSquares = function(nums) {
122+
const result = new Array(nums.length)
123+
let i = nums.length - 1
124+
let j = 0
125+
let k = nums.length - 1
126+
127+
while (i >= 0) {
128+
if (Math.abs(nums[j]) > Math.abs(nums[k])) {
129+
result[i] = nums[j] * nums[j];
130+
++j;
131+
} else {
132+
result[i] = nums[k] * nums[k];
133+
--k;
134+
}
135+
--i;
136+
}
137+
return result
138+
};
139+
const input = [-4,-1,0,3,10]
140+
const originalInput = [...input]
141+
const output = sortedSquares(input)
142+
return (
143+
<div>
144+
<p>
145+
<b>Input: </b>
146+
{JSON.stringify(originalInput)}
147+
</p>
148+
<p>
149+
<b>Output:</b> {output.toString()}
150+
</p>
151+
</div>
152+
);
153+
}
154+
```
155+
156+
#### Complexity Analysis
157+
158+
- Time Complexity: $O(n)$
159+
- Space Complexity: $O(n)$
160+
161+
## Code in Different Languages
162+
163+
<Tabs>
164+
165+
<TabItem value="JavaScript" label="JavaScript">
166+
<SolutionAuthor name="@vansh-codes" />
167+
168+
```javascript
169+
var sortedSquares = function(nums) {
170+
const result = new Array(nums.length)
171+
let i = nums.length - 1
172+
let j = 0
173+
let k = nums.length - 1
174+
175+
while (i >= 0) {
176+
if (Math.abs(nums[j]) > Math.abs(nums[k])) {
177+
result[i] = nums[j] * nums[j];
178+
j++;
179+
} else {
180+
result[i] = nums[k] * nums[k];
181+
k--;
182+
}
183+
i--;
184+
}
185+
return result;
186+
};
187+
```
188+
189+
</TabItem>
190+
191+
<TabItem value="TypeScript" label="TypeScript">
192+
<SolutionAuthor name="@vansh-codes" />
193+
194+
```typescript
195+
function sortedSquares(nums: number[]): number[] {
196+
const result = new Array(nums.length);
197+
let i = nums.length - 1;
198+
let j = 0;
199+
let k = nums.length - 1;
200+
201+
while (i >= 0) {
202+
if (Math.abs(nums[j]) > Math.abs(nums[k])) {
203+
result[i] = nums[j] * nums[j];
204+
j++;
205+
} else {
206+
result[i] = nums[k] * nums[k];
207+
k--;
208+
}
209+
i--;
210+
}
211+
212+
return result;
213+
}
214+
```
215+
216+
</TabItem>
217+
218+
<TabItem value="Python" label="Python">
219+
<SolutionAuthor name="@vansh-codes" />
220+
221+
```python
222+
223+
class Solution(object):
224+
def sortedSquares(self, nums):
225+
result = [0] * len(nums)
226+
i = len(nums) - 1
227+
j = 0
228+
k = len(nums) - 1
229+
230+
while i >= 0:
231+
if abs(nums[j]) > abs(nums[k]):
232+
result[i] = nums[j] ** 2
233+
j += 1
234+
else:
235+
result[i] = nums[k] ** 2
236+
k -= 1
237+
i -= 1
238+
239+
return result
240+
241+
```
242+
243+
</TabItem>
244+
245+
<TabItem value="Java" label="Java">
246+
<SolutionAuthor name="@vansh-codes" />
247+
248+
```java
249+
import java.util.Arrays;
250+
251+
class Solution {
252+
public int[] sortedSquares(int[] nums) {
253+
int[] result = new int[nums.length];
254+
int i = nums.length - 1;
255+
int j = 0;
256+
int k = nums.length - 1;
257+
258+
while (i >= 0) {
259+
if (Math.abs(nums[j]) > Math.abs(nums[k])) {
260+
result[i] = nums[j] * nums[j];
261+
j++;
262+
} else {
263+
result[i] = nums[k] * nums[k];
264+
k--;
265+
}
266+
i--;
267+
}
268+
269+
return result;
270+
}
271+
}
272+
```
273+
274+
</TabItem>
275+
276+
<TabItem value="C++" label="C++">
277+
<SolutionAuthor name="@vansh-codes" />
278+
279+
```cpp
280+
class Solution {
281+
public:
282+
int sortedSquares(vector<int>& nums) {
283+
vector<int> result(nums.size());
284+
int i = nums.size()-1, j = 0, k = nums.size()-1;
285+
while(i >= 0)
286+
{
287+
if(abs(nums[j]) > abs(nums[k]))
288+
{
289+
result[i] = nums[j] * nums[j];
290+
++j;
291+
}
292+
else
293+
{
294+
result[i] = nums[k] * nums[k];
295+
--k;
296+
}
297+
--i;
298+
}
299+
return result;
300+
}
301+
};
302+
303+
```
304+
305+
</TabItem>
306+
</Tabs>
307+
308+
</TabItem>
309+
</Tabs>
310+
311+
## References
312+
313+
- **LeetCode Problem**: [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/description)
314+
315+
- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/squares-of-a-sorted-array/solutions/)

0 commit comments

Comments
 (0)