-
Notifications
You must be signed in to change notification settings - Fork 0
/
hand_of_straights.php
75 lines (60 loc) · 2.06 KB
/
hand_of_straights.php
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/**
* Hand Of Straights
* @link https://leetcode.com/problems/hand-of-straights
*
* Approach:
* Iterate through each unique card and put it into current group, if current group size is equals to groupSize argument,
* then just start taking element to the next group.
* But input may contain duplicates, so when you go to next group start at smallest element that has more than 0 zero duplicates.
* In each iteration in context of current group check is this number consecutive.
*
* Time Complexity - O(n logn)
* Space Complexity - O(n)
*/
class Solution {
function isNStraightHand($hand, $groupSize) {
if (count($hand) % $groupSize) {
return false;
}
sort($hand);
$uniqueHand = [];
$counter = [];
for ($i = 0; $i < count($hand); $i++) {
if (isset($counter[$hand[$i]])) {
$counter[$hand[$i]]++;
} else {
$counter[$hand[$i]] = 1;
$uniqueHand[] = $hand[$i];
}
}
$currentGroupSize = 0;
$idx = 0;
$restartIdx = 0;
while ($idx < count($uniqueHand)) {
if ($counter[$uniqueHand[$idx]] === 0) {
$idx++;
continue;
}
$counter[$uniqueHand[$idx]]--;
if ($counter[$uniqueHand[$idx]] === 0 && $restartIdx === $idx) {
$restartIdx = $idx + 1;
while ($counter[$uniqueHand[$restartIdx]] === 0 && $restartIdx < count($uniqueHand)) {
$restartIdx++;
}
}
// last element of current group, no need to check consecutive
if ($currentGroupSize + 1 === $groupSize) {
$idx = $restartIdx;
$currentGroupSize = 0;
continue;
}
if ($uniqueHand[$idx] + 1 !== ($uniqueHand[$idx + 1] ?? -1) || $counter[$uniqueHand[$idx + 1]] === 0) {
return false;
}
$currentGroupSize++;
$idx++;
}
return true;
}
}