Maximum Palindromes

  • + 1 comment

    My solution

    def _FACT_TABLE():
        facts=[0, 1, 2]
        def _fact(n):
            if n<len(facts)-1:
                return facts[n]
            for i in range(len(facts), n+1):
                facts.append(facts[i-1]*i)
            return facts[n]
        return _fact
    
    _fact=_FACT_TABLE()
    
    
    def _sort(symbs):
        p_s=[x//2 for x in symbs.values() if x//2 > 0 ]
        m_s=[x%2 for x in symbs.values() if x%2 > 0 ]
        return p_s, m_s
       
       
    def _to_symbs(l, r):
        symbs={}
        for i in range(l-1,r):
            symbs[S[i]]=symbs.get(S[i],0)+1
        return symbs
        
        
    def _calculate(p_s, m_s):
        res=_fact(max(sum(p_s), 1))
        for x in p_s:
            res=int(res/_fact(x))
        res=res*max(len(m_s),1)
        return res
        
        
    def answerQuery(l, r):
        # Return the answer for this query modulo 1000000007.
        symbs=_to_symbs(l,r)
        if len(symbs)==1:
            return 1
        p_s, m_s=_sort(symbs)
        return _calculate(p_s, m_s)