kt: add «2965. Find Missing and Repeated Values»

URL:	https://leetcode.com/problems/find-missing-and-repeated-values/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-03-06 09:39:16 +01:00
parent e147651e12
commit 0897005fdd
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,21 @@
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)
}
}