[
stack
sort
greedy
]
Leetcode 1296. Divide Array in Sets of K Consecutive Numbers
Problem statement
https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
Solution
Equal to Leetcode 0846 Hand of Straights.
Complexity
Time complexity is O(m log m + n)
. Space complexity is O(n)
.
Code
class Solution:
def isPossibleDivide(self, hand, W):
stack = sorted(Counter(hand).items())
while stack:
num, freq = stack.pop()
addon = []
for i in range(1, W):
if not stack: return False
num_n, freq_n = stack.pop()
if num_n != num - i or freq_n < freq: return False
if freq_n != freq: addon += [(num_n, freq_n - freq)]
stack += addon[::-1]
return True