Let’s say we have a string s = “abbacdc” and we have stored all the positions(1-based indexing) where each of the characters has occurred, for example ‘a’ has occurred at positions 11 and 44, ‘b’ has occurred at positions 22 and 33 and so on.

Now if for some query l=4l = 4 and r=7r = 7 then the first occurrence of ‘a’, ‘c’ and ‘d’ are at position 44, 55 and 66 respectively. So kk for ‘a’ will be 11, ‘c’ will be 22 and ‘d’ will be 33. For each character from ‘a’ to ‘z’, it can be easily found these positions by doing Binary Search on the stored positions of the characters. As we have got kk for the characters of the substring, now we can easily calculate the length of the substring using the count of the characters in the substring. Final complexity will be O(n26logn)O(n*26*logn).

Statistics

82% Solution Ratio
adnan_tokyEarliest, Jul '21
Nafis2003174.132453Fastest, 0.0s
Nafis2003174.132453Lightest, 5.5 kB
D3structorShortest, 514B
Toph uses cookies. By continuing you agree to our Cookie Policy.