Skip to content

Commit 845e35e

Browse files
authored
Merge pull request #762 from Hemav009/hs
Added leetcode solutions 18-20
2 parents 76b9b33 + f91c7aa commit 845e35e

File tree

3 files changed

+478
-0
lines changed

3 files changed

+478
-0
lines changed
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
---
2+
id: FourSum
3+
title: 4Sum (LeetCode)
4+
sidebar_label: 0018-FourSum
5+
tags:
6+
- Two Pointers
7+
description: "Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]]"
8+
---
9+
10+
## Problem Description
11+
12+
| Problem Statement | Solution Link | LeetCode Profile |
13+
| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ |
14+
| [4Sum](https://leetcode.com/problems/4sum/description/) | [4Sum Solution on LeetCode](https://leetcode.com/problems/4sum/solutions/) | [Abhinash Singh](https://leetcode.com/u/singhabhinash/) |
15+
16+
### Problem Description
17+
18+
Given an array `nums` of `n` integers, return an array of all the unique quadruplets `[nums[a], nums[b], nums[c], nums[d]]` such that:
19+
20+
- `0 <= a, b, c, d < n`
21+
- `a, b, c, and d are distinct`
22+
- `nums[a] + nums[b] + nums[c] + nums[d] == target`
23+
24+
You may return the answer in any order.
25+
26+
### Examples
27+
28+
#### Example 1
29+
30+
- **Input:** `nums = [1,0,-1,0,-2,2], target = 0`
31+
- **Output:** `[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]`
32+
33+
#### Example 2
34+
35+
- **Input:** `nums = [2,2,2,2,2], target = 8`
36+
- **Output:** `[[2,2,2,2]]`
37+
38+
### Constraints
39+
40+
- $1 <= nums.length <= 200$
41+
- $-10^9 <= nums[i] <= 10^9$
42+
- $-10^9 <= target <= 10^9$
43+
44+
### Approach
45+
46+
To solve the problem, we can use the following approach:
47+
48+
1. Sort the input array of integers `nums`.
49+
2. Initialize an empty set `s`, and an empty list `output`.
50+
3. Use nested loops to iterate through all possible combinations of quadruplets in `nums`.
51+
4. For each combination, use two pointers (`k` and `l`) to traverse the sub-array between the second and second-to-last elements of the combination.
52+
5. At each iteration of the innermost while loop, calculate the sum of the current quadruplet and check if it is equal to the target.
53+
6. If the sum is equal to the target, insert the quadruplet into the set `s` and increment both pointers (`k` and `l`).
54+
7. If the sum is less than the target, increment the pointer `k`.
55+
8. If the sum is greater than the target, decrement the pointer `l`.
56+
9. After all quadruplets have been checked, iterate through the set `s` and add each quadruplet to the `output` list.
57+
10. Return the `output` list.
58+
59+
### Solution Code
60+
61+
#### Python
62+
63+
```python
64+
class Solution:
65+
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
66+
nums.sort()
67+
s = set()
68+
output = []
69+
for i in range(len(nums)):
70+
for j in range(i + 1, len(nums)):
71+
k = j + 1
72+
l = len(nums) - 1
73+
while k < l:
74+
sum = nums[i] + nums[j] + nums[k] + nums[l]
75+
if sum == target:
76+
s.add((nums[i], nums[j], nums[k], nums[l]))
77+
k += 1
78+
l -= 1
79+
elif sum < target:
80+
k += 1
81+
else:
82+
l -= 1
83+
output = list(s)
84+
return output
85+
```
86+
87+
#### C++
88+
89+
```cpp
90+
class Solution {
91+
public:
92+
vector<vector<int>> fourSum(vector<int>& nums, int target) {
93+
sort(nums.begin(), nums.end());
94+
set<vector<int>> s;
95+
vector<vector<int>> output;
96+
for (int i = 0; i < nums.size(); i++) {
97+
for(int j = i + 1; j < nums.size(); j++) {
98+
int k = j + 1;
99+
int l = nums.size() - 1;
100+
while (k < l) {
101+
long long sum = nums[i];
102+
sum += nums[j];
103+
sum += nums[k];
104+
sum += nums[l];
105+
if (sum == target) {
106+
s.insert({nums[i], nums[j], nums[k], nums[l]});
107+
k++;
108+
l--;
109+
} else if (sum < target) {
110+
k++;
111+
} else {
112+
l--;
113+
}
114+
}
115+
}
116+
}
117+
for(auto quadruplets : s)
118+
output.push_back(quadruplets);
119+
return output;
120+
}
121+
};
122+
```
123+
124+
#### Java
125+
126+
```java
127+
class Solution {
128+
public List<List<Integer>> fourSum(int[] nums, int target) {
129+
Arrays.sort(nums);
130+
Set<List<Integer>> s = new HashSet<>();
131+
List<List<Integer>> output = new ArrayList<>();
132+
for (int i = 0; i < nums.length; i++) {
133+
for (int j = i + 1; j < nums.length; j++) {
134+
int k = j + 1;
135+
int l = nums.length - 1;
136+
while (k < l) {
137+
long sum = nums[i];
138+
sum += nums[j];
139+
sum += nums[k];
140+
sum += nums[l];
141+
if (sum == target) {
142+
s.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
143+
k++;
144+
l--;
145+
} else if (sum < target) {
146+
k++;
147+
} else {
148+
l--;
149+
}
150+
}
151+
}
152+
}
153+
output.addAll(s);
154+
return output;
155+
}
156+
}
157+
```
158+
159+
### Conclusion
160+
161+
The given solution sorts the input list and uses a nested loop structure with two pointers to find all unique quadruplets that sum up to the target. By using a set to store the quadruplets, it ensures that duplicates are avoided. The solution efficiently narrows down potential combinations by adjusting the pointers based on the current sum relative to the target. This approach is effective for generating the required output while maintaining uniqueness.
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
---
2+
id: remove-nth-node-from-end-of-list
3+
title: Remove nth node from end of list (LeetCode)
4+
sidebar_label: 0019-remove-nth-node-from-end-of-list
5+
tags:
6+
- Two Pointers
7+
- Linked List
8+
description: "Given the head of a linked list, remove the nth node from the end of the list and return its head."
9+
---
10+
11+
## Problem Description
12+
13+
| Problem Statement | Solution Link | LeetCode Profile |
14+
| :-------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------ |
15+
| [Remove nth node from end of list](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/) | [Remove nth node from end of list on LeetCode](https://leetcode.com/problems/remove-nth-node-from-end-of-list/solutions/) | [Areetra Halder](https://leetcode.com/u/areetrahalder/) |
16+
17+
### Problem Description
18+
19+
Given the head of a linked list, remove the nth node from the end of the list and return its head.
20+
21+
### Examples
22+
23+
#### Example 1
24+
25+
- **Input:** `head = [1,2,3,4,5], n = 2`
26+
- **Output:** `[1,2,3,5]`
27+
28+
#### Example 2
29+
30+
- **Input:** `head = [1], n = 1`
31+
- **Output:** `[]`
32+
33+
#### Example 3
34+
35+
- **Input:** `head = [1,2], n = 1`
36+
- **Output:** `[1]`
37+
38+
### Constraints
39+
40+
- The number of nodes in the list is sz.
41+
- $1 <= sz <= 30$
42+
- $0 <= Node.val <= 100$
43+
- $1 <= n <= sz$
44+
45+
### Approach
46+
47+
1. Calculate the size of the Single Linked List. We need to travel to the prev node of the node to be removed thus we perform reduce size by n
48+
2. If the node to be removed is the first node (size == 0) then we can simply return the next node of head since it will be null if the list has only one node.
49+
3. Traverse till the prev node using a loop again
50+
4. Skip the next node by linking the prev node to the next of next node. If not present, assign null.
51+
5. Finally return the head.
52+
53+
### Solution Code
54+
55+
#### Python
56+
57+
```python
58+
# Definition for singly-linked list.
59+
# class ListNode(object):
60+
# def __init__(self, val=0, next=None):
61+
# self.val = val
62+
# self.next = next
63+
class Solution(object):
64+
def removeNthFromEnd(self, head, n):
65+
length = self.findLength(head)
66+
i, traverseTill = 0, length - n - 1
67+
if traverseTill == -1:
68+
return head.next
69+
curr = head
70+
while i < traverseTill:
71+
curr = curr.next
72+
i += 1
73+
curr.next = curr.next.next
74+
return head
75+
76+
def findLength(self, head):
77+
count = 0
78+
if head is None:
79+
return count
80+
curr = head
81+
while curr is not None:
82+
count += 1
83+
curr = curr.next
84+
return count
85+
```
86+
87+
#### Java
88+
89+
```java
90+
/**
91+
* Definition for singly-linked list.
92+
* public class ListNode {
93+
* int val;
94+
* ListNode next;
95+
* ListNode() {}
96+
* ListNode(int val) { this.val = val; }
97+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
98+
* }
99+
*/
100+
class Solution {
101+
public ListNode removeNthFromEnd(ListNode head, int n) {
102+
int length = findLength(head);
103+
int i = 0, traverseTill = length - n - 1;
104+
if(traverseTill == -1) return head.next;
105+
ListNode curr = head;
106+
while(i < traverseTill){
107+
curr = curr.next;
108+
i++;
109+
}
110+
curr.next = curr.next.next;
111+
return head;
112+
}
113+
public int findLength(ListNode head){
114+
int count = 0;
115+
if(head == null) return count;
116+
ListNode curr = head;
117+
while(curr != null){
118+
count++;
119+
curr = curr.next;
120+
}
121+
return count;
122+
}
123+
}
124+
```
125+
126+
#### C++
127+
128+
```cpp
129+
/**
130+
* Definition for singly-linked list.
131+
* struct ListNode {
132+
* int val;
133+
* ListNode *next;
134+
* ListNode() : val(0), next(nullptr) {}
135+
* ListNode(int x) : val(x), next(nullptr) {}
136+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
137+
* };
138+
*/
139+
class Solution {
140+
public:
141+
ListNode* removeNthFromEnd(ListNode* head, int n) {
142+
int length = 0;
143+
ListNode* curr = head;
144+
145+
// Calculate the length of the linked list
146+
while (curr != nullptr) {
147+
length++;
148+
curr = curr->next;
149+
}
150+
151+
// Find the position to remove
152+
int traverseTill = length - n - 1;
153+
int i = 0;
154+
curr = head;
155+
156+
// If the head needs to be removed
157+
if (traverseTill == -1) {
158+
head = head->next;
159+
delete curr;
160+
return head;
161+
}
162+
163+
// Traverse to the node before the one to be removed
164+
while (i < traverseTill) {
165+
curr = curr->next;
166+
i++;
167+
}
168+
169+
// Remove the nth node from the end
170+
ListNode* temp = curr->next;
171+
curr->next = curr->next->next;
172+
delete temp;
173+
174+
return head;
175+
}
176+
};
177+
```

0 commit comments

Comments
 (0)