Substrings of Size Three with Distinct Characters - Problem

A string is good if there are no repeated characters.

Given a string s, return the number of good substrings of length three in s.

Note that if there are multiple occurrences of the same substring, every occurrence should be counted.

A substring is a contiguous sequence of characters in a string.

Input & Output

Example 1 — Basic Case
$ Input: s = "xyzzaz"
Output: 1
💡 Note: Only "xyz" at the beginning has all distinct characters. "yzz", "zza", and "zaz" all have repeated characters.
Example 2 — Multiple Good Substrings
$ Input: s = "aababcabc"
Output: 4
💡 Note: The good substrings are: "bab" (index 2), "abc" (index 3), "bca" (index 4), "cab" (index 5), "abc" (index 6). Total = 4 distinct character substrings.
Example 3 — No Good Substrings
$ Input: s = "aaa"
Output: 0
💡 Note: Only one substring "aaa" exists, but it has repeated characters, so no good substrings.

Constraints

  • 1 ≤ s.length ≤ 100
  • s consists of lowercase English letters.

Visualization

Tap to expand
Substrings of Size Three with Distinct Characters INPUT String s = "xyzzaz" x 0 y 1 z 2 z 3 a 4 z 5 All Substrings of Length 3: "xyz" "yzz" "zza" "zaz" Length: 6 Possible substrings: 4 ALGORITHM STEPS 1 Sliding Window Use window of size 3 2 Check Each Substring Compare all 3 chars 3 Distinct Check a!=b AND b!=c AND a!=c 4 Count Good Ones Increment counter Analysis: "xyz" x!=y!=z [OK] "yzz" z==z [FAIL] "zza" z==z [FAIL] "zaz" z==z [FAIL] FINAL RESULT Good Substrings Found: "xyz" x y z All characters distinct! Output: 1 Only 1 good substring out of 4 total Key Insight: For a fixed window size of 3, we only need O(1) comparisons per window position. Check if s[i] != s[i+1] AND s[i+1] != s[i+2] AND s[i] != s[i+2]. Time: O(n), Space: O(1). TutorialsPoint - Substrings of Size Three with Distinct Characters | Optimal Solution
Asked in
Amazon 25 Facebook 18 Google 15 Microsoft 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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