Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created July 3, 2023 21:02
Show Gist options
  • Save Ifihan/0eb60d0443b829fcf11e2ec805b01b9c to your computer and use it in GitHub Desktop.
Save Ifihan/0eb60d0443b829fcf11e2ec805b01b9c to your computer and use it in GitHub Desktop.
Find Common Characters

Find Common Characters

Question on Leetcode - Easy

Approach

My approach to this question was use a set to break down each string into a set and store their occurence to a hashmap. Then, I compare the values of each character to the length of the array.

For example, if a appears three times in the array and the length of the array is four, a is not going to be included in the result printed.

Any edge cases thought of? Nope. Not yet.

Code

Algoexpert

def commonCharacters(strings):
    char = {}
    for i in strings:
        unique = set(i)
        for chars in unique:
            if chars not in char:
                char[chars] = 0
            char[chars] += 1

    finalchar = []
    for k, v in char.items():
        if v == len(strings):
            finalchar.append(k)
    return finalchar

Leetcode

from collections import defaultdict

class Solution:
    def commonChars(self, words: List[str]) -> List[str]:
        res = [] 
        d = defaultdict(lambda: 0) 
        for x in words[0]:
            d[x] += 1
        
        for key in d:
            for word in words[1:]:
                if not key in word:
                    d[key] = 0
                else:
                    if d[key] > 1:
                        d[key] = min(d[key], word.count(key)) 
        for key, value in d.items():
            if value > 0:
                for i in range(value):
                    res.append(key)
        return res

Complexities

  • Time complexity: O(n x m)
  • Space complexity: O(c) - Total number of unique characters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment