2185. Counting Words With a Given Prefix
Approach
Count words where w.StartsWith(pref) is true.
Key Techniques
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.
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.
A prefix sum array pre-computes cumulative values so any range query is answered in O(1). The classic sum of range [l, r] = prefix[r+1] - prefix[l]. 2D prefix sums extend this to matrix sub-rectangle queries. Combine with a hash map for "subarray sum equals k" problems.
// Approach: Count words where w.StartsWith(pref) is true.
// Time: O(n * p) Space: O(1)
public class Solution
{
public int PrefixCount(string[] words, string pref)
{
return words.Count(w => w.StartsWith(pref));
}
}