How to tackle time limit exceeded error in leetcode
Asked Answered
M

3

5

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
Moon answered 14/9, 2019 at 1:50 Comment(2)
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.Quenchless
Note that without knowing what your task actually is, it is very difficult to help you optimize your code.Knowland
N
4

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)
Nebulous answered 14/9, 2019 at 11:32 Comment(1)
it would be better to do lens = (len(x) for x in strs) as generators are mostly faster then listsHindi
C
11

This error happens when your submitted answer doesn't have a good time complexity.

When the Leetcode system ran your code with a bigger input, your code did not finish quickly enough. There may be some known algorithm to solve your problem statement. Search the question statement on the internet and you will find some algorithm to solve the problem.

Candlemas answered 11/2, 2022 at 17:40 Comment(0)
N
4

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)
Nebulous answered 14/9, 2019 at 11:32 Comment(1)
it would be better to do lens = (len(x) for x in strs) as generators are mostly faster then listsHindi
T
0

If you are getting this error, there are some potential issues:

  1. Infinite loop
  2. Incorrect variable updates
  3. Incorrect pointer updates

Fundamentally, it is your code that's causing the issue. Check everything is properly written and your are not breaking your code.

Theorize answered 19/9 at 6:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.