Program to count the number of consistent strings in Python

Suppose we have a string s consisting of distinct characters and also have an array of strings called words. A string is consistent when all characters in the string appear in the string s. We have to find the number of consistent strings present in the array words.

So, if the input is like s = "px", words = ["ad", "xp", "pppx", "xpp", "apxpa"], then the output will be 3 because there are three strings with only 'p' and 'x': ["xp", "pppx", "xpp"].

Algorithm

To solve this, we will follow these steps −

  • Initialize count = 0

  • For each word in the words array:

    • Check if all characters in the word exist in string s

    • If any character is not found in s, skip this word

    • If all characters are found, increment the count

  • Return the final count

Method 1: Using Nested Loop with Break

This approach uses a for-else construct to check each character in every word ?

def solve(s, words):
    count = 0
    for i in range(len(words)):
        for j in range(len(words[i])):
            if words[i][j] not in s:
                break
        else:
            count += 1
    return count

s = "px"
words = ["ad", "xp", "pppx", "xpp", "apxpa"]
print(solve(s, words))
3

Method 2: Using Set Operations

A more Pythonic approach using set operations to check if all characters are present ?

def solve_with_sets(s, words):
    allowed_chars = set(s)
    count = 0
    
    for word in words:
        word_chars = set(word)
        if word_chars.issubset(allowed_chars):
            count += 1
    
    return count

s = "px"
words = ["ad", "xp", "pppx", "xpp", "apxpa"]
print(solve_with_sets(s, words))
3

Method 3: Using all() Function

Using Python's built-in all() function for cleaner code ?

def solve_with_all(s, words):
    return sum(1 for word in words if all(char in s for char in word))

s = "px"
words = ["ad", "xp", "pppx", "xpp", "apxpa"]
print(solve_with_all(s, words))
3

Comparison

Method Time Complexity Space Complexity Readability
Nested Loop O(n × m) O(1) Medium
Set Operations O(n × m) O(k) High
all() Function O(n × m) O(1) Very High

Where n is the number of words, m is the average length of words, and k is the number of unique characters.

Conclusion

All three methods solve the problem effectively. The set-based approach is most efficient for large character sets, while the all() function provides the most readable solution. Choose based on your preference for readability versus performance.

Updated on: 2026-03-25T20:30:38+05:30

753 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements