Code Logo

Lantern Vowel Pathways

Published at05 Jan 2026
Hard 2 views
Like6

You are given a grid of letters, and the job is to count how many valid pathways satisfy the vowel-order rule.

The key rule is about the vowels seen along a path. Whenever the path touches vowels, they must appear in nondecreasing order: you can stay on the same vowel or move forward from a to e to i and so on, but you are not allowed to go backward.

That means the path is not judged only by where it moves. It is also judged by the vowel history it builds while moving through the grid. Consonants are easier to handle because they do not force the vowel order backward.

So the task is to count all grid pathways that obey the movement rules while never breaking the nondecreasing vowel order.

Example Input & Output

Example 1
Input
grid = ["bc", "df"]
Output
2
Explanation

The possible paths do not break the vowel rule, so both of them count.

Example 2
Input
grid = ["ab", "oo"]
Output
2
Explanation

Paths "a->b->o->o" and "a->o->o" both have vowels in nondecreasing order.

Example 3
Input
grid = ["ae", "ia"]
Output
1
Explanation

Only one path keeps the vowels in a safe order from start to finish.

Algorithm Flow

Recommendation Algorithm Flow for Lantern Vowel Pathways
Recommendation Algorithm Flow for Lantern Vowel Pathways

Solution Approach

This is a dynamic programming problem because the answer for one partial path depends on two pieces of state: where you are in the grid, and what the latest vowel rank on the path is.

A useful state looks like this:

dp[row][col][lastVowel]

Here, lastVowel records the most advanced vowel seen so far. When you move to a new cell, there are two cases:

If the letter is a consonant, the vowel state stays the same.

If the letter is a vowel, it must have rank at least lastVowel; otherwise that path becomes invalid.

By propagating counts through the grid with that extra vowel-order state, we count only the paths that stay legal the whole time.

The nice thing about this DP is that it does not need to remember the whole path string. It only needs the current cell and the last vowel rank, which is enough to enforce the ordering rule.

Best Answers

java
class Solution {
    public int count_vowels(String s) {
        int count = 0;
        String vowels = "aeiouAEIOU";
        for (char c : s.toCharArray()) {
            if (vowels.indexOf(c) != -1) count++;
        }
        return count;
    }
}