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: [0, 0] ("a") [0, 1] ("ab") [1, 1] ("b") [1, 2] ("ba") [2, 2] ("a") */
sobes.tech AI
Answer from AI
To find the number of index pairs (i, j) for which the substring s[i:j+1] contains no repeating characters, you can use the "sliding window" method (two pointers).
Idea:
- Use two pointers: start and end, which will denote the current considered interval.
- Expand end while the characters are unique.
- When a repeat is encountered, move start, removing characters from the set.
- For each position of end, count the number of substrings without repeats that end at end.
Example in Go:
func countUniqueSubstrings(s string) int {
seen := make(map[rune]int)
start := 0
count := 0
for end, ch := range s {
if pos, ok := seen[ch]; ok && pos >= start {
start = pos + 1
}
seen[ch] = end
count += end - start + 1
}
return count
}
Here, count accumulates the number of unique substrings without repeating characters.