Skip to content

Commit 63cae25

Browse files
authored
Summarizes technique for solving the problem.
1 parent 8a51e97 commit 63cae25

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

3Sum and 4Sum/README.md

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,22 @@
55
## 3Sum
66

77
> Given an array of integers, find all subsets of the array with 3 values where the 3 values sum up to a target number.
8-
8+
>
99
> **Note**: The solution subsets must not contain duplicate triplets.
10-
10+
>
1111
> For example, given the array [-1, 0, 1, 2, -1, -4], and the target **0**:
1212
> The solution set is: [[-1, 0, 1], [-1, -1, 2]] // The two **-1** values in the array are considered to be distinct
1313
14-
There are 3 key procedures in solving this algorithm:
14+
There are 2 key procedures in solving this algorithm. Sorting the array, and avoiding duplicates.
1515

16-
1. Sort the array in ascending order. This allows you to make smart decisions when moving indexes around (since duplicates will be adjacent to each other).
16+
### Pre-sorting
1717

18-
2. Ignoring duplicate values
18+
Sorting your input array allows for powerful assumptions:
1919

20-
3. Clever adjustment of indices for each pass.
20+
* duplicates are always adjacent to each other
21+
* moving an index to the right increases the value, while moving an index to the left decreases the value
22+
23+
You'll make use of these two rules to create an efficient algorithm.
2124

2225
#### Avoiding Duplicates
2326

@@ -67,8 +70,6 @@ extension BidirectionalCollection where Element: Equatable {
6770
}
6871
```
6972

70-
###
71-
7273
## 4Sum
7374
Given an array S of n integers, find all subsets of the array with 4 values where the 4 values sum up to a target number.
7475

0 commit comments

Comments
 (0)