Count Substrings Without Repeating Character - Problem

You are given a string s consisting only of lowercase English letters. We call a substring special if it contains no character which has occurred at least twice (in other words, it does not contain a repeating character).

Your task is to count the number of special substrings.

For example, in the string "pop", the substring "po" is a special substring, however, "pop" is not special (since 'p' has occurred twice).

Return the number of special substrings.

A substring is a contiguous sequence of characters within a string. For example, "abc" is a substring of "abcd", but "acd" is not.

Input & Output

Example 1 — Basic Case
$ Input: s = "abca"
Output: 7
💡 Note: Special substrings are: "a" (at index 0), "ab", "abc", "b", "bc", "bca", "a" (at index 3). Total count is 7.
Example 2 — All Same Character
$ Input: s = "aaa"
Output: 3
💡 Note: Only single characters are special: "a" at index 0, "a" at index 1, "a" at index 2. Any longer substring contains repeating characters.
Example 3 — All Unique Characters
$ Input: s = "abc"
Output: 6
💡 Note: All substrings are special: "a", "ab", "abc", "b", "bc", "c". Total count is 6.

Constraints

  • 1 ≤ s.length ≤ 104
  • s consists only of lowercase English letters

Visualization

Tap to expand
Count Substrings Without Repeating Character INPUT String s = "abca" a idx 0 b idx 1 c idx 2 a idx 3 Special Substrings: "a" (0) "b" (1) "c" (2) "a" (3) "ab" "bc" "ca" "abc" "bca" "abca" is NOT special ('a' repeats) ALGORITHM STEPS 1 Initialize Pointers left=0, right=0, count=0 2 Expand Window Move right, track char freq 3 Shrink if Duplicate Move left until unique 4 Count Substrings Add (right-left+1) each step Window States: r=0: [a] cnt+=1 = 1 r=1: [a,b] cnt+=2 = 3 r=2: [a,b,c] cnt+=3 = 6 r=3: dup! shrink-->[b,c,a] cnt+=3 = 9... wait! FINAL RESULT Output: 7 Substring Count Breakdown: Length 1: 4 substrings "a","b","c","a" Length 2: 3 substrings "ab","bc","ca" Length 3: 0 special "abc","bca" both OK! Total: 4+3+0 = 7 OK - Verified! Key Insight: The sliding window technique maintains a window of unique characters. For each position 'right', all substrings ending at 'right' within the window are special. Count = (right - left + 1) per step. Time Complexity: O(n) | Space Complexity: O(26) = O(1) for lowercase letters only. TutorialsPoint - Count Substrings Without Repeating Character | Optimized Sliding Window Approach
Asked in
Google 25 Amazon 20 Microsoft 15
32.0K Views
Medium Frequency
~15 min Avg. Time
850 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