Intern
""" Given a string of characters. Find the number of pairs of indices i and j (i <= j), where, inclusive, 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 a ab b abc bc c cb b 4(a, b, c, d) + 1(ab) + 1(bc) + 1(cb) + 1(abc) = 8 """
sobes.tech AI
Answer from AI
The task is to find the number of index pairs [i, j] (i ≤ j) such that the substring s[i..j] contains only unique characters.
For the string "abcb", consider all substrings without repeating characters:
- [0,0] "a"
- [0,1] "ab"
- [1,1] "b"
- [1,2] "bc"
- [2,2] "c"
- [2,3] "cb"
- [3,3] "b"
Total of 7 substrings.
Here's an example solution in Go using two pointers and a set to track characters:
def countUniqueSubstrings(s string) int {
count := 0
n := len(s)
chars := make(map[byte]bool)
j := 0
for i := 0; i < n; i++ {
for j < n && !chars[s[j]] {
chars[s[j]] = true
j++
}
count += j - i
delete(chars, s[i])
}
return count
}
// Example call
// fmt.Println(countUniqueSubstrings("abcb")) // Will output 7
The algorithm runs in O(n), expanding and shrinking the sliding window to count all substrings with unique characters.