Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if characters of one string can be swapped to form other in Python
Sometimes we need to check if we can rearrange the characters of one string to form another string. This is essentially checking if two strings are anagrams of each other.
So, if the input is like s = "worldlloeh" and t = "helloworld", then the output will be True as we can swap characters from "worldlloeh" to make "helloworld".
Algorithm
To solve this, we will follow these steps ?
- Check if both strings have the same length
- Count the frequency of each character in the first string
- For each character in the second string, decrease its count
- If any character count goes negative, return False
- If all characters are processed successfully, return True
Using Dictionary Approach
We can use a dictionary to count character frequencies ?
from collections import defaultdict
def solve(s, t):
s_len = len(s)
t_len = len(t)
if s_len != t_len:
return False
freq = defaultdict(int)
# Count characters in first string
for char in s:
freq[char] += 1
# Check characters in second string
for i in range(t_len):
freq[t[i]] -= 1
if freq[t[i]] < 0:
return False
return True
# Example 1
s = "worldlloeh"
t = "helloworld"
print(f"Can '{s}' be rearranged to '{t}'? {solve(s, t)}")
# Example 2
s1 = "listen"
t1 = "silent"
print(f"Can '{s1}' be rearranged to '{t1}'? {solve(s1, t1)}")
# Example 3
s2 = "python"
t2 = "java"
print(f"Can '{s2}' be rearranged to '{t2}'? {solve(s2, t2)}")
Can 'worldlloeh' be rearranged to 'helloworld'? True Can 'listen' be rearranged to 'silent'? True Can 'python' be rearranged to 'java'? False
Using Counter Method
Python's Counter class provides a more elegant solution ?
from collections import Counter
def can_swap_to_form(s, t):
return Counter(s) == Counter(t)
# Test examples
s = "worldlloeh"
t = "helloworld"
print(f"Using Counter: {can_swap_to_form(s, t)}")
s1 = "anagram"
t1 = "nagaram"
print(f"Using Counter: {can_swap_to_form(s1, t1)}")
Using Counter: True Using Counter: True
Using Sorted Method
Another simple approach is to sort both strings and compare ?
def can_swap_sorted(s, t):
return sorted(s) == sorted(t)
# Test examples
s = "worldlloeh"
t = "helloworld"
print(f"Using sorted: {can_swap_sorted(s, t)}")
s1 = "race"
t1 = "care"
print(f"Using sorted: {can_swap_sorted(s1, t1)}")
Using sorted: True Using sorted: True
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Dictionary/Counter | O(n) | O(k) | Large strings |
| Sorted | O(n log n) | O(n) | Simple implementation |
Conclusion
Use Counter for the most readable solution, dictionary approach for custom logic, or sorted method for simplicity. All methods check if characters can be rearranged to form another string.
