-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0846-hand-of-straights.js
50 lines (37 loc) · 1.49 KB
/
0846-hand-of-straights.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* https://leetcode.com/problems/hand-of-straights/
* Time O(N * K) | Space O(N)
* @param {number[]} hand
* @param {number} groupSize
* @return {boolean}
*/
var isNStraightHand = function (hand, groupSize, count = new Map()) {
const map = getFrequencyMap(hand);/* Time O(N) | Space O(N) */
const sortUniqHand = getUniqueHand(hand);/* Time O(N * Log(N)) | Space O(N) */
return search(groupSize, map, sortUniqHand);/* Time O(N * K) */
};
const getFrequencyMap = (hand, map = new Map()) => {
for (const _hand of hand) {/* Time O(N) */
const val = (map.get(_hand) || 0) + 1;
map.set(_hand, val);/* Space O(N) */
}
return map;
}
const getUniqueHand = (hand) => [ ...new Set(hand) ]/* Time O(N) | Space O(N) */
.sort((a, b) => b - a);/* Time O(N * Log(N)) | Space HeapSort O(1) | Space QuickSort O(log(N)) */
const search = (groupSize, map, sortUniqHand) => {
while (sortUniqHand.length) {/* Time O(N) */
const smallest = sortUniqHand[sortUniqHand.length - 1];
for (let i = smallest; i < smallest + groupSize; i++) {/* Time O(K) */
if (!map.has(i)) return false;
const val = map.get(i) - 1;
map.set(i, val);
let isEqual = map.get(i) === 0;
if (!isEqual) continue;
isEqual = i === sortUniqHand[sortUniqHand.length - 1];
if (!isEqual) return false;
sortUniqHand.pop();
}
}
return true;
}