Intern
Given a string of characters, find the number of index pairs i and j (i <= j) between which there are no repeating characters, inclusive. 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 "acbb", what is the answer?
sobes.tech AI
Answer from AI
For the string "acbb", you need to find the number of index pairs [i, j] (i ≤ j) such that the substring s[i..j] contains only unique characters.
Let's analyze the string "acbb":
- [0,0] = "a" — unique
- [0,1] = "ac" — unique
- [0,2] = "acb" — unique
- [0,3] = "acbb" — repeated "b", not suitable
- [1,1] = "c" — unique
- [1,2] = "cb" — unique
- [1,3] = "cbb" — repeated "b", not suitable
- [2,2] = "b" — unique
- [2,3] = "bb" — repeated "b", not suitable
- [3,3] = "b" — unique
Total of 7 such pairs.
This problem can be solved using two pointers and a set to track unique characters:
func countUniqueSubstrings(s string) int {
seen := make(map[rune]bool)
count := 0
left := 0
for right, ch := range s {
for seen[ch] {
delete(seen, rune(s[left]))
left++
}
seen[ch] = true
count += right - left + 1
}
return count
}
// Example usage:
// fmt.Println(countUniqueSubstrings("acbb")) // Outputs 7
This algorithm runs in O(n), where n is the length of the string.