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
Find the count of sub-strings whose characters can be rearranged to form the given word in Python
Given a string S (all letters are lowercase), we need to find the count of all substrings of length four whose characters can be rearranged to form the word "bird".
For example, if the input is "birdb", the output will be 2 because there are two 4-character substrings that contain exactly one 'b', one 'i', one 'r', and one 'd'.
Approach
To solve this problem, we follow these steps −
Initialize a counter to 0
Iterate through all possible 4-character substrings
For each substring, count occurrences of 'b', 'i', 'r', 'd'
If each character appears exactly once, increment the counter
Example
Let us see the implementation to get better understanding −
def number_of_occurrence(s):
cnt = 0
for i in range(0, len(s) - 3):
bird = [0, 0, 0, 0] # Count for b, i, r, d
for j in range(i, i + 4):
if s[j] == 'b':
bird[0] += 1
elif s[j] == 'i':
bird[1] += 1
elif s[j] == 'r':
bird[2] += 1
elif s[j] == 'd':
bird[3] += 1
# Check if we have exactly one of each character
if bird == [1, 1, 1, 1]:
cnt += 1
return cnt
# Test with example
s = "birdb"
result = number_of_occurrence(s)
print(f"String: {s}")
print(f"Count of valid substrings: {result}")
String: birdb Count of valid substrings: 2
How It Works
For the string "birdb":
Substring "bird" (positions 0-3): contains b=1, i=1, r=1, d=1 ?
Substring "irdb" (positions 1-4): contains i=1, r=1, d=1, b=1 ?
Both substrings can be rearranged to form "bird", so the count is 2.
Alternative Approach Using Counter
We can also use Python's Counter for cleaner code −
from collections import Counter
def count_bird_substrings(s):
target = Counter("bird")
count = 0
for i in range(len(s) - 3):
substring = s[i:i + 4]
if Counter(substring) == target:
count += 1
return count
# Test with example
s = "birdb"
result = count_bird_substrings(s)
print(f"String: {s}")
print(f"Count of valid substrings: {result}")
String: birdb Count of valid substrings: 2
Conclusion
Both approaches work by checking each 4-character substring to see if it contains exactly the letters needed to form "bird". The Counter approach is more concise while the manual counting approach gives better control over the logic.
