3

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]
            candidate.append(tmp)

        print(max(candidate))

Error Message

Time Limit Exceeded
2
  • 5
    Time Limit Exceeded means they ran your code on a bigger input, and the code is slow. You need to optimize your code to reduce runtime complexity.
    – brokenfoot
    Sep 14, 2019 at 2:10
  • Note that without knowing what your task actually is, it is very difficult to help you optimize your code. Sep 14, 2019 at 6:14

2 Answers 2

5

This error comes when you don't have written code in Good Time complexity. When the Leetcode system ran your code with bigger input your code did not run in optimal time. There may be some known Algorithm to solve your problem statement. Search the question statement on internet you will find some Algorithm to solve this problem.

2

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.