Longest Common Prefix

Niani Byrd
1 min readDec 19, 2021

Let’s switch gears and attack a DSA problem, but solve it in Ruby! Ruby was the first programming language I learned at Flatiron School. It truly is a beautiful language, and a great intro into the world of coding! So take a look at the following question:

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 ""

The first thing we’ll do is the easiest part. We know that if there is no common prefix, we must return an empty string, so let’s just take care of that first.

def longest_common_prefix(strs)
return "" if strs.empty?
end

Next, we’ll go through the base string, and iterate over each index. During each iteration, we’ll check if that letter exists in all the other words in the array at the same position.

def longest_common_prefix(strs)
return "" if strs.empty?
s = ""
base = strs[0]
for i in 0..base.length-1
end

If there exists a match, we append it to the string.

def longest_common_prefix(strs)
return "" if strs.empty?
s = ""
base = strs[0]
for i in 0..base.length-1
if strs.all?{|x| x[i] == base[i]}
s += base[i]

Once we continue iterating and there is no longer a match, we break.

def longest_common_prefix(strs)
return "" if strs.empty?
s = ""
base = strs[0]
for i in 0..base.length-1
if strs.all?{|x| x[i] == base[i]}
s += base[i]
else
break
end
end
s
end

Happy coding! :)

--

--