DDSA Solutions

1684. Count the Number of Consistent Strings

Time: O(n*m)
Space: O(1)
Advertisement

Approach

Boolean set of allowed chars; count words where every char is in set.

Key Techniques

Array

Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.

Hash Table

Hash tables provide O(1) average-case lookup, insert, and delete. They are the go-to tool for counting frequencies, detecting complements (Two Sum pattern), and caching seen values. In C#, use Dictionary<K,V> for maps and HashSet<T> for membership checks.

String

String problems range from simple character counting to complex pattern matching. Common approaches include two pointers, sliding window, prefix hashing, and the KMP algorithm. In C#, strings are immutable — use StringBuilder for efficient concatenation inside loops.

1684.cs
C#
// Approach: Boolean set of allowed chars; count words where every char is in set.
// Time: O(n*m) Space: O(1)

public class Solution
{
    public int CountConsistentStrings(string allowed, string[] words)
    {
        bool[] s = new bool[26];

        foreach (char c in allowed)
            s[c - 'a'] = true;

        int ans = 0;

        foreach (string w in words)
        {
            if (Check(w, s))
                ans++;
        }

        return ans;
    }

    private bool Check(string w, bool[] s)
    {
        for (int i = 0; i < w.Length; i++)
        {
            if (!s[w[i] - 'a'])
                return false;
        }

        return true;
    }
}
Advertisement
Was this solution helpful?