@@ -26,22 +26,20 @@ class Solution:
26
26
```
27
27
28
28
## Iterative Solution with Map
29
- - Runtime: O(N* U )
30
- - Space: O(U )
29
+ - Runtime: O(N^2 )
30
+ - Space: O(N^2 )
31
31
- N = Number of elements in array
32
- - U = Number of unique sums (Worst case U=2^N)
33
32
34
33
We can use a dictionary to keep track of the sums and how many paths there are for each sum.
35
34
We just need to maintain a rolling dictionary as we traverse across the numbers.
36
35
Each traversal we will create new sums and add them into a new dictionary.
37
36
We will move the values across from the old dictionary as well.
38
37
39
- For the run-time, U can be 2^N for the worst case (2,4,8,16,32...).
40
- Now, you may think this is solution is terrible compared to the previous recursive solution.
41
- That maybe true but only if we were to always create a unique sum every single time.
42
- Maybe an input like [ 1,10,100,1000,10000...]
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.
43
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.
44
- So U is actually less than O(2^N) on most cases while the brute force solution above will always be ran at 2^N.
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.
45
43
46
44
```
47
45
from collections import defaultdict
0 commit comments