Skip to content

Commit ba77e85

Browse files
committed
2981. Find Longest Special Substring That Occurs Thrice I
1 parent 7e3e5b9 commit ba77e85

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Solution by Sergey Leschev
2+
// 2981. Find Longest Special Substring That Occurs Thrice I
3+
// Binary search
4+
5+
function maximumLength(s: string): number {
6+
const n = s.length
7+
8+
// Helper function to check if a special substring of length `x` exists at least thrice
9+
const helper = (x: number): boolean => {
10+
const count = new Array(26).fill(0)
11+
let start = 0
12+
13+
for (let end = 0; end < n; end++) {
14+
// Move start pointer until we match the current character
15+
while (s[start] !== s[end]) start++
16+
// Check if the substring length is at least `x`
17+
if (end - start + 1 >= x) count[s.charCodeAt(end) - 'a'.charCodeAt(0)]++
18+
// If any character count exceeds 2, return true
19+
if (count[s.charCodeAt(end) - 'a'.charCodeAt(0)] > 2) return true
20+
}
21+
22+
return false
23+
}
24+
25+
let left = 1
26+
let right = n
27+
28+
if (!helper(left)) return -1
29+
30+
while (left + 1 < right) {
31+
const mid = Math.floor((left + right) / 2)
32+
if (helper(mid)) {
33+
left = mid
34+
} else {
35+
right = mid
36+
}
37+
}
38+
39+
return left
40+
}

0 commit comments

Comments
 (0)