Sunday, February 1, 2026

Longest Common Prefix

Profile Pic of Akash AmanAkash Aman

Updated: February 2026

Longest Common Prefix
easy

💡 Intuition

  • The longest common prefix must be shared by all strings, so we compare characters at the same positions and stop at the first mismatch.
  • The characters matched up to that point form the longest common prefix.

f l o w e rf l o wf l i g h tf l o wf l o wf l o w e rf l o w e rf l i g h tf l i g h tMatchedMatchedUnmatchedfl

🚀 Solution

go
func longestCommonPrefix(strs []string) string { for i,char := range strs[0] { for _,str := range strs[1:] { if i == len(str) || char != rune(str[i]) { return str[0:i]; } } } return strs[0]; }

⏳ Time Complexity

  • Since we iterate using two nested loops over n strings and up to m characters (where m is the length of the shortest string / common sequence), the overall time complexity isO(n x m).