|
1 |
| -def check_permutation(input_str_1: str, input_str_2: str) -> bool: |
| 1 | +from typing import Dict |
| 2 | + |
| 3 | + |
| 4 | +def check_permutation_with_sorting(input_str_1: str, input_str_2: str) -> bool: |
2 | 5 | """
|
3 | 6 | Check if two strings are permutations of each other.
|
4 | 7 |
|
@@ -32,3 +35,52 @@ def check_permutation(input_str_1: str, input_str_2: str) -> bool:
|
32 | 35 | return False
|
33 | 36 |
|
34 | 37 | return True
|
| 38 | + |
| 39 | +def check_permutation_with_map(input_str_1: str, input_str_2: str) -> bool: |
| 40 | + """ |
| 41 | + Check if two strings are permutations of each other. |
| 42 | +
|
| 43 | + This function determines whether two input strings are permutations of one |
| 44 | + another by comparing the frequency of characters in each string. It considers |
| 45 | + case sensitivity and whitespace as significant when evaluating the two strings. |
| 46 | +
|
| 47 | + Complexity: |
| 48 | + Time: O(n) as iteration is handled on each string where n is the number of characters in each string |
| 49 | + Space: O(n) as a dictionary is used to store characters for lookups |
| 50 | +
|
| 51 | + Args: |
| 52 | + input_str_1 (str): The first input string to compare. |
| 53 | + input_str_2 (str): The second input string to compare. |
| 54 | +
|
| 55 | + Returns: |
| 56 | + bool |
| 57 | + True if the two strings are permutations of each other, False otherwise. |
| 58 | + """ |
| 59 | + # strings of different lengths can not be permutations of each other |
| 60 | + if len(input_str_1) != len(input_str_2): |
| 61 | + return False |
| 62 | + |
| 63 | + input_str_1_lower = input_str_1.lower() |
| 64 | + input_str_2_lower = input_str_2.lower() |
| 65 | + |
| 66 | + char_count: Dict[str, int] = dict() |
| 67 | + |
| 68 | + # Now, if input_str_1 and input_str_2 are permutations of each other, the two for loops will counterbalance each |
| 69 | + # other and the values of all the keys in char_count should be 0. |
| 70 | + # We find this out at the end where we evaluate count == 0 for all the keys in char_count. Using the all function, |
| 71 | + # we combine the evaluation results from all the iterations and return it from the function. The all() function |
| 72 | + # returns True if all items in an iterable are True. Otherwise, it returns False. |
| 73 | + |
| 74 | + for char in input_str_1_lower: |
| 75 | + if char in char_count: |
| 76 | + char_count[char] += 1 |
| 77 | + else: |
| 78 | + char_count[char] = 1 |
| 79 | + |
| 80 | + for char in input_str_2_lower: |
| 81 | + if char in char_count: |
| 82 | + char_count[char] -= 1 |
| 83 | + else: |
| 84 | + return False |
| 85 | + |
| 86 | + return all(count == 0 for count in char_count.values()) |
0 commit comments