URL: https://leetcode.com/problems/find-missing-and-repeated-values/ Signed-off-by: Matej Focko <me@mfocko.xyz>
21 lines
686 B
Kotlin
21 lines
686 B
Kotlin
class Solution {
|
|
fun findMissingAndRepeatedValues(grid: Array<IntArray>): IntArray {
|
|
val n = grid.size.toLong()
|
|
val n2 = n.toLong() * n
|
|
|
|
val (sum, sumOfSquares) =
|
|
grid.fold(0L to 0L) { acc, row ->
|
|
row.fold(acc) { (sum, sumOfSquares), x ->
|
|
sum + x to sumOfSquares + x * x
|
|
}
|
|
}
|
|
|
|
val sumDiff = sum - n2 * (n2 + 1) / 2
|
|
val sqrDiff = sumOfSquares - n2 * (n2 + 1) * (2 * n2 + 1) / 6
|
|
|
|
val repeating = ((sqrDiff / sumDiff + sumDiff) / 2).toInt()
|
|
val missing = ((sqrDiff / sumDiff - sumDiff) / 2).toInt()
|
|
|
|
return intArrayOf(repeating, missing)
|
|
}
|
|
}
|