Problem: Given a list of strings, write a function to find the longest common prefix among them. If there is no common prefix, return an empty string.
Function signature: def longest_common_prefix(strs: List[str]) -> str:
Explanation: The problem asks us to find the longest common prefix among a given list of strings. We can solve this problem by iterating over the characters of the first string in the list and comparing them with the corresponding characters in the other strings. If we encounter a character that does not match, we can return the prefix up to that point. If we reach the end of the first string without encountering a mismatch, we add that character to our prefix and continue comparing it with the next string in the list. We repeat this process until we have compared all the strings in the list.
Test case 1:
vbnetCopy codeInput: strs = ["flower", "flow", "flight"]
Output: "fl"
Explanation: The longest common prefix among the given strings is "fl".
Test case 2:
vbnetCopy codeInput: strs = ["dog", "racecar", "car"]
Output: ""
Explanation: There is no common prefix among the given strings, so we return an
empty string.
here’s the Kotlin code for the problem:
fun longestCommonPrefix(strs: List<String>): String {
if (strs.isEmpty()) {
return ""
}
val firstStr = strs[0]
for (i in firstStr.indices) {
val char = firstStr[i]
for (j in 1 until strs.size) {
if (i == strs[j].length || strs[j][i] != char) {
return firstStr.substring(0, i)
}
}
}
return firstStr
}
fun main() {
val strs1 = listOf("flower", "flow", "flight")
val prefix1 = longestCommonPrefix(strs1)
println("Longest common prefix of $strs1: $prefix1")
val strs2 = listOf("dog", "racecar", "car")
val prefix2 = longestCommonPrefix(strs2)
println("Longest common prefix of $strs2: $prefix2")
}