I’ve wrote my code for Longest Common Prefix in LeetCode, but it was returned “Time Limit Exceeded”.
There is no specific error message, so I have no idea how to fix my code to pass test cases.
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: #find the number of shortest characters shortest_num = 0 nums =  * len(strs) for i in range(len(strs)): nums[i] = len(strs[i]) shortest_num = min(nums) l1 = strs l2 = strs l3 = strs for j in range(shortest_num): tmp = "" while l1[j] == l2[j] and l2[j] == l3[j]: tmp += l1[j] candidate.append(tmp) print(max(candidate))
Time Limit Exceeded
It is faster to always use list comprehensions.
For example to get the list of string lengths use the following
lens = [len(x) for x in strs] min_len = min(lens)