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 and , ‘b’ has occurred at positions and and so on.
Now if for some query and then the first occurrence of ‘a’, ‘c’ and ‘d’ are at position , and respectively. So for ‘a’ will be , ‘c’ will be and ‘d’ will be . 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 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 .