I solved Codility's GenomicRangeQuery challenge in Scala. We are given a long DNA sequence (up to 100000 bases), where A, C, G, T are assigned values 1, 2, 3, 4, respectively. There are up to 50000 queries of the form (pi, qi), for each of which we should return the smallest value in the DNA string between positions pi and qi (inclusive, and zero-based).
I came up with the following solutions, both of which got 100% correctness but 0% performance. I'd like to know what can I do to improve the performance of these functions.
Answer #1
def solution(s: String, p: Array[Int], q: Array[Int]): Array[Int] = {
for (i <- p.indices.toArray) yield {
val gen = s.substring(p(i), q(i) + 1)
gen match {
case _ if gen.contains('A') => 1
case _ if gen.contains('C') => 2
case _ if gen.contains('G') => 3
case _ if gen.contains('T') => 4
}
}
}
Answer #2
def solution(s: String, p: Array[Int], q: Array[Int]): Array[Int] = {
val weights =
for (c <- s.toCharArray) yield c match {
case 'A' => 1
case 'C' => 2
case 'G' => 3
case 'T' => 4
}
for (i <- p.indices.toArray) yield weights.slilce(p(i), q(i) + 1).min
}