Open In App

Weighted Prefix Search

Last Updated : 12 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 : 
 

C++




// C++ program to find the maximum weight with given prefix.
// Brute Force based C++ program to find the
// string with maximum weight and given prefix.
#include<bits/stdc++.h>
#define MAX 1000
using namespace std;
  
// Return the maximum weight of string having
// given prefix.
int maxWeight(char str[MAX][MAX], int weight[],
                          int n, char prefix[])
{
    int ans = -1;
    bool check;
  
    // Traversing all strings
    for (int i = 0; i < n; i++)
    {
        check = true;
  
        // Checking if string contain given prefix.
        for (int j=0, k=0; j < strlen(str[i]) &&
                           k < strlen(prefix); j++, k++)
        {
            if (str[i][j] != prefix[k])
            {
                check = false;
                break;
            }
        }
  
        // If contain prefix then finding
        // the maximum value.
        if (check)
            ans = max(ans, weight[i]);
    }
  
    return ans;
}
  
// Driven program
int main()
{
    int n = 3;
    char str[3][MAX] = { "geeks", "geeksfor", "geeksforgeeks" };
    int weight[] = {15, 30, 45};
    char prefix[] = "geek";
  
    cout << maxWeight(str, weight, n, prefix) << endl;
  
    return 0;
}


Java




// Java program to find the maximum 
// weight with given prefix.
  
class GFG {
    static final int MAX = 1000;
  
    // Return the maximum weight of string having
    // given prefix.
    static int maxWeight(String str[], int weight[],
                              int n, String prefix)
    {
        int ans = -1;
        boolean check;
  
        // Traversing all strings
        for (int i = 0; i < n; i++)
        {
            check = true;
  
            // Checking if string contain given prefix.
            for (int j=0, k=0; j < str[i].length() &&
                               k < prefix.length(); j++, k++)
            {
                if (str[i].charAt(j) != prefix.charAt(k))
                {
                    check = false;
                    break;
                }
            }
  
            // If contain prefix then finding
            // the maximum value.
            if (check)
                ans = Math.max(ans, weight[i]);
        }
  
        return ans;
    }
  
    // Driven program
    public static void main(String args[])
    {
        int n = 3;
        String str[] = { "geeks", "geeksfor", "geeksforgeeks" };
        int weight[] = {15, 30, 45};
        String prefix = "geek";
  
        System.out.println(maxWeight(str, weight, n, prefix));
    }
}
//This code is contributed by Sumit Ghosh


Python3




# Python program to find the maximum weight with given prefix.
  
# Return the maximum weight of string having
# given prefix.
def maxWeight(str, weight, n, prefix):
    ans = -1
    check = False
  
    # Traversing all strings
    for i in range(n):
        check = True
          
        # Checking if string contain given prefix.
        for j, k in zip(range(len(str[i])), range(len(prefix))):
            if str[i][j] != prefix[k]:
                check = False
                break
              
        # If contain prefix then finding
        # the maximum value.
        if check:
            ans = max(ans, weight[i])
  
    return ans
  
# Driver program
n = 3
str = ["geeks", "geeksfor", "geeksforgeeks"]
weight = [15, 30, 45]
prefix = "geek"
  
print(maxWeight(str, weight, n, prefix))
  
#  This code is contributed by Aman Kumar.


C#




// C# program to find the maximum weight 
// with given prefix.
using System;
  
class GFG 
{
  
    // Return the maximum weight of 
    // string having given prefix.
    static int maxWeight(string []str, int []weight,
                         int n, string prefix)
    {
        int ans = -1;
        bool check;
  
        // Traversing all strings
        for (int i = 0; i < n; i++)
        {
            check = true;
  
            // Checking if string contain given prefix.
            for (int j=0, k=0; j < str[i].Length &&
                     k < prefix.Length; j++, k++)
            {
                if (str[i][j] != prefix[k])
                {
                    check = false;
                    break;
                }
            }
  
            // If contain prefix then finding
            // the maximum value.
            if (check)
                ans = Math.Max(ans, weight[i]);
        }
  
        return ans;
    }
  
