Skip to content

Instantly share code, notes, and snippets.

@renanreismartins
Created February 21, 2023 15:48
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 renanreismartins/43efce7997518880e0f96594a2051633 to your computer and use it in GitHub Desktop.
Save renanreismartins/43efce7997518880e0f96594a2051633 to your computer and use it in GitHub Desktop.
A bit better, much to be done. Maybe do both operations in one traverse, fix the imperative checks and 0 checks. But enough for the day
object MissingPositive extends App {
def missingPositive(nums: Array[Int]): Int = {
val found: Map[Int, Int] = nums.foldLeft(Map[Int, Int]())((m, i) => if (i >= 0) m + (i -> 1) else m)
val min = nums
.filter(e => e > 0)
.foldLeft(Integer.MAX_VALUE)((m, i) => i.min(m))
if (min >= 0) {
var count = 1
while (found.contains(count)) {
count += 1
}
count
} else {
min - 1
}
}
println(missingPositive(Array(1, 2, 0)))
println(missingPositive(Array(3, 4, -1, 1)))
println(missingPositive(Array(7, 8, 9, 11, 12)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment