Created
June 12, 2026 01:12
-
-
Save vvgomes/b972e2e84adda264c9b98488d8150906 to your computer and use it in GitHub Desktop.
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
| (ns foobar | |
| (:require [clojure.test :refer [deftest is testing]])) | |
| (defn init-count [hm k] | |
| (assoc hm k 0)) | |
| (defn inc-count [hm k] | |
| (update-in hm [k] inc)) | |
| (defn find-dup [coll] | |
| (let [counts (reduce init-count {} (set coll)) | |
| max-entry (apply max-key val (reduce inc-count counts coll))] | |
| (when (> (val max-entry) 1) (key max-entry)))) | |
| (deftest find-dup-tests | |
| (testing "finds first occurency of adjacent repeated values" | |
| (is (= 3 (find-dup [1 2 3 3 4 5])))) | |
| (testing "find nothing when there are no repeated values" | |
| (is (nil? (find-dup [1 2 3 4 5])))) | |
| (testing "finds first ocurrency of non-adjacent repeated values" | |
| (is (= 3 (find-dup [1 2 3 4 5 3])))) | |
| (testing "finds most frequent repeated values" | |
| (is (= 2 (find-dup [1 2 3 4 5 3 2 2 4]))))) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is a specific scenario in which there can be only one duplicate number in the collection. In that case, finding the duplicate is as simple as finding the collection intersection with its set: