Skip to content

Commit 5540ebc

Browse files
authored
Merge pull request neetcode-gh#2396 from Ritesh7766/main
Create 1498-number-of-subsequences-that-satisfy-the-given-sum-condition.cpp, 0018-4sum.cpp
2 parents 96e744c + acafd9c commit 5540ebc

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

cpp/0018-4sum.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Time Complexity = O(n^3)
2+
// Space Complexity = O(n)
3+
4+
class Solution {
5+
public:
6+
vector<vector<int>> fourSum(vector<int>& nums, int target) {
7+
sort(nums.begin(), nums.end());
8+
9+
vector<vector<int> > res;
10+
int n = nums.size();
11+
12+
for (int i = 0; i < n; i++) {
13+
if (i > 0 && nums[i] == nums[i - 1])
14+
continue;
15+
for (int j = i + 1; j < n; j++) {
16+
if (j > (i + 1) && nums[j] == nums[j - 1])
17+
continue;
18+
int l = j + 1, r = n - 1;
19+
while (l < r) {
20+
long sm = (long)nums[i] + (long)nums[j] + (long)nums[l] + (long)nums[r];
21+
if (sm == target) {
22+
res.push_back(vector<int>{nums[i], nums[j], nums[l], nums[r]});
23+
l += 1;
24+
while (l < r && nums[l] == nums[l - 1])
25+
l += 1;
26+
}
27+
else if (sm > target)
28+
r -= 1;
29+
else
30+
l += 1;
31+
}
32+
}
33+
}
34+
return res;
35+
}
36+
};
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Time Complexity - O(nlogn)
2+
// Space Complexity - O(n)
3+
4+
class Solution {
5+
public:
6+
int numSubseq(vector<int>& nums, int target) {
7+
sort(nums.begin(), nums.end());
8+
int n = nums.size();
9+
10+
int left = 0, right = n - 1;
11+
int res = 0, mod = 1e9 + 7;
12+
while (left <= right) {
13+
if (nums[left] + nums[right] > target) {
14+
right--;
15+
}
16+
else {
17+
res = (res + fastPower(2, right - left, mod)) % mod;
18+
left++;
19+
}
20+
}
21+
return res;
22+
}
23+
24+
int fastPower(int a, int b, int mod) {
25+
long long ans = 1;
26+
long long base = a;
27+
while (b != 0) {
28+
if (b % 2 == 1) {
29+
ans = (ans * base) % mod;
30+
}
31+
base = (base * base) % mod;
32+
b /= 2;
33+
}
34+
return ans;
35+
}
36+
};

0 commit comments

Comments
 (0)