1. Brute Force — Quadratic Search with Used Array
Intuition
Sort hand. For each card i from 0 to N - 1: if used[i], continue. We need cards hand[i] + 1, hand[i] + 2, ..., hand[i] + groupSize - 1. Scan forward to find each consecutive card, marking them used. If any is missing, return false.
When to apply: When N <= 200.
Algorithm
- Step 1: If hand.length % groupSize != 0 return false.
- Step 2: Sort hand ascending.
- Step 3: Create boolean used array of size N.
- Step 4: For each i: if !used[i], mark used[i] = true and find next groupSize - 1 consecutive cards.
- Step 5: If all found, return true; else false.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution {public: bool isNStraightHand(vector<int>& hand, int groupSize) { int n = hand.size(); if (n % groupSize != 0) return false; sort(hand.begin(), hand.end()); vector<bool> used(n, false); for (int i = 0; i < n; ++i) { if (used[i]) continue; used[i] = true; int needed = hand[i] + 1; int count = 1; for (int j = i + 1; j < n && count < groupSize; ++j) { if (!used[j] && hand[j] == needed) { used[j] = true; needed++; count++; } } if (count < groupSize) return false; } return true; }}; int main() { Solution sol; vector<int> hand = {1, 2, 3, 6, 2, 3, 4, 7, 8}; cout << (sol.isNStraightHand(hand, 3) ? "true" : "false") << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Nested loops scanning forward for consecutive elements. - Space complexity:
O(N)— Boolean used array of size N.
Why Brute Force Doesn't Scale:
With N = 104, N2 is 108 operations. Hash map + sorted keys batch decrement reduces it to O(N log N) in ~10ms.
For N = 10,000: O(N log N) requires ~1.4 * 105 operations, executing in ~4ms.