Problem 1641

Abstract / Summary

Count the number of strings of a given length made from vowels in order without repeating a vowel out of sequence.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1641.py

class Solution:
    def countVowelStrings(self, n: int) -> int:
        # 0 = "a", 1 = "e", 2 = "i", 3 = "o", 4 = "u"
        last = [ 1, 0, 0, 0, 0 ]
        for i in range(n):
            next = [ 0, 0, 0, 0, 0 ]
            for i, l in enumerate(last):
                for j in range(i, 5):
                    next[j] += l
            last = next
        return sum(last)
11 lines | 387 bytes | submitted December 22, 2023 | GitHub   10% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 79% (200k+ submissions).

Typical patterns to solve this problem:
  • Combinatorics
  • Dynamic Programming
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the number of possible strings of length n that can be formed using the five English vowels (a, e, i, o, u) where the vowels must appear in non-decreasing alphabetical order. It employs a compact dynamic programming approach that iteratively builds the count for each vowel position while preserving the ordering constraint.

Core Logic

The algorithm maintains a one-dimensional array, last, where each entry represents the number of valid strings that end with a particular vowel. The index mapping is explicit in the comment:

# 0 = "a", 1 = "e", 2 = "i", 3 = "o", 4 = "u"
last = [1, 0, 0, 0, 0]

The initial state reflects that a string of length 1 consisting solely of 'a' is the only valid string ending with 'a'; all other vowels have zero possibilities at this point.

Iterative Transition

For each position in the target string (executed n times), a new array next is constructed. The nested loops propagate counts from last to next while respecting the non-decreasing order:

for i in range(n):
    next = [0, 0, 0, 0, 0]
    for i, l in enumerate(last):
        for j in range(i, 5):
            next[j] += l
    last = next

The outer loop iterates over the string length. Inside, enumerate(last) yields the current vowel index i and its associated count l. The inner loop runs from the current index i up to the last vowel index 4. By adding l to every next[j] where j >= i, the code accumulates all ways to extend existing strings with any vowel that does not violate the ordering rule. After processing all indices, last is replaced with next, ready for the next iteration.

Final Aggregation

Once all positions have been processed, the total number of valid strings is obtained by summing the entries of last:

return sum(last)

Each entry now holds the count of strings of length n ending with the corresponding vowel, and their sum yields the overall count.

Edge Cases Handled

When n equals zero, the outer loop does not execute, leaving last unchanged as [1, 0, 0, 0, 0]. The final sum(last) returns 1, which correctly represents the empty string as a single valid combination under the problem’s combinatorial interpretation.

The algorithm also gracefully handles very large values of n. Python’s arbitrary-precision integers ensure that intermediate sums do not overflow, and the fixed-size inner loops keep the computation bounded regardless of n.

Performance Optimizations

The implementation leverages several implicit optimizations:

  • The state vector last has a constant length of five, eliminating the need for dynamic data structures that grow with n. This keeps memory usage minimal and predictable.
  • By reusing the next list on each iteration rather than creating new lists for every inner loop, the code reduces allocation overhead.
  • The inner accumulation loop iterates only over the suffix of the vowel list (range(i, 5)), avoiding unnecessary additions for indices that would violate the ordering constraint. This targeted update pattern reduces the number of arithmetic operations per iteration.
  • The final aggregation uses Python’s built-in sum, which is implemented in C and therefore faster than a manual accumulation loop.

These choices collectively ensure that the algorithm runs efficiently even for large input sizes while maintaining clear and concise logic.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have five different magic treasure boxes labeled a, e, i, o, and u. This code is like a game where you want to fill these boxes with special string patterns.

At the very start, you have one invisible token in the first box when nothing has been built yet. The code uses a loop to look at the boxes over and over again, up to a certain number of steps. Every time the loop runs, it looks at how many tokens are in each box and moves them into new boxes. The rule for this game is that tokens can only stay in their current box or move into a box that comes after their current one.

Inside the loop, the code creates a fresh set of boxes and fills them based on the ones from the previous step. It carefully adds up the possibilities so that by the end, you know exactly how many different ways those tokens could have been placed into the boxes. It is just like counting how many paths you can take through a maze where you can only walk forward.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.19 | σ = 1.16

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Java Go
Progiez C++ Python Java
github black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
MacJim C++
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
MacJim C++
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
30 links | 21 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   December 22, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality