Hackerrank alternating characters
Challenge
Prit’s solution
(defn alternating-characters [s]
"TOC: 25m
Complexity: O(n), (= n (count s))"
(letfn [(find-indices [s]
(loop [s (seq s) indices {:A [] :B []} curr-index 0]
(if-not (empty? s)
(recur (rest s)
(if (= (first s) \A)
(assoc indices :A (conj (:A indices) curr-index))
(assoc indices :B (conj (:B indices) curr-index)))
(inc curr-index))
indices)))
(count-adjacent [indices]
(loop [a-indices indices last-char -2 num-adjacent 0]
(if-not (empty? a-indices)
(let [curr-char (first a-indices)]
(prn curr-char last-char)
(recur (rest a-indices) curr-char (if (= curr-char (inc last-char)) (inc num-adjacent)
num-adjacent)))
num-adjacent)))]
(let [indices (find-indices s)]
(->
(count-adjacent (:A indices))
(+ (count-adjacent (:B indices)))))))
(alternating-characters "AAABBAB")
The find-indices function returns the indices of the characters A and B in the form {:A [index-1 index-2 …] :B {index-1 index-2 …}}.
The count-adjacent counts how many adjacent numbers are present in a sorted array. For example in the array [1 2 3 4 6], there will be three adjacent numbers.
We find the indices at which the characters are present, count the adjacent indices in each case and add them. Tests 9-12 are failing due because “Time limit exceeded.“ Any ideas on how these tests can be passed?