Count Sorted Vowel Strings - Problem

Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.

A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet.

Input & Output

Example 1 — Basic Case
$ Input: n = 1
Output: 5
💡 Note: All single vowel strings are valid: 'a', 'e', 'i', 'o', 'u' are all lexicographically sorted by themselves
Example 2 — Small Length
$ Input: n = 2
Output: 15
💡 Note: Valid strings include 'aa', 'ae', 'ai', 'ao', 'au', 'ee', 'ei', 'eo', 'eu', 'ii', 'io', 'iu', 'oo', 'ou', 'uu'. Invalid would be 'ea', 'ia', etc.
Example 3 — Larger Case
$ Input: n = 33
Output: 66045
💡 Note: For n=33, using the mathematical formula C(33+4, 4) = C(37, 4) = 66045 valid sorted vowel strings

Constraints

  • 1 ≤ n ≤ 50

Visualization

Tap to expand
Count Sorted Vowel Strings INPUT n = 1 String length Available Vowels: a e i o u Constraint: Strings must be lexicographically sorted For n=1, valid strings: "a", "e", "i", "o", "u" (5 single-char strings) ALGORITHM STEPS 1 Initialize DP array dp[i] = count ending with vowel i 2 Base case (n=1) Each vowel = 1 string 3 Apply recurrence dp[i] = sum(dp[0..i]) 4 Sum all dp values Result = sum(dp[0..4]) DP Table for n=1: a e i o u 1 1 1 1 1 1 + 1 + 1 + 1 + 1 = 5 FINAL RESULT Output: 5 All Valid Strings: "a" "e" "i" "o" "u" Status: OK 5 sorted vowel strings Time: O(n) | Space: O(1) Key Insight: This is a combinatorics problem solvable with Dynamic Programming. For lexicographically sorted strings, each position can only use vowels that come at or after the previous character. The count equals choosing n items from 5 with repetition: C(n+4, 4) = (n+4)! / (n! * 4!) -- a "stars and bars" formula. TutorialsPoint - Count Sorted Vowel Strings | Optimal Solution (Dynamic Programming)
Asked in
Google 15 Amazon 12
125.0K Views
Medium Frequency
~15 min Avg. Time
3.4K 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