string permutations
Python programming
string comparison
algorithm
coding tutorial

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:

python
1def are_permutations(a: str, b: str) -> bool:
2    if len(a) != len(b):
3        return False
4    return sorted(a) == sorted(b)

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:

python
1def are_permutations_sorted(a: str, b: str) -> bool:
2    if len(a) != len(b):
3        return False
4    return sorted(a) == sorted(b)
5
6print(are_permutations_sorted("listen", "silent"))
7print(are_permutations_sorted("apple", "papel"))
8print(are_permutations_sorted("apple", "apply"))

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:

python
1from collections import Counter
2
3def are_permutations_counter(a: str, b: str) -> bool:
4    if len(a) != len(b):
5        return False
6    return Counter(a) == Counter(b)
7
8print(are_permutations_counter("abc", "cba"))
9print(are_permutations_counter("aabbcc", "abcabc"))

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:

python
1def are_permutations_ascii(a: str, b: str) -> bool:
2    if len(a) != len(b):
3        return False
4
5    counts = [0] * 128
6
7    for ch in a:
8        counts[ord(ch)] += 1
9
10    for ch in b:
11        counts[ord(ch)] -= 1
12        if counts[ord(ch)] < 0:
13            return False
14
15    return True

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:

python
1from collections import Counter
2
3def normalize(text: str) -> str:
4    return "".join(ch.lower() for ch in text if not ch.isspace())
5
6def are_permutations_normalized(a: str, b: str) -> bool:
7    a = normalize(a)
8    b = normalize(b)
9    return Counter(a) == Counter(b)

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.
  • 'Counter gives 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.

Course illustration
Course illustration

All Rights Reserved.