Kindly review this scala code for given problem and suggest improvements.

Problem - Given an array of integers and a target sum, check if array contains a pair which adds up to sum.

Example -

i/p - (1,2,4,5,6) 7 
o/p - true 

i/p - (1,1,1,5,6) 2
o/p - true

i/p - (1,4,4,5,6) 13
o/p - false

Scala implementation

import scala.collection.immutable._

object FindMatchingSum {
  def containsMatchingSum(data: Array[Int], complementTable: Set[Int], sum: Int): Boolean = {
    if (data.isEmpty) false
    else if (complementTable contains data.head) true
    else containsMatchingSum(data.drop(1), complementTable ++ Set(sum-data.head), sum)
  }

  def main(args: Array[String]):Unit = {
    println(containsMatchingSum(Array(1,2,4,5,6), Set[Int](), 7))
    println(containsMatchingSum(Array(1,1,1,5,6), Set[Int](), 2))
    println(containsMatchingSum(Array(1,4,4,5,6), Set[Int](), 9))
    println(containsMatchingSum(Array(1,4,4,5,6), Set[Int](), 13))
  }
}

Sample run

scalac FindMatchingSum.scala                                                 
scala FindMatchingSum                                                        
true
true
true
false

If you're worried about efficiency you could copy the Array into a Vector or use an index instead of paring down the input.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.