diff --git a/kt/minimum-array-end.kt b/kt/minimum-array-end.kt new file mode 100644 index 0000000..bcad6a8 --- /dev/null +++ b/kt/minimum-array-end.kt @@ -0,0 +1,22 @@ +class Solution { + private data class State(val result: Long, val n: Long) { + fun update( + target: Long, + mask: Long, + ): State = + when { + n > 0 && mask.and(target) == 0L -> State(result.or((n.and(1L)) * mask), n.shr(1)) + else -> this + } + } + + fun minEnd( + n: Int, + x: Int, + ): Long = + (0..Long.SIZE_BITS) + .map { 1L.shl(it) } + .fold(State(x.toLong(), n - 1L)) { s, mask -> + s.update(x.toLong(), mask) + }.result +}