    // Driver Code
    public static void Main()
    {
        int n = 3;
        String []str = {"geeks", "geeksfor",
                         "geeksforgeeks"};
        int []weight = {15, 30, 45};
        String prefix = "geek";
  
        Console.WriteLine(maxWeight(str, weight, 
                          n, prefix));
    }
}
  
// This code is contributed by vt_m.


Javascript




<script>
    // Javascript program to find the maximum weight with given prefix.
      
    // Return the maximum weight of 
    // string having given prefix.
    function maxWeight(str, weight, n, prefix)
    {
        let ans = -1;
        let check;
    
        // Traversing all strings
        for (let i = 0; i < n; i++)
        {
            check = true;
    
            // Checking if string contain given prefix.
            for (let j=0, k=0; j < str[i].length &&
                     k < prefix.length; j++, k++)
            {
                if (str[i][j] != prefix[k])
                {
                    check = false;
                    break;
                }
            }
    
            // If contain prefix then finding
            // the maximum value.
            if (check)
                ans = Math.max(ans, weight[i]);
        }
    
        return ans;
    }
      
    let n = 3;
    let str = ["geeks", "geeksfor", "geeksforgeeks"];
    let weight = [15, 30, 45];
    let prefix = "geek";
  
    document.write(maxWeight(str, weight, 
                                n, prefix));
      
</script>


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 :
 

C++




// C++ program to find the maximum weight
// with given prefix.
#include<bits/stdc++.h>
#define MAX 1000
using namespace std;
  
// Structure of a trie node
struct trieNode
{
    // Pointer its children.
    struct trieNode *children[26];
  
    // To store weight of string.
    int weight;
};
  
// Create and return a Trie node
struct trieNode* getNode()
{
    struct trieNode *node = new trieNode;
    node -> weight = INT_MIN;
  
    for (int i = 0; i < 26; i++)
        node -> children[i] = NULL;
}
  
// Inserting the node in the Trie.
struct trieNode* insert(char str[], int wt, int idx,
                                struct trieNode* root)
{
    int cur = str[idx] - 'a';
  
    if (!root -> children[cur])
        root -> children[cur] = getNode();
  
    // Assigning the maximum weight
    root->children[cur]->weight =
                  max(root->children[cur]->weight, wt);
  
    if (idx + 1 != strlen(str))
        root -> children[cur] =
           insert(str, wt, idx + 1, root -> children[cur]);
  
    return root;
}
  
// Search and return the maximum weight.
int searchMaximum(char prefix[], struct trieNode *root)
{
    int idx = 0, n = strlen(prefix), ans = -1;
  
    // Searching the prefix in TRie.
    while (idx < n)
    {
        int cur = prefix[idx] - 'a';
  
        // If prefix not found return -1.
        if (!root->children[cur])
            return -1;
  
        ans = root->children[cur]->weight;
        root = root->children[cur];
        ++idx;
    }
  
    return ans;
}
  
// Return the maximum weight of string having given prefix.
int maxWeight(char str[MAX][MAX], int weight[], int n,
                                       char prefix[])
{
    struct trieNode* root = getNode();
  
    // Inserting all string in the Trie.
    for (int i = 0; i < n; i++)
        root = insert(str[i], weight[i], 0, root);
  
    return searchMaximum(prefix, root);
  
}
  
// Driven Program
int main()
{
    int n = 3;
    char str[3][MAX] = {"geeks", "geeksfor", "geeksforgeeks"};
    int weight[] = {15, 30, 45};
    char prefix[] = "geek";
  
    cout << maxWeight(str, weight, n, prefix) << endl;
  
    return 0;
}


Java




// Java program to find the maximum weight
// with given prefix.
  
public class GFG{
    static final int MAX = 1000;
      
    // Structure of a trie node
    static class TrieNode
    {
        // children
        TrieNode[] children = new TrieNode[26];
       
        // To store weight of string.
        int weight;
          
        // constructor
        public TrieNode() {
            weight = Integer.MIN_VALUE;
            for (int i = 0; i < 26; i++)
                children[i] = null;
        }
    }
    //static TrieNode root;
      
