imashutosh51

Longest Common String

Feb 26th, 2026 (edited)
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 KB | None | 0 0
  1. class Solution:
  2.     def longestCommonPrefix(self, strs: List[str]) -> str:
  3.         if not strs:
  4.             return ""
  5.  
  6.         for i in range(len(strs[0])):
  7.             char = strs[0][i]
  8.             for s in strs:
  9.                 if i >= len(s) or s[i] != char:
  10.                     return strs[0][:i]
  11.  
  12.         return strs[0]
  13. M-2:
  14. #Sort the array and compare the first and last string
  15. class Solution:
  16.     def longestCommonPrefix(self, strs: List[str]) -> str:
  17.         if not strs:
  18.             return ""
  19.        
  20.         strs.sort()
  21.         first = strs[0]
  22.         last = strs[-1]
  23.        
  24.         i = 0
  25.         while i < len(first) and i < len(last) and first[i] == last[i]:
  26.             i += 1
  27.        
  28.         return first[:i]
Advertisement
Add Comment
Please, Sign In to add comment