Maximum number of Strings with Common Prefix of length K
Last Updated :
21 Feb, 2023
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.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
Node* child[26];
int count = 0;
};
Node* root;
int result = 0, K;
void insert(string& s)
{
Node* curr = root;
for ( int i = 0; i < s.size(); i++) {
if (curr->child[s[i] - 'a' ] == NULL) {
curr->child[s[i] - 'a' ] = new Node();
}
curr->child[s[i] - 'a' ]->count++;
if (i + 1 == K) {
result = max(result,
curr->child[s[i] - 'a' ]->count);
break ;
}
curr = curr->child[s[i] - 'a' ];
}
}
int main()
{
vector<string> arr
= { { "hello" , "heydeei" , "hap" , "hak" , "paloa" ,
"padfk" , "padfla" , "pada" } };
K = 4;
root = new Node();
for ( auto s : arr) {
insert(s);
}
cout << result;
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static class Node {
Node []child = new Node[ 26 ];
int count = 0 ;
};
public static Node root;
public static int result = 0 , K;
public static void insert(String s)
{
Node curr= root;
for ( int i = 0 ; i < s.length(); i++) {
if (curr.child[s.charAt(i) - 'a' ] == null ) {
curr.child[s.charAt(i) - 'a' ] = new Node();
}
curr.child[s.charAt(i) - 'a' ].count++;
if (i + 1 == K) {
result = Math.max(result,curr.child[s.charAt(i) - 'a' ].count);
break ;
}
curr = curr.child[s.charAt(i) - 'a' ];
}
}
public static void main(String[] args)
{
String[] arr = { "hello" , "heydeei" , "hap" , "hak" , "paloa" ,
"padfk" , "padfla" , "pada" } ;
K = 4 ;
root = new Node();
for (String s : arr) {
insert(s);
}
System.out.print(result);
}
}
|
Python3
class Node:
def __init__( self ):
self .child = [ None ] * 26
self .count = 0
result = 0
K = 0
root = None
def insert(s):
global root
global result
global K
curr = root
for i in range ( len (s)):
if ( not curr.child[ ord (s[i]) - ord ( 'a' )]):
curr.child[ ord (s[i]) - ord ( 'a' )] = Node()
curr.child[ ord (s[i]) - ord ( 'a' )].count + = 1
if (i + 1 = = K):
result = max (result,curr.child[ ord (s[i]) - ord ( 'a' )].count)
break
curr = curr.child[ ord (s[i]) - ord ( 'a' )]
return curr
if __name__ = = '__main__' :
arr = [ "hello" , "heydeei" , "hap" , "hak" , "paloa" , "padfk" , "padfla" , "pada" ]
K = 4
N = len (arr)
root = Node()
for i in range (N):
insert(arr[i])
print (result)
|
C#
using System;
public class GFG {
class Node {
public Node[] child = new Node[26];
public int count = 0;
};
static Node root;
static int result = 0, K;
static void insert(String s)
{
Node curr = root;
for ( int i = 0; i < s.Length; i++) {
if (curr.child[s[i] - 'a' ] == null ) {
curr.child[s[i] - 'a' ] = new Node();
}
curr.child[s[i] - 'a' ].count++;
if (i + 1 == K) {
result = Math.Max(
result, curr.child[s[i] - 'a' ].count);
break ;
}
curr = curr.child[s[i] - 'a' ];
}
}
static void Main()
{
string [] arr
= { "hello" , "heydeei" , "hap" , "hak" ,
"paloa" , "padfk" , "padfla" , "pada" };
K = 4;
root = new Node();
for ( int i = 0; i < arr.Length; i++) {
insert(arr[i]);
}
Console.Write(result);
}
}
|
Javascript
class Node {
constructor(){
this .child = new Array(26);
this .count = 0;
}
}
let root;
let result = 0, K;
function insert( s)
{
let curr = root;
for (let i = 0; i < s.length; i++) {
let x= s.charCodeAt(i)-97;
if (curr.child[x] == null ) {
curr.child[x] = new Node();
}
curr.child[x].count++;
if (i + 1 == K) {
result = Math.max(result,
curr.child[x].count);
break ;
}
curr = curr.child[x];
}
}
let arr = [ "hello" , "heydeei" , "hap" , "hak" , "paloa" ,
"padfk" , "padfla" , "pada" ];
K = 4;
root = new Node();
for (let i=0;i<arr.length;i++) {
let s= arr[i];
insert(s);
}
console.log(result);
|
Time Complexity: O(N * K), where N is the length of the given string array.
Auxiliary Space: O(N * K)
Share your thoughts in the comments
Please Login to comment...