Here is the next problem:
Although the description doesn’t seem like much and the problem is labeled as ‘Easy’, it is in fact a bit challenging to code an efficient solution. Here are some examples of input and output:
As you can see, the concept of the problem is quite simple, intuitively, however the execution of the solution is a bit more difficult to write in lines of code. Nevertheless, that is what I’m here for. Here is how I decided to write my solution:
Let’s break it down. The first two lines(inside the brackets of the method), are a check to make sure there are no errors due to the array being empty:
Next, I simply created a temporary local variable called prefix, and set it equal to the string in the first index of the array, strs:
After that, I traversed through the array and made a nested while loop. The logic behind this was to check each other value in the array and compare how much of the first value in strs was the beginning of each other value in the array. Pretty much, the variable prefix is the entire first value, and every time that another value in the array does not start with prefix, the last character of prefix is taken off, and the process repeats until all the other values in the array begin with prefix. While that sounds like a lot, it is actually only 3 lines. After that, all you do is return prefix. Here is what that looks like:
Once again, here is the final product:
Here is my output:
Here are the logistics of my solution:
This is by far my best solution so far in all my solutions on my site, at least analytically speaking. Anyways, if you have any suggestions, be sure to let me know in the comments section below. I hope you guys at least learned something today and that you all have a great day!