Created
April 29, 2025 22:10
-
-
Save clementi/d14c7adaf037fe9142a0ab846ea60c5b to your computer and use it in GitHub Desktop.
Solution to the 3SUM problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (defn sum3 | |
| "Solve the 3SUM problem in O(n^2) time." | |
| [s] | |
| (def tab @{}) | |
| (def solutions @{}) | |
| (def len (length s)) | |
| (for k 0 len | |
| (put tab (s k) k)) | |
| (for i 0 len | |
| (for j 0 len | |
| (def k (get tab (- 0 (s i) (s j)))) | |
| (when (and k (not= k i) (not= k j) (not= i j)) | |
| (put solutions {i true j true k true} true)))) | |
| (map keys (keys solutions))) | |
| (let [arr @[2 4 1 3 8 7 -3 -1 12 -5 -8]] | |
| (printf "3sum of %j: " arr) | |
| (printf "%j" (sum3 arr))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment