Fork me on GitHub

Challenge:;playlist_slugs%5B%5D=interview-preparation-kit&amp;playlist_slugs%5B%5D=warmup My attempt:

(defn sockMerchant [n ar]
  "Complexity: O(n), (= (count ar) n)
   TOC: ~14 min"
  (reduce + (map (fn [[_ v]] (if (>= v 2) (quot v 2) 0))
       (frequencies ar)))
  #_(->> (map (fn [[k v]] (if (>= v 2) [k (rem v 2)] nil))
          (frequencies ar)) ;; looked up online
     (remove nil?)) ;; looked up online

(sockMerchant 7 [10 20 20 10 10 30 50 10 20])


Challenge:;playlist_slugs%5B%5D=interview-preparation-kit&amp;playlist_slugs%5B%5D=warmup My attempt:

(defn countingValleys [steps path]
  "Complexity: O(n), (= steps n)
   TOC: ~ 28 min"
  (loop [path- (split path #"") dist-from-sea 0 valleys 0] ;; looked up online
    (if (seq path-) ;; looked up online
      (if (= (first path-) "U")
        (recur (rest path-) (inc dist-from-sea)
               (if (= (inc dist-from-sea) 0) (inc valleys) valleys))
        (recur (rest path-) (dec dist-from-sea) valleys))

(countingValleys 8 "UDDDUDUU")


My first comment would be that camelCase is not idiomatic in Clojure — kebab-case is what folks will expect.

💯 3

(Weird puzzle: sock merchant doesn’t use n at all, but it’s supposed to be the length of the array? And you’re passing 7 instead of 9 in your call)


For the sock merchant, I’d go with something more straightforward that is closer to the problem statement:

user=> (defn sock-merchant [n ar] 
         (reduce (fn [[socks pairs] sock] 
                   (if (contains? socks sock) 
                     [(disj socks sock) (inc pairs)] 
                     [(conj socks sock) pairs])) 
                 [#{} 0] 
That returns a pair: the unmatched socks leftover and the number of pairs matched.

👍 3

I like this solution. Occasionally, I fall in the trap of always looking for the “higher level” solution where a more “procedural” solution would be OK.


In the second function, using - as a suffix on a binding is a bit unusual. Most people would just reuse path (and shadow the parameter) or maybe use path'.


I’d probably use (seq path) instead of (split path #"") and then (if path ..) inside the loop, and recur with (next path)next returns nil on an empty sequence, rest returns an empty sequence. And test against \U at that point since (seq "str") produces (\s \t \r) with characters, not strings.


Otherwise, I’d probably follow the same overall structure as you did @ps for counting-valleys.