VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-number-of-strings-with-common-prefix-of-length-k/

⇱ Maximum number of Strings with Common Prefix of length K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum number of Strings with Common Prefix of length K

Last Updated : 23 Jul, 2025

Given a string array arr[] of length N, the task is to find the maximum number of strings that share a common prefix of length K.

Examples:

Input: arr = { { "hello", "heydeei", "hap", "hak", "paloa", "padfk", "padfla", "pada" } }, K = 4
Output: 2
Explanation: String padfk", "padfla" are the two string that share the common prefix of length k.

Input: arr = { { "happy", "hapi", "hape", "hak", "paloa", "padfk", "padfla", "pada" } }, K = 3
Output: 3

An approach using Trie:

The idea is to use Trie data structure to keep a count of all occurrences of a prefix by maintaining a variable count in the structure of the node of Trie. While inserting a new string into trie keep checking K character of new strings are inserted or not. If we'd already inserted K characters into trie than maximise the count of prefix at that node.

Follow the steps below to implement the above idea:

  • Iterate over the given string array and Insert the given strings into Trie one by one
    • Initialize a trie node curr which points to the root initially
    • Iterate over the length of the given string
      • Check if the node for the current character exists in trie
        • If not exist then create a new trie node and assign the reference to the current node child
      • Increment the count of prefixes.
      • Check if the length of the current string becomes greater than the required K.
        • If true, then update the result with the maximum between the current result or the count of occurrences of the current prefix.
      • Move the current pointer to the next node

Below is the implementation of the above approach.


Output
2

Time Complexity: O(N * K), where N is the length of the given string array.
Auxiliary Space: O(N * K)

Comment