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
We can use a dictionary to keep track of the sums and how many paths there are for each sum.
34
31
We just need to maintain a rolling dictionary as we traverse across the numbers.
35
32
Each traversal we will create new sums and add them into a new dictionary.
36
33
We will move the values across from the old dictionary as well.
37
34
38
-
For the run-time, you may think that the run-time hasn't changed.
39
-
Why is this an improvement?
40
-
An input like [1,10,100,1000,10000...] will achieve N^2 run time.
41
-
However, given any other input, since its add and subtract and not multiply or divide, its unlikely and its more likely we will have overlapping sums.
42
-
So the run time is actually less than O(2^N) on most cases while the brute force solution above will always be ran at 2^N.
35
+
The dictionary is used to exploit the fact that there can be overlapping sums.
36
+
You can imagine the dictionary used for each height/level of the recursion tree, gathering all the sums from the previous summation and reusing it to recalcuate for the current height.
37
+
38
+
```
39
+
Sums for each height, Key: sum, Val: n_paths
40
+
1 {1: 1, -1: 1}
41
+
+/ \-
42
+
1 1 {2: 1, 0: 2, -2: 1}
43
+
+/ \- +/ \-
44
+
1 1 1 1 {3: 1, 1: 3, -1: 3, -3: 1}
45
+
```
46
+
47
+
You may think to yourself that the run-time hasn't changed.
48
+
You are correct, if given a set of numbers that would create unique sums for each height of the tree, this would end up being O(2^N).
49
+
However, since this question is done with addition and subtract, it is more likely there will be overlapping sums.
50
+
So the run-time is actually less than O(2^N) for the average case.
0 commit comments