VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-strings-whose-prefix-match-with-the-given-string-to-a-given-length-k/

⇱ Count k length prefix matches - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count k length prefix matches

Last Updated : 2 May, 2026

Given an array of strings arr[] and some queries where each query consists of a string str and an integer k. The task is to find the count of strings in arr[] whose prefix of length k matches with the k length prefix of str.
Examples:

Input: arr[] = ["abba", "abbb", "abbc", "abbd", "abaa", "abca"], str = "abbg", k = 3 
Output:
"abba", "abbb", "abbc" and "abbd" are the matching strings.

Input: arr[] = ["geeks", "geeksforgeeks", "forgeeks"], str = "geeks", k = 2 
Output:

[Naive Approach] Using Direct Prefix Comparison - O(n * k) Time and O(1) Space

We compare the first k characters of the given string with the first k characters of every string in the array. If they match, we count that string.


Output
4

[Optimal Approach] Using Trie (Prefix Counting) - O(n * L + k) Time and O(n * L) Space

We use a Trie to store all strings and maintain frequency at each node. While inserting, we increment the frequency for every prefix. Then for a given string, we traverse up to length k and return the frequency stored at that node, which represents how many strings share that prefix.

  • Create a Trie node structure with 26 children and frequency
  • Insert all strings into the Trie. While inserting, increment frequency at each node
  • Start traversing the given string from root, move character by character in Trie. If path breaks, return 0
  • When length k is reached, return stored frequency

Output
4


Comment
Article Tags:
Article Tags: