Skip to content

Commit

Permalink
add Kotlin solution for 846. Hand of Straights
Browse files Browse the repository at this point in the history
  • Loading branch information
technophilist committed Apr 21, 2023
1 parent 1d8e1bf commit 5e14e12
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions kotlin/0846-hand-of-straights.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
fun isNStraightHand(hand: IntArray, groupSize: Int): Boolean {
if (hand.size % groupSize != 0) return false
val countMap = mutableMapOf<Int, Int>()
hand.forEach { countMap[it] = countMap.getOrDefault(it, 0) + 1 }
val minHeap = PriorityQueue(countMap.keys)

while (minHeap.isNotEmpty()) {
val minValue = minHeap.peek()
if (countMap.getValue(minValue) == 0) {
minHeap.remove()
continue
}
// loop through consecutive numbers starting from the "minValue" number
for (consecutiveNumber in minValue until (minValue + groupSize)) {
if (
consecutiveNumber !in countMap.keys ||
countMap.getValue(consecutiveNumber) == 0
) return false
countMap[consecutiveNumber] = countMap.getValue(consecutiveNumber) - 1
}
// if the loop successfully executes without returning, it indicates that
// it was possible to create a group of size [groupSize] with minValue
// as the first element in the group.
}
return true
}
}

0 comments on commit 5e14e12

Please sign in to comment.