DEV Community

Karleb
Karleb

Posted on

#846. Hand of Straights

https://leetcode.com/problems/hand-of-straights/?envType=daily-question&envId=2024-06-06

/**
 * @param {number[]} hand
 * @param {number} groupSize
 * @return {boolean}
 */

 function findSuccessors(hand, groupSize, i, n) {
    let next =  hand[i] + 1
    hand[i] = -1
    let count = 1
    i++

    while(i < n && count < groupSize) {
        if (hand[i] === next) {
            next = hand[i] + 1
            hand[i] = -1
            count++
        }
        i++
    }

    return count === groupSize
}

var isNStraightHand = function (hand, groupSize) {
    let n = hand.length

    if (n % groupSize !== 0) return false

    hand.sort((a, b) => a - b)

    for (let i = 0; i < hand.length; i++) {
        if (hand[i] !== -1) {
            if (! findSuccessors(hand, groupSize, i, n)) return false
        }
    }

    return true
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)