As asked
Implement a binary search function in Scala that takes a sorted IndexedSeq[Int] and a target Int and returns an Option[Int] with the index. Write it tail-recursively and explain why tail recursion matters on the JVM.
Sample answer outline
The candidate should write a @tailrec inner helper with lo and hi parameters, computing mid = lo + (hi - lo) / 2 to avoid overflow. If arr(mid) == target return Some(mid); if target < arr(mid) search left; else search right. Return None when lo > hi. Tail recursion matters because the JVM does not optimize general recursion; @tailrec tells the compiler to verify it can be converted to a loop, avoiding StackOverflowError.
Reference implementation (scala)
def binarySearch(arr: IndexedSeq[Int], target: Int): Option[Int] = {
@annotation.tailrec
def loop(lo: Int, hi: Int): Option[Int] = ???
loop(0, arr.length - 1)
}Expect these follow-ups
- What does the @tailrec annotation do at compile time?
- How would you generalize this to work on any Ordered type?