How to find the longest common string prefix in array of strings with Swift

1 Answer

0 votes
import Foundation

func longestCommonPrefix(_ strs: [String]) -> String {
    guard !strs.isEmpty else { return "" }
    
    var prefix = strs[0]
    
    for str in strs {
        while !str.hasPrefix(prefix) {
            prefix = String(prefix.dropLast())
            if prefix.isEmpty { return "" }
        }
    }
    
    return prefix
}


let stringsArr = ["cartography", "carburettor", "carbonating"]

let commonPrefix = longestCommonPrefix(stringsArr)

print(commonPrefix) 


/*
run:

car

*/

 



answered Apr 25, 2025 by avibootz
...