Skip to content

1358. Number of Substrings Containing All Three Characters #1418

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We need to count the number of substrings in a given string that contain all three characters 'a', 'b', and 'c'. The solution should efficiently handle strings up to a length of 50,000 characters.

Approach

The approach involves using a sliding window technique combined with tracking the last occurrence of each character ('a', 'b', and 'c'). The key insight is that for each position in the string, we can determine the earliest position where all three characters have appeared. This allows us to count all valid substrings ending at the current position efficiently.

  1. Track Last Occurrences: Maintain variables to track the last occurrence indices of 'a', 'b', and 'c'.
  2. Check Validity: For each…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Mar 11, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Mar 11, 2025
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants