could someone help me optimize my python solution


  • 0
    R

    TLE problem. Thanks

    class Solution(object):
        def findAnagrams(self, s, p):
            """
            :type s: str
            :type p: str
            :rtype: List[int]
            """
            res = []
            lens = len(s)
            lenp = len(p)
            setp = set(p)
            for i in range(lens - lenp + 1):
                temp = set(s[i:i + lenp])
                if temp == setp:
                    res.append(i)
            return res

  • 1
    J

    The issue in your code is that you slice the string over and over, therefore the complexity gets over the roof.
    If you create dictionary of frequencies / array long enough to hold all possible characters (should be around ~130) then your code will be much faster.


  • 0
    R

    @jermenkoo Ok, thank you, I will try it!


Log in to reply
 

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