py_string_permutation_checker — Permutation / Anagram Check
Difficulty: hard
Write a function that determines if two strings are permutations of each other. Two strings are permutations if they contain the same characters with the same frequencies. The comparison is case-sensitive.
def string_permutation_checker(s1: str, s2: str) -> bool:
Examples
>>> string_permutation_checker("abc", "bca")
True
>>> string_permutation_checker("abc", "def")
False
>>> string_permutation_checker("listen", "silent")
True
>>> string_permutation_checker("hello", "bello")
False
>>> string_permutation_checker("", "")
True
>>> string_permutation_checker("a", "")
False
>>> string_permutation_checker("Abc", "abc")
False
>>> string_permutation_checker("a gentleman", "elegant man")
True
Solution
Download py_string_permutation_checker.pydef string_permutation_checker(s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
return sorted(s1) == sorted(s2)
How It Works
Goal: Confirm both strings use the same characters with the same multiplicities.
Approach: Two strings are permutations of each other iff their sorted character sequences are identical.
Step by step:
- Length mismatch is an instant
False(and an early exit avoids needless sorting). sorted(s)returns a list of characters in ascending order.- Compare the two sorted lists with
==.
Key concept: Sorting normalizes any permutation to the same canonical form, so two permutations of the same multiset will always compare equal after sorting.