Skip to content

Commit 77896b5

Browse files
committed
add 4sum
1 parent 087752d commit 77896b5

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ This is my way of saying - change your interview style. There are lots of smart
1616
| [House Robber](https://leetcode.com/problems/house-robber/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/house-robber.rb) |
1717
| [Array Product](https://leetcode.com/problems/product-of-array-except-self/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/product-of-array.rb) |
1818
| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/top-k-elements.rb) |
19+
| [Sum 4 arrays](https://leetcode.com/problems/4sum-ii/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/4-sum.rb) |
1920
| [Reverse String In-place](https://leetcode.com/problems/reverse-string/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/reverse-string-inplace.rb) |
2021
| [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/) | [click](https://github.com/sagivo/algorithms/blob/master/src/mirror.rb) |
2122
| [Dijkstra's shortest path between two nodes](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm) | [click](https://github.com/sagivo/algorithms/blob/master/src/dijkstra.rb) |

src/4-sum.rb

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# @param {Integer[]} a
2+
# @param {Integer[]} b
3+
# @param {Integer[]} c
4+
# @param {Integer[]} d
5+
# @return {Integer}
6+
7+
def four_sum_count(a, b, c, d)
8+
return check_4_sum(a, b, c, d)
9+
end
10+
11+
def create_set(a, b)
12+
h = {}
13+
for ai in a
14+
for bi in b
15+
h[ai + bi] ||= 0
16+
h[ai + bi] += 1
17+
end
18+
end
19+
return h
20+
end
21+
22+
def check_4_sum(a, b, c, d)
23+
tot = 0
24+
a1 = create_set(a, b)
25+
a2 = create_set(c, d)
26+
a1.each do |k, v|
27+
if a2[-1 * k]
28+
tot += v * a2[-1 * k]
29+
end
30+
end
31+
p a1, a2
32+
return tot
33+
end
34+
35+
p four_sum_count([-1,-1], [-1,1], [-1, 1], [1,-1])

0 commit comments

Comments
 (0)