Intern
/* Given a string of characters. Find the number of pairs of indices i and j (i <= j) between which there are no repeating characters. For the string "aba" the answer is 5: can be ASCII [0, 0] ("a") [0, 1] ("ab") [1, 1] ("b") [1, 2] ("ba") [2, 2] ("a") */
sobes.tech AI
Answer from AI
To solve the problem, you need to iterate over all substrings of the string and check that each substring contains no repeating characters. To do this efficiently, you can use a sliding window with two pointers and a set to track unique characters.
Example in Go:
func countUniqueSubstrings(s string) int {
n := len(s)
count := 0
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
}
// Usage example:
// s := "aba"
// fmt.Println(countUniqueSubstrings(s)) // Outputs 5
Idea: expand the right pointer j while characters are unique, then move the left pointer i, removing characters from the set. The number of unique substrings starting at i is j - i.