Skip to content

Commit 914494c

Browse files
Merge branch 'main' into main
2 parents 1abc74f + ca4ab8b commit 914494c

16 files changed

+2040
-91
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ At CodeHarborHub, our mission is clear: to provide accessible and comprehensive
2828

2929
Now, resolve your all doubts and communicate with our all contributors.
3030

31-
[![](https://img.shields.io/badge/Discord-5865F2.svg?style=for-the-badge&logo=Discord&logoColor=white)](https://discord.com/channels/1231112132595028008/1238672287037919333)
31+
[![](https://img.shields.io/badge/Discord-5865F2.svg?style=for-the-badge&logo=Discord&logoColor=white)](https://discord.com/channels/1231112132595028008/1238672287037919333) [![Follow on LinkedIn](https://img.shields.io/badge/Follow%20on-LinkedIn-blue?style=for-the-badge&logo=linkedin)](https://www.linkedin.com/comm/mynetwork/discovery-see-all?usecase=PEOPLE_FOLLOWS&followMember=ajay-dhangar)
32+
3233

3334
## Getting Started
3435

Lines changed: 71 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
---
2-
32
id: subsets-ii
43
title: Subsets II
54
difficulty: Medium
@@ -31,58 +30,25 @@ Output: [[],[0]]
3130
- `1 <= nums.length <= 10`
3231
- `-10 <= nums[i] <= 10`
3332

34-
## Institution
35-
There are three important things to consider:
36-
37-
1. **Sort the Input:** Sort the `nums` array to handle duplicates easily.
38-
2. **Backtracking:** Use backtracking to generate subsets.
39-
3. **Avoid Duplicates:** Skip duplicates by checking if the current element is the same as the previous element and the previous element was not included in the current subset.
40-
41-
## Approach
42-
43-
# Generating All Unique Subsets
44-
45-
This solution defines a class `Solution` containing a method `subsetsWithDup` which generates all possible unique subsets for a given list of numbers, including handling duplicates.
46-
47-
## Implementation Steps
48-
49-
### Step 1: Define the `Solution` Class
50-
51-
Define a class `Solution` containing a method `subsetsWithDup` which takes a list of integers `nums` as input and returns a list of lists of integers.
52-
53-
### Step 2: Sort the Input List
54-
55-
Sort the `nums` list to handle duplicates easily.
56-
57-
### Step 3: Initialize Result List
58-
59-
Initialize an empty list called `result` to store the generated subsets.
60-
61-
### Step 4: Define the Backtracking Function
62-
63-
Define a function called `backtrack` which takes two parameters: `start` (the current index in `nums`) and `path` (the current subset being generated).
64-
65-
### Step 5: Append the Current Path
66-
67-
Append the current `path` to the `result`.
68-
69-
### Step 6: Loop Through the Elements
70-
71-
Loop through each element in `nums` starting from the `start` index:
72-
- If the current element is the same as the previous element and the previous element was not included in the current path, skip it to avoid duplicates.
73-
- Otherwise, include the current element in the path and recursively call the `backtrack` function with the next index.
33+
## Solution Approach
7434

75-
### Step 7: Call the Backtrack Function
35+
### Approach Overview
36+
The problem can be solved using backtracking. To handle duplicates, we need to sort the array first and then ensure that we do not include the same element twice in the same position within the subset.
7637

77-
Initially call the `backtrack` function with `start` set to 0 and an empty `path`.
38+
### Detailed Steps
7839

79-
### Step 8: Return Result
40+
1. **Sort the Input Array**:
41+
- Sorting helps in easily skipping duplicates.
42+
43+
2. **Backtracking Function**:
44+
- Use a helper function to generate all subsets.
45+
- Skip over duplicate elements by checking the previous element in the sorted array.
8046

81-
Return the `result` list.
47+
3. **Generate Subsets**:
48+
- Initialize an empty list to store all subsets.
49+
- Start backtracking from the first index.
8250

83-
This algorithm generates all possible unique subsets for a given list of numbers by using backtracking and handling duplicates by sorting the input list and skipping duplicate elements appropriately.
84-
85-
## Code
51+
## Code Examples
8652

8753
### C++
8854
```cpp
@@ -92,17 +58,17 @@ public:
9258
vector<vector<int>> result;
9359
vector<int> subset;
9460
sort(nums.begin(), nums.end());
95-
backtrack(nums, result, subset, 0);
61+
backtrack(nums, 0, subset, result);
9662
return result;
9763
}
98-
64+
9965
private:
100-
void backtrack(vector<int>& nums, vector<vector<int>>& result, vector<int>& subset, int start) {
66+
void backtrack(vector<int>& nums, int start, vector<int>& subset, vector<vector<int>>& result) {
10167
result.push_back(subset);
10268
for (int i = start; i < nums.size(); ++i) {
103-
if (i > start && nums[i] == nums[i - 1]) continue; // skip duplicates
69+
if (i > start && nums[i] == nums[i - 1]) continue;
10470
subset.push_back(nums[i]);
105-
backtrack(nums, result, subset, i + 1);
71+
backtrack(nums, i + 1, subset, result);
10672
subset.pop_back();
10773
}
10874
}
@@ -114,16 +80,16 @@ private:
11480
class Solution:
11581
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
11682
def backtrack(start, path):
117-
result.append(path)
83+
res.append(path)
11884
for i in range(start, len(nums)):
11985
if i > start and nums[i] == nums[i - 1]:
12086
continue
12187
backtrack(i + 1, path + [nums[i]])
122-
88+
12389
nums.sort()
124-
result = []
90+
res = []
12591
backtrack(0, [])
126-
return result
92+
return res
12793
```
12894

12995
### Java
@@ -132,22 +98,60 @@ class Solution {
13298
public List<List<Integer>> subsetsWithDup(int[] nums) {
13399
List<List<Integer>> result = new ArrayList<>();
134100
Arrays.sort(nums);
135-
backtrack(result, new ArrayList<>(), nums, 0);
101+
backtrack(nums, 0, new ArrayList<>(), result);
136102
return result;
137103
}
138-
139-
private void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums, int start) {
140-
result.add(new ArrayList<>(tempList));
104+
105+
private void backtrack(int[] nums, int start, List<Integer> subset, List<List<Integer>> result) {
106+
result.add(new ArrayList<>(subset));
141107
for (int i = start; i < nums.length; i++) {
142-
if (i > start && nums[i] == nums[i - 1]) continue; // skip duplicates
143-
tempList.add(nums[i]);
144-
backtrack(result, tempList, nums, i + 1);
145-
tempList.remove(tempList.size() - 1);
108+
if (i > start && nums[i] == nums[i - 1]) continue;
109+
subset.add(nums[i]);
110+
backtrack(nums, i + 1, subset, result);
111+
subset.remove(subset.size() - 1);
146112
}
147113
}
148114
}
149115
```
150116

117+
### C
118+
```c
119+
#include <stdlib.h>
120+
121+
// Function to sort the array
122+
int compare(const void *a, const void *b) {
123+
return (*(int*)a - *(int*)b);
124+
}
125+
126+
void backtrack(int* nums, int numsSize, int start, int* subset, int subsetSize, int** result, int* returnSize, int** columnSizes) {
127+
result[*returnSize] = (int*)malloc(subsetSize * sizeof(int));
128+
for (int i = 0; i < subsetSize; i++) {
129+
result[*returnSize][i] = subset[i];
130+
}
131+
(*columnSizes)[*returnSize] = subsetSize;
132+
(*returnSize)++;
133+
134+
for (int i = start; i < numsSize; i++) {
135+
if (i > start && nums[i] == nums[i - 1]) continue;
136+
subset[subsetSize] = nums[i];
137+
backtrack(nums, numsSize, i + 1, subset, subsetSize + 1, result, returnSize, columnSizes);
138+
}
139+
}
140+
141+
int** subsetsWithDup(int* nums, int numsSize, int* returnSize, int** columnSizes) {
142+
qsort(nums, numsSize, sizeof(int), compare);
143+
int** result = (int**)malloc(1000 * sizeof(int*));
144+
*returnSize = 0;
145+
*columnSizes = (int*)malloc(1000 * sizeof(int));
146+
int* subset = (int*)malloc(numsSize * sizeof(int));
147+
backtrack(nums, numsSize, 0, subset, 0, result, returnSize, columnSizes);
148+
free(subset);
149+
return result;
150+
}
151+
```
152+
151153
## Complexity
152-
- Time complexity: `O(2^n)`
153-
- Space complexity: `O(2^n)`
154+
155+
- **Time Complexity**: `O(2^n * n)`, where `n` is the length of the input array. This accounts for generating all subsets and sorting the array.
156+
157+
- **Space Complexity**: `O(2^n * n)`, as we need to store all subsets. Each subset can be of length `n` and there
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
---
2+
id: split-array-with-equal-sum
3+
title: Split Array with Equal Sum
4+
sidebar_label: 0548-split-array-with-equal-sum
5+
tags:
6+
- Array
7+
description: "This is a solution to the Number of Provincess problem on LeetCode."
8+
---
9+
10+
11+
## Problem Description
12+
13+
Given an array with `n` integers, you need to find if there are triplets `(i, j, k)` which satisfies following conditions:
14+
15+
1- `0 < i, i + 1 < j, j + 1 < k < n - 1`
16+
2- Sum of subarrays `(0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1)` should be equal.
17+
18+
where we define that subarray `(L, R)` represents a slice of the original array starting from the element indexed `L` to the element indexed `R`.
19+
20+
### Examples
21+
22+
**Example 1:**
23+
24+
```
25+
Input: [1,2,1,2,1,2,1]
26+
Output: True
27+
Explanation:
28+
i = 1, j = 3, k = 5.
29+
sum(0, i - 1) = sum(0, 0) = 1
30+
sum(i + 1, j - 1) = sum(2, 2) = 1
31+
sum(j + 1, k - 1) = sum(4, 4) = 1
32+
sum(k + 1, n - 1) = sum(6, 6) = 1
33+
34+
```
35+
36+
**Example 2:**
37+
38+
```
39+
Input: nums = [1,2,1,2,1,2,1,2]
40+
Output: false
41+
42+
```
43+
44+
45+
### Constraints
46+
47+
- `1 <= n <= 2000.`
48+
- Elements in the given array will be in range `[-1,000,000, 1,000,000].`
49+
50+
## Solution for Assign Cookies
51+
52+
### Approach:
53+
54+
1- Initialize `n` as the length of `nums` and `s` as the prefix sum array of size `n + 1`.
55+
2- Populate the prefix sum array `s`.
56+
3- Loop through possible middle split points `j` from `3` to `n - 3`.
57+
4- Use a set comprehension to collect valid prefix sums before `j`.
58+
5- Check if the valid suffix sum exists in the set, ensuring the conditions for splitting are met.
59+
60+
## Code in Different Languages
61+
62+
### C++
63+
64+
```cpp
65+
class Solution {
66+
public:
67+
bool splitArray(vector<int>& nums) {
68+
int n = nums.size();
69+
vector<int> s(n + 1);
70+
for (int i = 0; i < n; ++i) s[i + 1] = s[i] + nums[i];
71+
for (int j = 3; j < n - 3; ++j) {
72+
unordered_set<int> seen;
73+
for (int i = 1; i < j - 1; ++i)
74+
if (s[i] == s[j] - s[i + 1])
75+
seen.insert(s[i]);
76+
for (int k = j + 2; k < n - 1; ++k)
77+
if (s[n] - s[k + 1] == s[k] - s[j + 1] && seen.count(s[n] - s[k + 1]))
78+
return true;
79+
}
80+
return false;
81+
}
82+
};
83+
84+
85+
```
86+
### Java
87+
88+
```java
89+
class Solution {
90+
public boolean splitArray(int[] nums) {
91+
int n = nums.length;
92+
int[] s = new int[n + 1];
93+
for (int i = 0; i < n; ++i) {
94+
s[i + 1] = s[i] + nums[i];
95+
}
96+
for (int j = 3; j < n - 3; ++j) {
97+
Set<Integer> seen = new HashSet<>();
98+
for (int i = 1; i < j - 1; ++i) {
99+
if (s[i] == s[j] - s[i + 1]) {
100+
seen.add(s[i]);
101+
}
102+
}
103+
for (int k = j + 2; k < n - 1; ++k) {
104+
if (s[n] - s[k + 1] == s[k] - s[j + 1] && seen.contains(s[n] - s[k + 1])) {
105+
return true;
106+
}
107+
}
108+
}
109+
return false;
110+
}
111+
}
112+
113+
114+
```
115+
116+
### Python
117+
118+
```python
119+
class Solution:
120+
def splitArray(self, nums: List[int]) -> bool:
121+
n = len(nums)
122+
s = [0] * (n + 1)
123+
for i, v in enumerate(nums):
124+
s[i + 1] = s[i] + v
125+
for j in range(3, n - 3):
126+
seen = set()
127+
for i in range(1, j - 1):
128+
if s[i] == s[j] - s[i + 1]:
129+
seen.add(s[i])
130+
for k in range(j + 2, n - 1):
131+
if s[n] - s[k + 1] == s[k] - s[j + 1] and s[n] - s[k + 1] in seen:
132+
return True
133+
return False
134+
135+
```
136+
137+
## Complexity Analysis
138+
139+
### Time Complexity: O(n^2)
140+
141+
### Space Complexity: O(n)
142+
143+
## References
144+
145+
- **LeetCode Problem**: [Split Array with Equal Sum](https://leetcode.com/problems/split-array-with-equal-sum/)
146+

0 commit comments

Comments
 (0)