merge list of strings into one sorted string So I was tasked the following: 


  Given a list of strings, output a sorted string that consists of all
  lowercase characters  (a-z) from each string in the list.
  
  Example 
  
  [aba, xz] -> aabxz


I tried this:

from collections import Counter
from string import ascii_lowercase 
def merge(strings):
    counter = Counter()
    for string in strings:
        for char in string:
            counter[char] +=1

    result = []
    for c in ascii_lowercase:
        if c in counter:
            for _ in range(counter[c]):
                result.append(c)
    return "".join(result)


This works on most test cases, but times out on a couple test cases. I am extremely frustrated. How can I  improve the time complexity of this solution?
counter = Counter()
for string in strings:
    for char in string:
        counter[char] +=1



You are flattening your strings list to count each individual characters. For starter, if you were to extract letters individually, you could feed it to the Counter constructor and avoid the += 1 operation. Second, flattening an iterable is best done using itertools.chain.from_iterable:

counter = Counter(itertools.chain.from_iterable(strings))





result = []
for c in ascii_lowercase:
    if c in counter:
        for _ in range(counter[c]):
            result.append(c)
return "".join(result)



Instead of the inner for loop, you can create repeated sequence of characters using c * counter[c]. This also have the neat advantage to produce the empty string ('') when counter[c] is 0, removing the need for the c in counter test:

return ''.join(c * counter[c] for c in ascii_lowercase)




These changes result in a ×4 speedup on my machine.