Skip to content

Instantly share code, notes, and snippets.

@gokhanakkurt
Created October 18, 2019 08:50
Show Gist options
  • Save gokhanakkurt/42c15fca1fdacf9a26c18afa62a2fef3 to your computer and use it in GitHub Desktop.
Save gokhanakkurt/42c15fca1fdacf9a26c18afa62a2fef3 to your computer and use it in GitHub Desktop.
Find longest common prefix string in an array - (swift implementation, slicing method)
func longestCommonPrefix(_ strs: [String]) -> String {
// base case
if strs.isEmpty {
return ""
}
if var prefixStr = strs.first {
for index in 1..<strs.count {
let str = strs[index]
while str.contains(prefixStr) == false {
let index = prefixStr.index(prefixStr.startIndex, offsetBy: prefixStr.count - 1)
prefixStr = String(prefixStr[..<index])
if prefixStr.count == 0 {
return ""
}
}
}
return prefixStr
}
return ""
}
longestCommonPrefix(["flower", "florida", "flow"])
@PeterPaktorDev
Copy link

will be failed in case like ["c","acc","ccc"]

@avii-7
Copy link

avii-7 commented May 12, 2025

If the first word is too long and the other words are short, then your code ends up with character count of the first word iterations of while loop.

Example: ["abcdefgijklmnopqrstuvwxyz", "b"]


My version.

// LC: https://leetcode.com/problems/longest-common-prefix

// TC -> O(min(strs) * n)
// SC -> O(str.first!.count)

func longestCommonPrefix(_ strs: [String]) -> String {
    
    if strs.count == 1 {
        return strs.first!
    }
    
    guard let temp = strs.first, !temp.isEmpty else {
        return ""
    }
    
    var endIndex: String.Index? = nil
    
    outerLoop: 
    for index in temp.indices {
            for str in strs {
    
                if str.isEmpty {
                    return ""
                }
    
                // checking index out of range and characters equality
                if index >= str.endIndex || str[index] != temp[index] {
                    break outerLoop
                }
            }
            endIndex = index
        }
    
    if let endIndex {
        return String(temp[...endIndex])
    }
    
    return ""
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment