Back to Blog

Kotlin with Copilot: Find the 2 numbers in the list that add up to 9

Sandy LaneSandy Lane

Video: Kotlin with Copilot: Find the 2 numbers in the list that add up to 9 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin with Copilot: Find the 2 Numbers in the List That Add Up to 9

In this example, we use Kotlin to find two numbers in a list that sum up to a target value, specifically 9. The solution demonstrates a straightforward approach using a hash set to efficiently check for the complement of each number while iterating through the list.

Code

fun findTwoNumbersThatAddUpToTarget(numbers: List<Int>, target: Int): Pair<Int, Int>? {
  val seen = mutableSetOf<Int>()  // Keep track of numbers we've seen so far
  for (num in numbers) {
    val complement = target - num
    if (complement in seen) {
      return Pair(complement, num)  // Found the pair that adds up to target
    }
    seen.add(num)  // Add current number to the set
  }
  return null  // No pair found that adds up to target
}

fun main() {
  val list = listOf(2, 7, 11, 15)
  val target = 9
  val result = findTwoNumbersThatAddUpToTarget(list, target)
  if (result != null) {
    println("Pair found: ${result.first} + ${result.second} = $target")
  } else {
    println("No pair found that adds up to $target")
  }
}

Key Points

  • Use a hash set to track numbers seen so far for efficient complement lookup.
  • Check if the complement (target - current number) exists in the set to find the pair.
  • Return the first pair found that sums to the target or null if none exists.
  • This approach runs in O(n) time, making it efficient for large lists.