Number of Strings Which Can Be Rearranged to Contain Substring - Problem

You are given an integer n. A string s is called good if it contains only lowercase English characters and it is possible to rearrange the characters of s such that the new string contains "leet" as a substring.

For example:

  • The string "lteer" is good because we can rearrange it to form "leetr".
  • "letl" is not good because we cannot rearrange it to contain "leet" as a substring.

Return the total number of good strings of length n. Since the answer may be large, return it modulo 10^9 + 7.

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

Input & Output

Example 1 — Minimum Valid Length
$ Input: n = 4
Output: 12
💡 Note: With n=4, we need exactly "leet" or rearrangements that contain these 4 letters. There are 4! = 24 arrangements of "leet", but since we have repeated 'e', we get 4!/2! = 12 unique arrangements.
Example 2 — Length 5
$ Input: n = 5
Output: 960
💡 Note: With n=5, we can have "leet" plus one additional letter (any of 26 choices). The additional letter can be placed in any of 5 positions, giving us more arrangements.
Example 3 — Too Short
$ Input: n = 3
Output: 0
💡 Note: With only 3 characters, it's impossible to form "leet" which requires at least 4 characters (l, e, e, t).

Constraints

  • 1 ≤ n ≤ 105

Visualization

Tap to expand
Strings Rearrangeable to Contain "leet" INPUT n = 4 Target Substring: l e e t Requirements: - At least 1 'l' - At least 2 'e's - At least 1 't' Total possible strings: 26^n = 26^4 = 456976 ALGORITHM STEPS 1 Inclusion-Exclusion Count complementary sets 2 Define Bad Sets A:no l, B:<2 e, C:no t 3 Count Each Set Use combinatorics 4 Apply Formula Total - |A∪B∪C| Inclusion-Exclusion: |A∪B∪C| = |A|+|B|+|C| -|A∩B|-|A∩C|-|B∩C| +|A∩B∩C| For n=4: |A|=25^4, |B|=26^4+4*25^3 |C|=25^4, intersections... Bad = 456964 FINAL RESULT Good Strings = Total - Bad 456976 - 456964 = 12 Output: 12 Valid 4-char strings: leet eelt eetl elte ... and 8 more permutations OK - 12 good strings! Key Insight: Use Inclusion-Exclusion principle: Instead of counting good strings directly, count "bad" strings (missing l, having <2 e's, or missing t) and subtract from total. For n=4, exactly 12 permutations of {l,e,e,t} can be rearranged to form "leet". Time: O(n), Space: O(1). TutorialsPoint - Number of Strings Which Can Be Rearranged to Contain Substring | Optimal Solution
Asked in
Meta 15 Google 12 Amazon 8
23.5K Views
Medium Frequency
~25 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