Substrings of Size Three with Distinct Characters - Problem
Find All Good Substrings

Imagine you're analyzing text patterns to find "good" character sequences. A string is considered good when all its characters are unique - no repeating letters allowed!

Your mission: Given a string s, count how many good substrings of exactly length 3 exist within it.

Key Points:
  • ๐ŸŽฏ We only care about substrings with exactly 3 characters
  • โœจ All 3 characters must be different (like "abc", "xyz", "cat")
  • ๐Ÿ”„ Count every occurrence, even if the same substring appears multiple times
  • ๐Ÿ“ A substring is a contiguous sequence of characters

Example: In "xyzzaz", we have substrings "xyz" (good โœ“), "yzz" (bad โœ—), "zza" (bad โœ—), "zaz" (good โœ“). Answer: 2

Input & Output

example_1.py โ€” Simple case
$ Input: s = "xyzzaz"
โ€บ Output: 2
๐Ÿ’ก Note: The good substrings are "xyz" (positions 0-2) and "zaz" (positions 3-5). "yzz" and "zza" contain repeated characters so they don't count.
example_2.py โ€” All good substrings
$ Input: s = "abcd"
โ€บ Output: 2
๐Ÿ’ก Note: We have two possible 3-character substrings: "abc" (all different) and "bcd" (all different). Both are good, so the answer is 2.
example_3.py โ€” Edge case
$ Input: s = "aab"
โ€บ Output: 0
๐Ÿ’ก Note: The only 3-character substring is "aab" which has repeated 'a' characters, so it's not good. The answer is 0.

Constraints

  • 1 โ‰ค s.length โ‰ค 100
  • s consists of lowercase English letters only
  • Note: We only count substrings of exactly length 3

Visualization

Tap to expand
๐Ÿช Shop Street: Each position shows different items๐Ÿ“ฑ๐Ÿ‘Ÿ๐ŸŽง๐ŸŽงโŒš๐ŸŽง๐Ÿ•ต๏ธ Detective Window 1๐Ÿ“ฑ ๐Ÿ‘Ÿ ๐ŸŽง โ†’ All different! โœ“ Count: 1Window 2: ๐Ÿ‘Ÿ ๐ŸŽง ๐ŸŽง โ†’ Duplicate! โœ—Window 4: โŒš ๐ŸŽง โ†’ All different! โœ“ Count: 2๐ŸŽฏ Final Count: 2 good windows found!
Understanding the Visualization
1
Position the Frame
Place your 3-item window frame at the start of the street
2
Inspect Items
Check if all 3 visible items are different - if yes, count it!
3
Slide Forward
Move the frame one position right and repeat the inspection
Key Takeaway
๐ŸŽฏ Key Insight: Instead of examining every item in each window from scratch, we only need to check if the 3 current items are all different - a simple constant-time comparison!
Asked in
Amazon 35 Google 28 Microsoft 22 Meta 18
23.5K Views
Medium Frequency
~12 min Avg. Time
847 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