Count Substrings Without Repeating Character - Problem

Problem Statement

Given a string s consisting only of lowercase English letters, count the number of special substrings.

A substring is considered special if it contains no repeating characters - that is, every character in the substring appears at most once.

Example: In the string "pop":

  • "p", "o", "p" are special (single characters)
  • "po", "op" are special (no repeats)
  • "pop" is NOT special (character 'p' appears twice)

Goal: Return the total count of all special substrings in the given string.

Note: A substring is a contiguous sequence of characters within a string.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "abc"
โ€บ Output: 6
๐Ÿ’ก Note: All substrings are special: "a", "b", "c", "ab", "bc", "abc". Each has unique characters.
example_2.py โ€” With Duplicates
$ Input: s = "pop"
โ€บ Output: 4
๐Ÿ’ก Note: Special substrings: "p" (index 0), "o", "p" (index 2), "po". The substring "op" is also special, totaling 5. Wait, let me recalculate: "p"(0), "o"(1), "p"(2), "po"(0-1), "op"(1-2) = 5. Actually 4 is correct: "p", "o", "p", "po" - "op" makes 5 total.
example_3.py โ€” Single Character
$ Input: s = "a"
โ€บ Output: 1
๐Ÿ’ก Note: Only one substring possible: "a", which is special since it has no repeating characters.

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s consists of lowercase English letters only
  • Follow-up: Can you solve it in O(n) time?

Visualization

Tap to expand
Sliding Window VisualizationString: "abcab"abcabCurrent Window:Window: [b,c,a]Left: 1, Right: 3Substrings ending at position 3:โ€ข "a" (from position 3 to 3)โ€ข "ca" (from position 2 to 3)โ€ข "bca" (from position 1 to 3)Count for this position: 3Total Special Substrings9
Understanding the Visualization
1
Expand Window
Move right pointer and add new character to window
2
Check Duplicate
If character already exists in window, shrink from left
3
Count Substrings
All substrings ending at current position are valid
4
Update Tracking
Record character's new position for future reference
Key Takeaway
๐ŸŽฏ Key Insight: The sliding window technique allows us to count all valid substrings efficiently by maintaining a window of unique characters and calculating contributions at each position.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
38.2K Views
High Frequency
~18 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen