Problem statement

https://leetcode.com/problems/custom-sort-string/

Solution

Create counter of string T. First we need to iterate all symbols from S and if they are in our counter, add them to answer and remove these symbols from counter. Then iterate through the rest of counter and add symbols to the end of string.

Complexity

Time complexity is O(n+26), where n is size of T and 26 is size of alphabet. Space complexity is O(26) to keep counter.

Code

class Solution:
    def customSortString(self, S, T):
        cnt, ans = Counter(T), ""
        for s in S:
            if s in cnt:
                ans += s*cnt[s]
                cnt.pop(s)
                
        return ans + "".join(s*cnt[s] for s in cnt)