Tile Letter Possibilities

nathan brickett
3 min readAug 9, 2020

--

Today we are going to be solving the LeetCode problem — Tile Letter Possibilities. The question is this:

So we are given an input that is a string of tiles, we can see in our notes there will always be at least one tile and no more than seven tiles. Also we do not need to worry about lowercase letters. Right away we can see that this is a combination problem. We want to find out how many combinations we can make with these particular tiles. It seems fairly obvious that a depth first search function will help us solve this problem. Lets begin:

First let’s make a hash that will hold our letters and their corresponding tile counts. We will then create a function that recursively iterates through all of the combinations in our hash.

Here we create our ‘letterHash’ which holds our letters and their respective counts, we then run our dfs function. Let’s get into the nitty gritty…

Here is our dfs function, now whats going on? Our dfs function takes a hash as an argument. First it initializes a variable called sum and sets it equal to zero. Then we begin our for loop where we loop through each key in the hash or in our case each letter. In our for loop we first check to see if the letter count in our hash is equal to zero. If it is, then continue in our for loop and skip to the next letter. If the count is anything other than zero, we increase the sum by one, we subtract one from the letter count, and then we set sum equal to sum + dfs(hash), after we return from our recursive calls, it will increase the letter count by one, and then continue to the next letter in the for loop. When the for loop has finished it will return the sum.

Now I have a very hard time visualizing these recursive calls and it helps me to write it out so that I can track these variables myself and really see how this function actually operates. Recursive functions sometimes seem like magic, but it’s extremely important to understand what’s actually happening on each recursive call.

Thanks for reading this far, hopefully this helped you visualize whats going on and made these recursive functions a bit less intimidating.

--

--

No responses yet