Intern
Given a string of characters. Find the number of pairs of indices i and j (i <= j) between which, inclusively, there are no repeating characters. For the string "aba" the answer is 5: [0, 0] ("a") [0, 1] ("ab") [1, 1] ("b") [1, 2] ("ba") [2, 2] ("a") For the string "abcb" the answer is ?: aba 3 + 2 = 5 abcb 4 (a, b, c, d) + 1 (ab) + 1 (bc) + 1 (cb) + 1 (abc) = 8
sobes.tech AI
Answer from AI
You need to find the number of index pairs (i, j), where i ≤ j, such that the substring s[i..j] contains no repeating characters.
For the string "abcb", consider all substrings:
- [0,0] = "a" — unique
- [0,1] = "ab" — unique
- [0,2] = "abc" — unique
- [0,3] = "abcb" — 'b' repeats, not suitable
- [1,1] = "b" — unique
- [1,2] = "bc" — unique
- [1,3] = "bcb" — 'b' repeats, not suitable
- [2,2] = "c" — unique
- [2,3] = "cb" — unique
- [3,3] = "b" — unique
Total number of unique substrings without repeats: 8
Example solution in Go using two pointers (sliding window):
func countUniqueSubstrings(s string) int {
seen := make(map[byte]int)
left := 0
count := 0
for right := 0; right < len(s); right++ {
if pos, ok := seen[s[right]]; ok && pos >= left {
left = pos + 1
}
seen[s[right]] = right
count += right - left + 1
}
return count
}
// Usage example:
// fmt.Println(countUniqueSubstrings("abcb")) // Outputs 8
Idea: expand the right pointer, and if a repeat is encountered, move the left pointer to exclude the repeat, counting the number of unique substrings ending at the current right index.