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.
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 :
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 :
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Strings from an array which are not prefix of any other string
- Longest Common Prefix using Trie
- Count of strings whose prefix match with the given string to a given length k
- Longest prefix matching - A Trie based solution in Java
- Find shortest unique prefix for every word in a given list | Set 1 (Using Trie)
- Longest string in an array which matches with prefix of the given string
- Trie | (Insert and Search)
- Ternary Search Tree
- Search in a trie Recursively
- 2-3 Trees | (Search and Insert)
- Splay Tree | Set 1 (Search)
- Ternary Search Tree (Deletion)
- K Dimensional Tree | Set 1 (Search and Insert)
- Longest word in ternary search tree
- Self-Balancing-Binary-Search-Trees (Comparisons)
Improved By : vt_m