Skip to content

Commit d8087b6

Browse files
Merge branch 'CodeHarborHub:main' into patch-1
2 parents 04bc612 + 0a54399 commit d8087b6

14 files changed

+3759
-75
lines changed

dsa-problems/gfg-problems/medium/0401-0500.md

Lines changed: 622 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
---
2+
id: Counting-Sort
3+
title: Counting Sort (Geeks for Geeks)
4+
sidebar_label: Counting Sort
5+
tags:
6+
- Beginner
7+
- Sorting Algorithms
8+
- Geeks for Geeks
9+
- CPP
10+
- Python
11+
- Java
12+
- JavaScript
13+
- DSA
14+
description: "This is a solution to the Counting Sort problem on Geeks for Geeks."
15+
---
16+
17+
## 1. What is Counting Sort?
18+
19+
Counting Sort is a non-comparison-based sorting algorithm. It works by counting the number of occurrences of each unique element in the input array. The algorithm uses this count information to place the elements in their correct positions in the output array.
20+
21+
## 2. Algorithm for Counting Sort
22+
23+
1. Find the maximum element in the input array.
24+
2. Create a count array of size (maximum element + 1) and initialize all elements to 0.
25+
3. Count the occurrences of each element in the input array and store it in the count array.
26+
4. Modify the count array such that each element at each index stores the sum of previous counts.
27+
5. Output each element from the input array into the correct sorted position in the output array.
28+
29+
## 3. How does Counting Sort work?
30+
31+
- Counting Sort calculates the position of each element in the sorted array by using the count array.
32+
- The count array stores the count of each unique element.
33+
- By iterating through the input array and the count array, elements are placed into their correct positions in the output array.
34+
35+
## 4. Problem Description
36+
37+
Given an array of integers, implement the Counting Sort algorithm to sort the array in ascending order.
38+
39+
## 5. Examples
40+
41+
**Example 1:**
42+
```markdown
43+
Input: [4, 2, 2, 8, 3, 3, 1]
44+
Output: [1, 2, 2, 3, 3, 4, 8]
45+
46+
**Example 2:**
47+
```markdown
48+
Input: [7, 4, 4, 6, 2, 1, 5, 3, 8, 5]
49+
Output: [1, 2, 3, 4, 4, 5, 5, 6, 7, 8]
50+
```
51+
52+
**Explanation of Example 1:**
53+
- The initial array is [4, 2, 2, 8, 3, 3, 1].
54+
- Count array: [0, 1, 2, 2, 1, 0, 0, 0, 1]
55+
- Sorted array: [1, 2, 2, 3, 3, 4, 8]
56+
57+
## 6. Constraints
58+
59+
- The array can have any number of elements.
60+
- All elements in the array are non-negative integers.
61+
62+
## 7. Implementation
63+
64+
```java
65+
public class CountingSort {
66+
public static void countingSort(int arr[]) {
67+
int largest = Integer.MIN_VALUE;
68+
for (int i = 0; i < arr.length; i++) {
69+
largest = Math.max(largest, arr[i]);
70+
}
71+
72+
int count[] = new int[largest + 1];
73+
74+
for (int i = 0; i < arr.length; i++) {
75+
count[arr[i]]++;
76+
}
77+
78+
int j = 0;
79+
for (int i = 0; i < count.length; i++) {
80+
while (count[i] > 0) {
81+
arr[j] = i;
82+
j++;
83+
count[i]--;
84+
}
85+
}
86+
}
87+
88+
public static void main(String[] args) {
89+
int[] arr = {4, 2, 2, 8, 3, 3, 1};
90+
countingSort(arr);
91+
for (int num : arr) {
92+
System.out.print(num + " ");
93+
}
94+
}
95+
}
96+
```
97+
98+
## 8. Complexity Analysis
99+
100+
- **Time Complexity**:
101+
- Best case: $O(n + k)$
102+
- Average case: $O(n + k)$
103+
- Worst case: $O(n + k)$
104+
- where (n) is the number of elements in the input array and (k) is the range of the input.
105+
106+
- **Space Complexity**: $O(n + k)$
107+
108+
## 9. Advantages and Disadvantages
109+
110+
**Advantages:**
111+
- Simple to implement.
112+
- Efficient for sorting integers when the range of the input values is not significantly greater than the number of elements.
113+
114+
**Disadvantages:**
115+
- Not suitable for sorting strings or floating-point numbers.
116+
- The space complexity can be high if the range of input values is very large.
117+
118+
## 10. References
119+
120+
- **GFG Article on Counting Sort:** [Geeks for Geeks Counting Sort](https://www.geeksforgeeks.org/counting-sort/)
121+
- **GFG Problem** [Counting Sort Problem](https://www.geeksforgeeks.org/problems/counting-sort/1)
122+
- **Wikipedia Article on Counting Sort:** [Counting Sort - Wikipedia](https://en.wikipedia.org/wiki/Counting_sort)
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.

0 commit comments

Comments
 (0)