How to tackle time limit exceeded error in leetcode


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 = [0] * len(strs)
        for i in range(len(strs)):
            nums[i] = len(strs[i])
            shortest_num = min(nums)

        l1 = strs[0]
        l2 = strs[1]
        l3 = strs[2]

        for j in range(shortest_num):
            tmp = ""
            while l1[j] == l2[j] and l2[j] == l3[j]:
                tmp += l1[j]


Error Message

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)


Leave a Reply

Your email address will not be published. Required fields are marked *