Algorithm Question: LongestCommon Prefix
In this algorithm journey, I’ll be going over the Longest Common Prefix problem. This took me a while to solve but eventually, I was able to solve the problem. The problem states “Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix return an empty string”. My initial thought to solve this problem was to loop through the array and compare it to the first letters that match the array. This approach was decent, however, I questioned how I was going to execute?
Constraints and Challenges
My initial thought process was in the right direction, However, my execution needed to follow through. Brainstorming through this problem I faced the challenge of how was I going to extract and return the common prefix of each word in the array. I knew I had to compare each word in the array so I thought of looping through the array and comparing the current index to the next one and if it matches return the prefix. That particular strategy failed, Leetcode wanted a more dynamic approach.
I was able to come up with a solution that satisfied Leetcode. Below is my pseudo-code and thought process for solving the problem.
I was able to solve the problem through a few simple steps. My first step was to set a variable to an empty string. I would use this variable throughout this problem. The basic rule I had to apply and was given to me is if the length of the argument, a string, is equal to zero return an empty string. Therefore if given “ “ I would just return the variable. Now that the basic rule is out of the way, This leaves us room for solving the actual problem. I used a for loop to iterate through the array, however, I compared the initial index, which was zero, to the first word of the string. In the loop, I would create a variable labeled char and set it to the first word of the array of the current index. To be able to compare the first word of the array to the rest of the words in the array I would have to create another for loop. Once both for loops were added, I proceeded to initiate the conditional. If char does not equal the value or type of the current index of the first and second loop return prefix, otherwise increment the prefix to char. Here's the solution below.