File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments