![]() |
VOOZH | about |
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
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:
Below is the implementation of the above approach.
2
Time Complexity: O(N * K), where N is the length of the given string array.
Auxiliary Space: O(N * K)