Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Sliding window

Count substrings holding a, b and c

Medium · Target 20 minutes · Sliding window· Type asked at

Given a string s made only of the letters a, b and c, return the number of substrings that contain at least one of each.

Examples

InputOutputWhy
s = "abcabc"10Ending at index 2: 1 substring; at 3: 2; at 4: 3; at 5: 4.
s = "aaacb"3"aaacb", "aacb", "acb".
s = "abab"0No c anywhere.

Constraints

  • 1 ≤ |s| ≤ 5 × 10⁴
  • s consists of a, b and c only

Hints

Hint 1

If a substring contains all three letters, so does every substring that contains it.

Hint 2

For a right end hi, the valid starts are 0, 1, …, up to some last start. Find that last start.

Hint 3

Shrink while the window still holds all three. When it stops, lo is the number of valid starts for this hi.

Where people lose marks

  • Adding hi − lo + 1 out of habit: that counts the invalid starts here.
  • Adding inside the shrink loop instead of once per right end, which counts the same substrings several times.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.