Skip to content

Commit b6d2ec5

Browse files
author
Joseph Luce
authored
Update 494_target_sum.md
1 parent 0e8ae6d commit b6d2ec5

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed

leetcode/medium/494_target_sum.md

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,22 +26,20 @@ class Solution:
2626
```
2727

2828
## Iterative Solution with Map
29-
- Runtime: O(N*U)
30-
- Space: O(U)
29+
- Runtime: O(N^2)
30+
- Space: O(N^2)
3131
- N = Number of elements in array
32-
- U = Number of unique sums (Worst case U=2^N)
3332

3433
We can use a dictionary to keep track of the sums and how many paths there are for each sum.
3534
We just need to maintain a rolling dictionary as we traverse across the numbers.
3635
Each traversal we will create new sums and add them into a new dictionary.
3736
We will move the values across from the old dictionary as well.
3837

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.
4341
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.
4543

4644
```
4745
from collections import defaultdict

0 commit comments

Comments
 (0)