Checking if two strings are permutations of each other in Python
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Two strings are permutations of each other if they contain exactly the same characters with exactly the same counts, only in a different order. In Python, the cleanest solution depends on whether you want interview-style simplicity, fast frequency counting, or extra normalization such as ignoring spaces or case.
Start with the Definition
For exact comparison, two strings cannot be permutations if their lengths differ. That gives you a cheap early exit:
This works because sorting puts the same characters into the same order. If the sorted results match, the original strings are permutations.
Sorting Approach
The sorting solution is short and easy to explain:
Its time complexity is O(n log n) because sorting dominates the work. For many real inputs, that is perfectly fine and often the most readable answer.
Frequency Counting with Counter
If you want linear-time counting, use collections.Counter:
This is usually the best balance of clarity and performance in Python. It directly models the real condition: equal character frequencies.
Manual Counting for Restricted Character Sets
In interview problems, you may be asked to avoid sorting helpers or heavy library objects. If the character set is limited, such as ASCII letters, a manual counting table works well:
This approach is efficient, but it is only correct if you know the input character range in advance. It is less general than Counter, especially for full Unicode text.
Decide Whether Normalization Is Part of the Problem
Many "permutation" questions are underspecified. Do uppercase and lowercase count as different? Should spaces or punctuation be ignored? Those choices change the implementation.
For example, a case-insensitive, space-insensitive version can normalize first:
That is not "more correct" than the exact version. It is solving a different problem. The important part is making the rules explicit.
Common Pitfalls
- Forgetting the length check and doing unnecessary work.
- Using a restricted ASCII counting array for input that may contain Unicode characters.
- Ignoring the problem statement's rules about case, spaces, or punctuation.
- Treating sorting as inefficient in all cases when it is often the clearest answer.
- Confusing permutations with substrings or anagrams in a larger sentence.
Summary
- Two strings are permutations if they contain the same characters with the same counts.
- Sorting is the simplest exact solution and is often good enough.
- '
Countergives a direct and readable frequency-based solution.' - Manual counting works when the character set is known and restricted.
- Normalize only if the problem statement says to ignore case, spaces, or other characters.

