LeetCode: Count Vowels Permutation Solution

Memoized recursion

Approach

recursion(i, char)
number of valid strings of
n - i
length, starting with
char

Implementation

1/**
2 * @param {number} n
3 * @return {number}
4 */
5var countVowelPermutation = function (n) {
6 const MOD = 1e9 + 7
7
8 const possibleNext = {
9 a: "e",
10 e: "ai",
11 i: "aeou",
12 o: "iu",
13 u: "a",
14 }
15
16 const memo = Array.from({ length: n }, _ => ({}))
17
18 const recursion = (i, char, possibleChars = "aeiou") => {
19 if (i === n) return 1
20
21 if (memo[i][char]) return memo[i][char]
22
23 let res = 0
24
25 for (const possibleChar of possibleChars) {
26 res =
27 (res + recursion(i + 1, possibleChar, possibleNext[possibleChar])) % MOD
28 }
29
30 return (memo[i][char] = res)
31 }
32
33 return recursion(0)
34}

Comments

Loading comments...

Tags

leetcode

dynamic programming

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Reshape the Matrix

Jul 5, 2021

Flat, reverse, and pop

Previous Post

LeetCode: Find K Closest Elements

Jul 3, 2021

Sort with custom comparator

HoningJS

Search Posts