Problem statement

https://leetcode.com/problems/hand-of-straights/

Solution

Let us count our numbers and start from the biggest one. Imagine it has frequency freq, this means, than there must be numbers num - 1, ..., num - W + 1 with at least this frequencies. So, we check our stack and update frequencies.

Complexity

Complexity of sorting part is O(m log m), where n is the number of different cards and complexity of working with stack is O(n): on each step we reduce frequency of one of the elements by 1: final time complexity is O(m log m + n). Space complexity is O(n).

Code

class Solution:
    def isNStraightHand(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

Remark

There is also O(n) solution.

This problem is the same as 1296 Divide Array in Sets of K Consecutive Numbers. See also similar problem 0659 Split Array into Consecutive Subsequences, where we need to divide in groups of any size
>= 3.