Weighted Uniform Strings

  • + 0 comments

    Here is a solution in python with O(n + m) time and O(m) space.

    The space is in part because althogh the set cat grow as large as 26, values can be access at O(1) and the queries are the values that we search for in the set at a time of O(m) and equel space.

    def weightedUniformStrings(s, queries):
        res = []
        q_set = set([])
        weight = 0
        
        for i in range(len(s)): # O(n)
            if i == 0 or s[i] != s[i - 1]:
                weight = ord(s[i]) - ord('a') + 1
            else:
                weight += ord(s[i]) - ord('a') + 1
            
            q_set.add(weight) # O(n)
    
        for val in queries: # O(m)
            if val in q_set:
                res.append("Yes")
            else:
                res.append("No")
                
        return res