A Simple Solution Explained
I have written about algorithms and how to practice them before, but I wanted to speak about something I do constantly, and that is overthink. Especially with easier problems I tend to make them much harder than needed. The best way I have discovered for me to help with this little issue is to take a step back, read the question again, and break down every step into what I need to do for a solution vs. what I can do.
An great example of an easy algorithm that can be over thought is Length of the Last Word. It’s straight forward: you’re given a string and you need to return the length of the last word. Simple. Right? Let me tell you how unsimple it can be made.
Firstly, my instinct says that I need to get an array out of that string to find the last word: let words = s.split(“ ”). So far so good. Now I need to find the last word, so I should use a loop right? Ok let’s try it out. Let’s use a reverse loop since I need to grab the last element.
O.K. Awesome, I can now get the last element and return its length! Wait, what if my string argument is a word with one letter? That doesn’t work. Also what about that edge case that if there is no word I need to return 0? Now I need an if statement, and what if my string starts as out as a space? Where should I put the if statement now? Do I need more than one?
This is what some describe as “panic mode”. For me it happens when I think something is easy, make an attempt, and realize there’s no digging myself out of the whole I created and my mind shuts off. This isn’t a good place to be for an interview, or on the job, or when baking a wedding cake for the first time. Anytime, really.
So let’s step back. Let’s look at our data and what it’s doing. We get a string, we need a number, and we can get that through an array. So we started out strong with the .split() to get our array. We also know that not only will we get strings full of fun letters but also whitespace, which we don’t count. So let’s just trim that out before we split. Now we have an array with just words. Perfect. Now loop? Nope, we just need the last element, which we can slice off at -1. Now we just need the length! NO! Thinking too fast again. We need the length of the element itself. Using slice we get a new array of just that element so if we return its length it would only be 1. How do we get that element in its entirety? Pop! Now we can use .length and we are in fact done. Take a look:
So nice, so elegant, so simple. In conclusion it’s easy to overthink but sometimes the solutions are just as simple as the problem itself.