Why is my Python solution failed with "Time Limit Exceeded"?

  • 0

    Hi, can any of you tell me why my solution fails the test with "Time Limit Exceeded" error?

    class Solution:
        # @param {string} s
        # @return {string}
        def shortestPalindrome(self, s):
            if self.is_palindrome(s):
                return s
            # adding a character to left at a time starting with second char
            new_s = ''
            for i in range(1, len(s)):
                if not new_s:
                    new_s = s[i] + s
                    new_s = s[i] + new_s
                if self.is_palindrome(new_s):
                    return new_s
        def is_palindrome(self, s):
            length = len(s)
            is_palin = True
            for i in range(length):
                if s[i] != s[length-1-i]:
                    is_palin = False
                if i == length - 1 - i:
            return is_palin

  • -2
    This post is deleted!

  • 0

    You are using a Brute-Force way. One of the test cases has 20000 'a'. This kind of test will consume lots of time.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.