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
Selected Reading
Check whether second string can be formed from characters of first string in Python
Suppose we have two strings s and t. We have to check whether t can be formed using characters of s or not.
So, if the input is like s = "owleh" t = "hello", then the output will be True.
Algorithm
To solve this, we will follow these steps ?
- freq := a map containing all characters and their frequencies
- for i in range 0 to size of t - 1, do
- if freq[t[i]] is 0, then
- return False
- freq[t[i]] := freq[t[i]] - 1
- if freq[t[i]] is 0, then
- return True
Method 1: Using defaultdict
Let us see the following implementation to get better understanding ?
from collections import defaultdict
def solve(s, t):
freq = defaultdict(int)
for i in range(len(s)):
freq[s[i]] += 1
for i in range(len(t)):
if freq[t[i]] == 0:
return False
freq[t[i]] -= 1
return True
s = "owhtlleh"
t = "hello"
print(solve(s, t))
True
Method 2: Using Counter
We can also use Python's Counter class for a more concise solution ?
from collections import Counter
def can_form_string(s, t):
s_count = Counter(s)
t_count = Counter(t)
for char, needed in t_count.items():
if s_count[char] < needed:
return False
return True
s = "owhtlleh"
t = "hello"
print(can_form_string(s, t))
True
Method 3: Using Dictionary
Here's a solution using regular dictionary without defaultdict ?
def check_formation(s, t):
char_count = {}
# Count characters in first string
for char in s:
char_count[char] = char_count.get(char, 0) + 1
# Check if second string can be formed
for char in t:
if char not in char_count or char_count[char] == 0:
return False
char_count[char] -= 1
return True
s = "programming"
t = "gram"
print(check_formation(s, t))
s2 = "hello"
t2 = "world"
print(check_formation(s2, t2))
True False
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| defaultdict | O(m + n) | O(m) | No key checking needed |
| Counter | O(m + n) | O(m + n) | Most concise code |
| Regular dict | O(m + n) | O(m) | No imports required |
Conclusion
All three methods efficiently check if one string can be formed from another by counting character frequencies. The Counter approach is most readable, while defaultdict avoids key existence checks.
Advertisements
