The Indian Engineer

Problem 846 Hand of Straights

Posted on Last edited 3 mins

Greedy Hash-Map Sorting

Problem Statement

Link - Problem 846

Question

Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.

Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.

Note :

Example 1

Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3
Output: true
Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]

Example 2

Input: hand = [1,2,3,4,5], groupSize = 4
Output: false
Explanation: Alice's hand can not be rearranged into groups of 4.

Constraints

Solution

class Solution {
public:
    bool isNStraightHand(vector<int>& hand, int groupSize) {

    std::ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    if (hand.size() % groupSize != 0)
        return false;

    map<int, int> freqCount;

    for (const int& card : hand)
        freqCount[card]++;

    for (auto it = freqCount.begin(); it != freqCount.end(); ++it)
    {
        if (it->second > 0)
        {
            int count = it->second;
            for (int i = 0; i < groupSize; ++i)
            {
                if (freqCount[it->first + i] < count)
                    return false;

                freqCount[it->first + i] -= count;
            }
        }
    }
    return true;
    }
};

Complexity Analysis

Explanation

1. Intuition

2. Implementation

This problem is also same as Problem 1296 . We need to dovode the array into groups of size k such that each group is consecutive.