Skip to content

Instantly share code, notes, and snippets.

@OlegEfrem
Last active November 21, 2019 11:46
Show Gist options
  • Save OlegEfrem/951d478c2d998634fc6d7a4b59077e3e to your computer and use it in GitHub Desktop.
Save OlegEfrem/951d478c2d998634fc6d7a4b59077e3e to your computer and use it in GitHub Desktop.
Find second minimum element from a list of integers in scala, complexity should be n (hence list can't be sorted).
package com.recbuc.receipts
import scala.annotation.tailrec
object SecondMinimum {
def main(args: Array[String]): Unit = {
val regular = List(5, 3, 2, 5, 1, 3, 1, -1, 2, -1, 5) // expected -1
val sorted = regular.sorted // expected -1
val distinct = sorted.distinct //expected 1
val reverse = distinct.reverse //expected 1
printSecondMin(secondMin(regular), "regular")
printSecondMin(secondMin(sorted), "sorted")
printSecondMin(secondMin(distinct), "distinct")
printSecondMin(secondMin(reverse), "reverse")
}
def printSecondMin(result: Option[Int], listType: String): Unit = {
println(s"$listType list second min is: " + result)
}
//note if we initialize first with list head and second with second head, we will not get expected results
@tailrec
def secondMin(list: List[Int], first: Option[Int] = None, second: Option[Int] = None): Option[Int] = {
list match {
case Nil => second
case h :: t =>
if (first.isEmpty)
secondMin(t, Some(h), second)
else if (first.exists(h < _)) //note if we say <= instead of < then second and first will alwasys be different
secondMin(t, Some(h), first)
else if (second.isEmpty || second.exists(h < _))
secondMin(t, first, Some(h))
else
secondMin(t, first, second)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment