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.
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:
1 <= hand.length <= 1040 <= hand[i] <= 1091 <= groupSize <= hand.length
Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
Why this is a Greedy problem
A greedy algorithm makes the best-looking choice at each step without reconsidering past decisions. It works when the "greedy choice property" holds: local optima lead to global optimum. The hard part isn't the code β it's proving (or recognizing) when greedy is valid.
Sort by the right criterion, then make the greedy choice. Prove correctness by exchange argument: "swapping the greedy choice for any other choice can only make things worse or equal."
For "Jump Game": at each position, greedily track the farthest index you can reach. You don't need to try all paths β if the max reachable index ever covers position i, you can be there. Greedy works because reaching farther is always at least as good as reaching less far.
From brute force to optimal β understand every step of the journey
Greedy algorithms are "obviously correct" once you see the right exchange argument. For interval scheduling: if you pick the interval that ends latest first, you can always swap it for the one ending soonest β and the count can only stay the same or improve. That's the exchange argument. If you can't construct this argument, greedy probably doesn't work and you need DP.