|
| 1 | +# Link to problem: https://leetcode.com/problems/find-common-characters/ |
| 2 | + |
| 3 | +def commonChars(A): |
| 4 | + length = len(A) |
| 5 | + |
| 6 | + # Edge case: Only one string given; return all characters in it |
| 7 | + if length == 1: |
| 8 | + return list(A[0]) |
| 9 | + |
| 10 | + # Dictionary to hold characters common amongst all strings |
| 11 | + common_chars = {} |
| 12 | + |
| 13 | + # Populate common_chars with the character count of the first word |
| 14 | + for char in A[0]: |
| 15 | + if char in common_chars: |
| 16 | + common_chars[char] += 1 |
| 17 | + else: |
| 18 | + common_chars[char] = 1 |
| 19 | + |
| 20 | + for i in range(1, length): |
| 21 | + curr_word = A[i] |
| 22 | + |
| 23 | + # Shallow copy of the current common characters so far |
| 24 | + # We will update the contents of this dictionary |
| 25 | + curr_chars = common_chars.copy() |
| 26 | + |
| 27 | + # Only update for characters already in curr_chars |
| 28 | + # We only care about the common characters, so don't |
| 29 | + # create new entries for newly encountered chars |
| 30 | + for char in curr_word: |
| 31 | + if char in curr_chars: |
| 32 | + curr_chars[char] -= 1 |
| 33 | + |
| 34 | + for key, val in curr_chars.items(): |
| 35 | + old_com = common_chars[key] |
| 36 | + |
| 37 | + # Exact same number of instances as common_chars, or more. |
| 38 | + # Keep the original common_chars entry |
| 39 | + if val <= 0: |
| 40 | + continue |
| 41 | + # No instances of the common char in this word; remove from |
| 42 | + # the common_char dictionary |
| 43 | + elif val == old_com: |
| 44 | + del common_chars[key] |
| 45 | + # Some non-zero number of instances of the char, but less than |
| 46 | + # the common_chars |
| 47 | + else: |
| 48 | + common_chars[key] = old_com - curr_chars[key] |
| 49 | + |
| 50 | + # Parse the common_chars dict into proper final format |
| 51 | + ans = [] |
| 52 | + |
| 53 | + for key, val in common_chars.items(): |
| 54 | + for _ in range(val): |
| 55 | + ans.append(key) |
| 56 | + |
| 57 | + return ans |
0 commit comments