Skip to content

Commit 3809fd6

Browse files
author
rw
committed
twosum
1 parent bfa5d45 commit 3809fd6

File tree

4 files changed

+45
-0
lines changed

4 files changed

+45
-0
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,5 @@ run
44
```
55
nix-instantiate --eval leetcode.nix | jq -r 'fromjson | .'
66
```
7+
8+
or `just test`

justfile

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
test:
2+
nix-instantiate --eval leetcode.nix | jq -r 'fromjson | .'

leetcode.nix

+40
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,36 @@ let
3737
if iterations == 0 then guess
3838
else improve (nextGuess guess) (iterations - 1);
3939
in improve 1 iterations;
40+
# https://leetcode.com/problems/two-sum/
41+
twosum = nums: target:
42+
let
43+
h = {};
44+
add = (h: k: v: h // {k = v;});
45+
get = (h: k: h.k);
46+
in
47+
(builtins.foldl'
48+
(acc: num:
49+
let
50+
complement = target - num;
51+
in
52+
if builtins.length acc.ans > 0 then acc
53+
else
54+
if builtins.hasAttr (builtins.toString complement) h
55+
then acc // {
56+
ans = [get h complement acc.i];
57+
}
58+
else acc // {
59+
acc.h = add acc.h (builtins.toString complement) acc.i;
60+
i = acc.i + 1;
61+
}
62+
)
63+
{
64+
i = 0;
65+
h = h;
66+
ans = [];
67+
68+
}
69+
nums).ans;
4070

4171
# pickGifts = gifts: k:
4272
in
@@ -56,5 +86,15 @@ in
5686
(assert fib 6 == 8; "fib 6 is 8")
5787
(assert facTCO 15 == 1307674368000; "tail call optimized factorial works")
5888
(assert ftco 100 == 5050; "tail call optimized fibonacci works")
89+
# # nums = [2,7,11,15], target = 9
90+
# (assert twosum [2 7 11 15] 9 == [0 1]; "two sum works")
91+
# # Input: nums = [3,2,4], target = 6
92+
# # Output: [1,2]
93+
# (assert twosum [3 2 4] 6 == [1 2]; "two sum works")
94+
# # Input: nums = [3,3], target = 6
95+
# # Output: [0,1]
96+
# (assert twosum [3 3] 6 == [0 1]; "two sum works")
97+
5998
];
99+
twosum = twosum [2 7 11 15] 9;
60100
}

shell.nix

+1
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,6 @@ pkgs.mkShell {
44
pkgs.git
55
pkgs.nixfmt
66
pkgs.jq
7+
pkgs.just
78
];
89
}

0 commit comments

Comments
 (0)