Skip to content

Instantly share code, notes, and snippets.

@patroza
Forked from stzr1123/twoSum.scala
Last active November 4, 2019 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patroza/edef12261427ac3cc5498dab7704f96b to your computer and use it in GitHub Desktop.
Save patroza/edef12261427ac3cc5498dab7704f96b to your computer and use it in GitHub Desktop.
Interview type problems
import scala.annotation.tailrec
object ShittySolution {
// Given an array of integers, return indices of the two numbers such that they add up to a specific target.
//
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// https://leetcode.com/problems/two-sum/
// NB: More efficient solution would iterate once over the array and keep a Map of values and indicies
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
for (idx <- 0 until nums.length - 1) {
for (idy <- idx + 1 until nums.length) {
if (nums(idx) + nums(idy) == target) {
return Array(idx, idy)
}
}
}
throw new IllegalArgumentException("No solution exists")
}
def functionalTwoSum(nums: Array[Int], target: Int): Array[Int] = {
recursiveTwoSum(nums.zipWithIndex, target) match {
case Some((idx, idy)) => Array(idx, idy)
case None => throw new IllegalArgumentException("No solution exists")
}
}
@tailrec
def recursiveTwoSum(nums: Seq[(Int, Int)], target: Int): Option[(Int, Int)] = {
nums match {
case Nil => None
case head::tail => tail.find{
case (elem, _) => elem + head._1 == target
} match {
case Some((_: Int, idy: Int)) => Some(head._2, idy)
case None => recursiveTwoSum(tail, target)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment