![]() |
VOOZH | about |
Given a string s consisting of lowercase English letters, find the maximum number of characters between any two identical characters. If no character repeats, return -1.
Examples:
Input: s = "socks"
Output: 3
Explanation: There are 3 characters between the two occurrences of 's'.
Input: s = "for"
Output: -1
Explanation: No repeating character present.
Table of Content
The idea is to check every pair of indices
(i, j)wherei < j. Ifs[i] == s[j], then the number of characters between them isj - i - 1. Keep updating the maximum gap found.
3
Time Complexity: O(n^2)
Auxiliary Space: O(1)
The idea is to store the first occurrence of each character. While traversing the string, whenever the same character appears again, calculate the gap between the current index and its first occurrence. For any character, the maximum number of characters between two occurrences is obtained using its first occurrence and a later occurrence. Therefore, storing only the first occurrence of each character is sufficient.
Let us understand with example:
Input: s = "socks"
3
Time Complexity: O(n)
Auxiliary Space: O(1)