Skip to content

Commit 4b11537

Browse files
committed
2963. Count the Number of Good Partitions
1 parent e862f25 commit 4b11537

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
3+
// Solution by Sergey Leschev
4+
// 2963. Count the Number of Good Partitions
5+
6+
// Time complexity - O(N)
7+
// Space complexity - O(N)
8+
9+
func numberOfGoodPartitions(_ nums: [Int]) -> Int {
10+
let m = 1_000_000_007
11+
var count = 0
12+
var last: [Int: Int] = [:]
13+
14+
for i in 0..<nums.count {
15+
last[nums[i]] = i
16+
}
17+
18+
var next = -1
19+
20+
for i in 0..<nums.count {
21+
if i > next {
22+
count += 1
23+
}
24+
next = max(next, last[nums[i]]!)
25+
}
26+
27+
return power(2, count - 1, m)
28+
}
29+
30+
func power(_ b: Int, _ p: Int, _ m: Int) -> Int {
31+
if p <= 0 {
32+
return 1
33+
}
34+
let t = power(b, p / 2, m)
35+
return (p % 2 == 1) ? (((t * t) % m) * b) % m : (t * t) % m
36+
}
37+
}

0 commit comments

Comments
 (0)