    // Inserting the node in the Trie.
    static TrieNode insert(String str, int wt, int idx, TrieNode root)
    {
        int cur = str.charAt(idx) - 'a';
       
        if (root.children[cur] == null)
            root.children[cur] = new TrieNode();
       
        // Assigning the maximum weight
        root.children[cur].weight =
                      Math.max(root.children[cur].weight, wt);
       
        if (idx + 1 != str.length())
            root.children[cur] =
               insert(str, wt, idx + 1, root.children[cur]);
       
        return root;
    }
       
    // Search and return the maximum weight.
    static int searchMaximum(String prefix, TrieNode root)
    {
        int idx = 0, ans = -1;
        int n = prefix.length();
       
        // Searching the prefix in TRie.
        while (idx < n)
        {
            int cur = prefix.charAt(idx) - 'a';
       
            // If prefix not found return -1.
            if (root.children[cur] == null)
                return -1;
       
            ans = root.children[cur].weight;
            root = root.children[cur];
            ++idx;
        }
       
        return ans;
    }
       
    // Return the maximum weight of string having given prefix.
    static int maxWeight(String str[], int weight[], int n,
                                           String prefix)
    {
        TrieNode root = new TrieNode();
       
        // Inserting all string in the Trie.
        for (int i = 0; i < n; i++)
            root = insert(str[i], weight[i], 0, root);
       
        return searchMaximum(prefix, root);
       
    }
       
    // Driven Program
    public static void main(String args[])
    {
        int n = 3;
        String str[] = { "geeks", "geeksfor", "geeksforgeeks" };
        int weight[] = {15, 30, 45};
        String prefix = "geek";
  
        System.out.println(maxWeight(str, weight, n, prefix));
    }
}
//This code is contributed by Sumit Ghosh


Python3




# Python program to find the maximum weight
# with given prefix.
# Structure of a trie node
class TrieNode:
    def __init__(self):
        # Pointer its children.
        self.children = [None] * 26
          
        # To store weight of string.
        self.weight = float('-inf')
  
# Create and return a Trie node
def get_node():
    return TrieNode()
  
# Inserting the node in the Trie.
def insert(string, weight, idx, root):
    cur = ord(string[idx]) - ord('a')
    if not root.children[cur]:
        root.children[cur] = get_node()
          
    # Assigning the maximum weight
    root.children[cur].weight = max(root.children[cur].weight, weight)
    if idx + 1 != len(string):
        root.children[cur] = insert(string, weight, idx + 1, root.children[cur])
    return root
  
# Search and return the maximum weight.
def search_maximum(prefix, root):
    idx, n, ans = 0, len(prefix), -1
      
    # Searching the prefix in Trie.
    while idx < n:
        cur = ord(prefix[idx]) - ord('a')
          
        # If prefix not found return -1.
        if not root.children[cur]:
            return -1
        ans = root.children[cur].weight
        root = root.children[cur]
        idx += 1
    return ans
  
# Return the maximum weight of string having given prefix.
def max_weight(strings, weights, n, prefix):
    root = get_node()
      
    # Inserting all string in the Trie.
    for i in range(n):
        root = insert(strings[i], weights[i], 0, root)
    return search_maximum(prefix, root)
  
# Driver code
if __name__ == '__main__':
    n = 3
    strings = ["geeks", "geeksfor", "geeksforgeeks"]
    weights = [15, 30, 45]
    prefix = "geek"
    print(max_weight(strings, weights, n, prefix))
      
# This code is contributed by prajwal kandekar


C#




// C# program to find the maximum weight
// with given prefix.
using System;
  
// Structure of a trie node
public class TrieNode {
    // Pointer its children.
    public TrieNode[] Children;
  
    // To store weight of string.
    public int Weight;
  
    public TrieNode()
    {
        Children = new TrieNode[26];
        Weight = int.MinValue;
    }
}
  
public class GFG {
    // Create and return a Trie node
    public static TrieNode GetNode()
    {
        return new TrieNode();
    }
  
    // Inserting the node in the Trie.
    public static TrieNode Insert(string str, int wt,
                                  int idx, TrieNode root)
    {
        int cur = str[idx] - 'a';
  
        if (root.Children[cur] == null)
            root.Children[cur] = GetNode();
  
        // Assigning the maximum weight
        root.Children[cur].Weight
            = Math.Max(root.Children[cur].Weight, wt);
  
        if (idx + 1 != str.Length)
            root.Children[cur] = Insert(str, wt, idx + 1,
                                        root.Children[cur]);
  
        return root;
    }
  
    // Search and return the maximum weight.
    public static int SearchMaximum(string prefix,
                                    TrieNode root)
    {
        int idx = 0, n = prefix.Length, ans = -1;
  
        // Searching the prefix in Trie.
        while (idx < n) {
            int cur = prefix[idx] - 'a';
  
            // If prefix not found return -1.
            if (root.Children[cur] == null)
                return -1;
  
            ans = root.Children[cur].Weight;
            root = root.Children[cur];
            ++idx;
        }
  
        return ans;
    }
  
    // Return the maximum weight of string having given
    // prefix.
    public static int MaxWeight(string[] str, int[] weight,
                                int n, string prefix)
    {
        TrieNode root = GetNode();
  
        // Inserting all string in the Trie.
        for (int i = 0; i < n; i++)
            root = Insert(str[i], weight[i], 0, root);
  
        return SearchMaximum(prefix, root);
    }
  
    // Driver Program
    public static void Main()
    {
        int n = 3;
        string[] str
            = { "geeks", "geeksfor", "geeksforgeeks" };
        int[] weight = { 15, 30, 45 };
        string prefix = "geek";
  
        Console.WriteLine(
            MaxWeight(str, weight, n, prefix));
    }
}
  
// This code is contributed by prasad264


Javascript




// JavaScript program to find the maximum weight
// with given prefix.
  
// Structure of a trie node
class TrieNode {
  constructor() {
    
    // Pointer its children.
    this.children = new Array(26);
    this.children.fill(null);
      
    // To store weight of string.
    this.weight = Number.NEGATIVE_INFINITY;
  }
}
  
// Create and return a Trie node
function get_node() {
  return new TrieNode();
}
  
// Inserting the node in the Trie.
function insert(string, weight, idx, root) {
  const cur = string.charCodeAt(idx) - 'a'.charCodeAt(0);
  if (!root.children[cur]) {
    root.children[cur] = get_node();
  }
    
  // Assigning the maximum weight
  root.children[cur].weight = Math.max(root.children[cur].weight, weight);
  if (idx + 1 !== string.length) {
    root.children[cur] = insert(string, weight, idx + 1, root.children[cur]);
  }
  return root;
}
  
// Search and return the maximum weight.
function search_maximum(prefix, root) {
  let idx = 0, n = prefix.length, ans = -1;
  
  // Searching the prefix in Trie.
  while (idx < n) {
    const cur = prefix.charCodeAt(idx) - 'a'.charCodeAt(0);
    // If prefix not found return -1.
    if (!root.children[cur]) {
      return -1;
    }
    ans = root.children[cur].weight;
    root = root.children[cur];
    idx += 1;
  }
  return ans;
}
  
// Return the maximum weight of string having given prefix.
function max_weight(strings, weights, n, prefix) {
  let root = get_node();
  
  // Inserting all string in the Trie.
  for (let i = 0; i < n; i++) {
    root = insert(strings[i], weights[i], 0, root);
  }
  return search_maximum(prefix, root);
}
  
// Driver code
const n = 3;
const strings = ["geeks", "geeksfor", "geeksforgeeks"];
const weights = [15, 30, 45];
const prefix = "geek";
console.log(max_weight(strings, weights, n, prefix));


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)

 



Similar Reads

