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 email@example.com. 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.
- Longest Common Prefix using Trie
- Count of strings whose prefix match with the given string to a given length k
- Find shortest unique prefix for every word in a given list | Set 1 (Using Trie)
- Longest prefix matching - A Trie based solution in Java
- Longest string in an array which matches with prefix of the given string
- Splay Tree | Set 1 (Search)
- 2-3 Trees | (Search and Insert)
- Ternary Search Tree
- Trie | (Insert and Search)
- K Dimensional Tree | Set 1 (Search and Insert)
- Ternary Search Tree (Deletion)
- Treap | Set 2 (Implementation of Search, Insert and Delete)
- Treap (A Randomized Binary Search Tree)
- Self-Balancing-Binary-Search-Trees (Comparisons)
- Longest word in ternary search tree
Improved By : vt_m