Ctrl K

Balanced Stretches of a String

Hard
You are given a string text of lowercase English letters and an integer divisor. The letters a, e, i, o, u are vowels; every other letter is a consonant. Call a non-empty stretch of the string (a run of consecutive characters) **balanced** if: - it has as many vowels as consonants; - the number of vowels times the number of consonants is divisible by divisor. Count the balanced stretches of text. Stretches at different positions count separately even if they spell the same string. Checking every stretch takes O(n²), and the string can be up to 5·10⁴ characters long, so aim for something faster.
Example 1
text="tobeor", divisor=4 → 2

"tobe" (2 vowels, 2 consonants, 2·2 = 4 is divisible by 4) and "beor" (also 2 and 2) qualify. The whole string has 3 and 3, and 9 is not divisible by 4. Two-letter stretches like "to" or "be" give 1·1 = 1, which 4 does not divide.

Example 2
text="kayak", divisor=1 → 6

With divisor = 1 any stretch with as many vowels as consonants counts: "ka", "ay", "ya", "ak", "kaya", "ayak", six in total.

Example 3
text="rhythm", divisor=3 → 0

There are no vowels at all, so no stretch qualifies.

Constraints
  • 1 ≤ len(text) ≤ 5·10⁴
  • 1 ≤ divisor ≤ 1000
  • text consists of lowercase English letters only
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEven Vowel and Consonant Pieces MediumPair GCDs by Sorted Position HardPieces With Matching Ends MediumPieces With a Fixed Zero-to-One Ratio MediumSimplify a Letter Polynomial Hard
loading Python…
Input
text="tobeor", divisor=4
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 92 tests on the server, hidden ones included.