VOOZH about

URL: https://www.geeksforgeeks.org/dsa/weighted-prefix-search/

⇱ Weighted Prefix Search - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Weighted Prefix Search

Last Updated : 12 Sep, 2023

Given n strings and a weight associated with each string. The task is to find the maximum weight of string having the given prefix. Print "-1" if no string is present with given prefix.
Examples: 
 

Input : 
s1 = "geeks", w1 = 15
s2 = "geeksfor", w2 = 30
s3 = "geeksforgeeks", w3 = 45
prefix = geek
Output : 45

All the string contain the given prefix, but
maximum weight of string is 45 among all.


 


 

Method 1: (Brute Force)


Check all the string for given prefix, if string contains the prefix, compare its weight with maximum value so far.
Below is the implementation of above idea : 
 

Output: 
 

45

Time Complexity: O(n*m*k) where n is the number of strings in the input array, m is the maximum length of any string in the array, and k is the length of the prefix. 
Auxiliary Space: O(n*m)
 

Method 2 (efficient):


The idea is to create and maintain a Trie. Instead of the normal Trie where we store the character, store a number with it, which is maximum value of its prefix. When we encounter the prefix again update the value with maximum of existing and new one. 
Now, search prefix for maximum value, run through the characters starting from the root, if one of character is missing return -1, else return the number stored in the root.
Below is the implementation of the above idea :
 

45

Time Complexity: O(n*m+k) where n is the number of strings in the input array, m is the maximum length of any string in the array, and k is the length of the prefix. 
Auxiliary Space: O(n*m)


 

Comment
Article Tags: