Skip to content

Commit b09b8df

Browse files
committed
Solved problem 977 : Squares Of A Sorted Array
1 parent c1d33a0 commit b09b8df

File tree

2 files changed

+44
-3
lines changed

2 files changed

+44
-3
lines changed

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
### Problems Solved
1818

19-
| Total | 40 |
19+
| Total | 41 |
2020
|:---:|:---:|
2121

2222
#### Search By Topic
@@ -40,13 +40,13 @@
4040
| Sliding Window | 1 |
4141
| Stack | 2 |
4242
| Tries | 0 |
43-
| Two Pointers | 3 |
43+
| Two Pointers | 4 |
4444

4545
#### Search By Difficulty
4646

4747
| Difficulty | Number |
4848
|:---|---:|
49-
| Easy | 39 |
49+
| Easy | 40 |
5050
| Medium | 1 |
5151
| Hard | 0 |
5252

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
* Problem: 977
3+
* Name: Squares Of A Sorted Array
4+
* Difficulty: Easy
5+
* Topic: Two Pointers
6+
* Link: https://leetcode.com/problems/squares-of-a-sorted-array/
7+
*/
8+
9+
#include <bits/stdc++.h>
10+
using namespace std;
11+
12+
// Naive Approach
13+
// Time Complexity: O(n log n)
14+
// Space Complexity: O(1)
15+
vector<int> sortedSquaresSort(vector<int>& nums) {
16+
for (int idx = 0; idx < nums.size(); idx++){
17+
nums[idx] = nums[idx] * nums[idx];
18+
}
19+
sort(nums.begin(), nums.end());
20+
return nums;
21+
}
22+
23+
// Two Pointer Approach
24+
// Time Complexity: O(n)
25+
// Space Complexity: O(n)
26+
vector<int> sortedSquaresTwoPointers(vector<int>& nums) {
27+
vector<int> result(nums.size());
28+
int left = 0;
29+
int right = nums.size()-1;
30+
while (left <= right){
31+
if (abs(nums[left]) > abs(nums[right])){
32+
result[right - left] = nums[left] * nums[left];
33+
left++;
34+
}
35+
else {
36+
result[right - left] = nums[right] * nums[right];
37+
right--;
38+
}
39+
}
40+
return result;
41+
}

0 commit comments

Comments
 (0)