At an index, if all strings have the same character, set of these characters will have length one.
Say there are strings and the shortest string has length
. There are
iterations. In each iteration both collecting characters at a given index and creating the set takes time
.
Time: , space:
.
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
common_prefix = []
for heads in zip(*strs):
if len(set(heads)) != 1:
break
common_prefix.append(heads[0])
return "".join(common_prefix)
Leave a comment