Maximum sum increasing subsequence from a prefix and a given element after prefix is must
Given an array of n positive integers, write a program to find the maximum sum of increasing subsequence from prefix till ith index and also including a given kth element which is after i, i.e., k &gt; i. Examples : Input: arr[] = {1, 101, 2, 3, 100, 4, 5} i-th index = 4 (Element at 4th index is 100) K-th index = 6 (Element at 6th index is 5.) Outp
14 min read
Check if count of substrings in S with string S1 as prefix and S2 as suffix is equal to that with S2 as prefix and S1 as suffix
Given three strings S, S1, and S2, the task is to check if the number of substrings that start and end with S1 and S2 is equal to the number of substrings that start and end with S2 and S1 or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "helloworldworldhelloworld", S1 = "hello", S2 = "world"Output: NoExpla
8 min read
Prefix Factorials of a Prefix Sum Array
Given an array arr[] consisting of N positive integers, the task is to find the prefix factorials of a prefix sum array of the given array i.e., [Tex]prefix[i] = (\sum_{0}^{i}arr[i])! [/Tex]. Examples: Input: arr[] = {1, 2, 3, 4}Output: 1 6 720 3628800Explanation:The prefix sum of the given array is {1, 3, 6, 10}. Therefore, prefix factorials of th
10 min read
Maximum prefix sum which is equal to suffix sum such that prefix and suffix do not overlap
Given an array arr[] of N Positive integers, the task is to find the largest prefix sum which is also the suffix sum and prefix and suffix do not overlap. Examples: Input: N = 5, arr = [1, 3, 2, 1, 4]Output: 4Explanation: consider prefix [1, 3] and suffix [4] which gives maximum prefix sum which is also suffix sum such that prefix and suffix do not
7 min read
Search a string in the dictionary with a given prefix and suffix for Q queries
Given an array arr[] consisting of N strings and Q queries in form of two strings prefix and suffix, the task for each query is to find any one string in the given array with the given prefix and suffix. If there exists no such string then print "-1". Examples: Input: arr[] = {"apple", "app", "biscuit", "mouse", "orange", "bat", "microphone", "mine
15+ min read
Longest Common Prefix using Binary Search
Given a set of strings, the tasks is to find the longest common prefix using Binary Search. Input: str = {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output: "gee" Explanation: All the given strings have "gee" prefix common in them, which is the longest them. Input: {"apple", "ape", "april"} Output: "ap" Some other approaches to Longest Common Pref
10 min read
Shortest path with exactly k edges in a directed and weighted graph
Given a directed and two vertices ‘u’ and ‘v’ in it, find shortest path from ‘u’ to ‘v’ with exactly k edges on the path. The graph is given as adjacency matrix representation where value of graph[i][j] indicates the weight of an edge from vertex i to vertex j and a value INF(infinite) indicates no edge from i to j. For example, consider the follow
15+ min read
Probability of a random pair being the maximum weighted pair
Given two arrays A and B, a random pair is picked having an element from array A and another from array B. Output the probability of the pair being maximum weighted. Examples: Input : A[] = 1 2 3 B[] = 1 3 3 Output : 0.222 Explanation : Possible pairs are : {1, 1}, {1, 3}, {1, 3}, {2, 1}, {2, 3}, {2, 3}, {3, 1}, {3, 3}, {3, 3} i.e. 9. The pair with
7 min read
Find the root of the sub-tree whose weighted sum XOR with X is maximum
Given a tree, and the weights of all the nodes, the task is to find the root of the sub-tree whose weighted sum XOR with given integer X is maximum.Examples: Input: X = 15 Output: 4 Weight of sub-tree for parent 1 = ((-1) + (5) + (-2) + (-1) + (3)) XOR 15 = 4 XOR 15 = 11 Weight of sub-tree for parent 2 = ((5) + (-1) + (3)) XOR 15 = 7 XOR 15 = 8 Wei
7 min read
Weighted sum of the characters of a string in an array | Set 2
You are given an array of strings str[], the task is to find the score of a given string s from the array. The score of a string is defined as the product of the sum of its characters’ alphabetical values with the position of the string in the array. Examples: Input: str[] = {"sahil", "shashanak", "sanjit", "abhinav", "mohit"}, s = "abhinav" Output
10 min read
three90RightbarBannerImg