You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
-**Time Complexity:** O(rows * cols), two complete passes over the data.
118
+
-**Space Complexity:** O(1), as we modify the input matrix directly.
119
+
120
+
### Approach 3: Optimized BFS with a 2-pass Solution
121
+
122
+
This uses the first two methods but optimizes BFS by reducing unnecessary checks using a two-pass solution similar to dynamic programming. This method can save some overhead in BFS initialization. Although very similar to the dynamic programming approach, careful attention is paid so initial BFS fills in skews of the grid minimizing the work in the main passes. The same code and logic apply for this optimization.
123
+
124
+
-**Time Complexity:** O(rows * cols)
125
+
-**Space Complexity:** O(rows * cols) for BFS queue usage, reducible to O(1) when done during passes.
-[Optimal Solution Using Stack](#optimal-solution-using-stack)
7
+
8
+
### Brute Force Approach
9
+
10
+
#### Intuition
11
+
The brute force solution involves checking every possible subsequence of length three for each triplet `(i, j, k)` with conditions `i < j < k` and `nums[i] < nums[k] < nums[j]`. This method essentially checks all combinations of triplets to see if they form the "132" pattern.
12
+
13
+
#### Approach
14
+
1. Use three nested loops to iterate over each possible triplet `(i, j, k)`.
15
+
2. For each triplet, check if they satisfy the "132" pattern: `nums[i] < nums[k] < nums[j]`.
16
+
3. If we find such a triplet, return `true`.
17
+
4. If we finish all iterations without finding such a triplet, return `false`.
18
+
19
+
#### Complexity
20
+
-**Time Complexity**: O(n^3), where n is the length of the input array.
21
+
-**Space Complexity**: O(1), as we use only a constant amount of extra space.
22
+
23
+
```csharp
24
+
publicboolFind132patternBruteForce(int[] nums)
25
+
{
26
+
intn=nums.Length;
27
+
for (inti=0; i<n; i++)
28
+
{
29
+
for (intj=i+1; j<n; j++)
30
+
{
31
+
for (intk=j+1; k<n; k++)
32
+
{
33
+
// Check for the "132" pattern
34
+
if (nums[i] <nums[k] &&nums[k] <nums[j])
35
+
{
36
+
returntrue;
37
+
}
38
+
}
39
+
}
40
+
}
41
+
returnfalse;
42
+
}
43
+
```
44
+
45
+
### Optimal Solution Using Stack
46
+
47
+
#### Intuition
48
+
This solution involves using a stack to efficiently find the "132" pattern. The idea is to iterate backward through the array and keep track of potential third elements (`nums[k]` in the pattern) using a stack. We maintain a variable to track the potential `nums[k]` as we traverse backwards. If we find a triplet satisfying the 132 conditions, we return true.
49
+
50
+
#### Approach
51
+
1. Initialize a stack to keep potential third elements (`nums[k]`).
52
+
2. Start traversing from the end of the array towards the beginning.
53
+
3. Keep track of the maximum `nums[k]` found (`third`), initially set to the minimum integer value.
54
+
4. For each element `nums[j]`, check if it can potentially be the middle element in the "132" pattern with `third` as `nums[k]`.
55
+
5. If `nums[j]` is less than `third`, we've found a valid "132" pattern.
56
+
6. If not, push `nums[j]` to the stack, updating `third` if necessary when elements are popped.
57
+
7. Continue until a pattern is found or all elements are processed.
58
+
59
+
#### Complexity
60
+
-**Time Complexity**: O(n), as each element is pushed and popped from the stack at most once.
61
+
-**Space Complexity**: O(n), due to the stack used to store elements.
62
+
63
+
```csharp
64
+
publicboolFind132patternOptimal(int[] nums)
65
+
{
66
+
intn=nums.Length;
67
+
intthird=Int32.MinValue;
68
+
Stack<int>stack=newStack<int>();
69
+
70
+
// Traverse from the end of the list to the beginning
71
+
for (inti=n-1; i>=0; i--)
72
+
{
73
+
// If current element is less than the third element of 132 pattern
74
+
if (nums[i] <third)
75
+
{
76
+
returntrue;
77
+
}
78
+
79
+
// Pop elements from stack until we find something larger than nums[i]
80
+
while (stack.Count>0&&nums[i] >stack.Peek())
81
+
{
82
+
// Update third
83
+
third=stack.Pop();
84
+
}
85
+
86
+
// Push current element onto the stack
87
+
stack.Push(nums[i]);
88
+
}
89
+
returnfalse;
90
+
}
91
+
```
92
+
93
+
This solution effectively utilizes a stack to achieve linear time complexity, providing an optimal solution to detect the "132" pattern in an array.
-[Sorting and Two-Pointer Approach](#sorting-and-two-pointer-approach)
4
6
5
-
### Solution
6
-
csharp
7
-
```csharp
8
-
// Time Complexity: O(n^3)
9
-
// Space Complexity: O(1) (excluding output list)
10
-
usingSystem;
11
-
usingSystem.Collections.Generic;
12
-
usingSystem.Linq;
7
+
### Brute Force Approach
8
+
The brute force approach for solving the 3Sum problem is to generate all possible triplets (i, j, k) where i < j < k. We then check if the sum of the elements at these indices is zero.
9
+
10
+
**Intuition:**
11
+
- Iterate through all unique pairs of indices (i, j, k) in the array, and check if their sum equals zero.
12
+
- Since we need combinations without repetitions, ensure i < j < k.
13
13
14
+
```csharp
14
15
publicclassSolution {
15
16
publicIList<IList<int>> ThreeSum(int[] nums) {
16
-
varresult=newHashSet<IList<int>>();
17
-
intn=nums.Length;
17
+
IList<IList<int>>result=newList<IList<int>>();
18
18
19
-
// Iterate through all possible triplets
20
-
for (inti=0; i<n-2; i++) {
21
-
for (intj=i+1; j<n-1; j++) {
22
-
for (intk=j+1; k<n; k++) {
19
+
// Iterate through all elements for the first number
if (item[0] ==triplet[0] &&item[1] ==triplet[1] &&item[2] ==triplet[2]) {
43
+
returntrue;
44
+
}
45
+
}
46
+
returnfalse;
33
47
}
34
48
}
35
49
```
36
50
37
-
## Approach 2: Two Pointers (Optimal)
51
+
**Time Complexity:** O(n^3)
52
+
**Space Complexity:** O(n), storing the result.
38
53
39
-
### Solution
40
-
csharp
41
-
```csharp
42
-
// Time Complexity: O(n^2)
43
-
// Space Complexity: O(n) (for sorting or output list)
44
-
usingSystem;
45
-
usingSystem.Collections.Generic;
46
-
usingSystem.Linq;
54
+
### Sorting and Two-Pointer Approach
55
+
This approach reduces the time complexity by first sorting the array and then using a two-pointer strategy to find the pairs that sum to the negative of each element.
47
56
57
+
**Intuition:**
58
+
- Sort the array. This helps in easily skipping duplicates and using a two-pointer method effectively.
59
+
- Fix one number a[i] and then find two numbers from the remaining part of the array which sum to -a[i].
60
+
- Use two pointers starting from both ends of the remaining array to find the combinations.
61
+
62
+
```csharp
48
63
publicclassSolution {
49
64
publicIList<IList<int>> ThreeSum(int[] nums) {
50
-
varresult=newList<IList<int>>();
51
-
Array.Sort(nums); // Sort the array to use two-pointer technique
0 commit comments