Skip to content

Instantly share code, notes, and snippets.

@vvgomes
Created June 12, 2026 01:12
Show Gist options
  • Select an option

  • Save vvgomes/b972e2e84adda264c9b98488d8150906 to your computer and use it in GitHub Desktop.

Select an option

Save vvgomes/b972e2e84adda264c9b98488d8150906 to your computer and use it in GitHub Desktop.
(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])))))
@vvgomes

vvgomes commented Jul 1, 2026

Copy link
Copy Markdown
Author

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:

(defn find-only-dup [ints]
  (- (reduce + ints) (reduce + (set ints))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment