Open In App

Weighted sum of the characters of a string in an array | Set 2

Improve
Improve
Like Article
Like
Save
Share
Report

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: 228 
Sum of alphabetical values of “abhinav” = 1 + 2 + 8 + 9 + 14 + 1 + 22 = 57 
Position of “abhinav” in str is 4, 57 x 4 = 228 

Input: str[] = {“geeksforgeeks”, “algorithms”, “stack”}, s = “algorithms” 
Output: 244 

Naive approach:

  • Find the sum of characters of given string s and store it into variable ‘a’
  • Find the position of given string s in str and store it into variable ‘b’
  • Find the product of a * b.

Below is the implementation of the above approach:

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the required string score
int strScore(string str[], string s, int n)
{
    int a = 0;
 
    // Find the sum of character of given string s
    // and store into variable a
    for (auto c : s)
        a += (c - 'a') + 1;
 
    int b = 0;
 
    // Find the position of given string s in str
    // and store into variable b
    for (int i = 0; i < n; i++) {
        if (str[i] == s) {
            b = i + 1;
            break;
        }
    }
 
    // Find the product of a * b.
    return a * b;
}
 
// Driver code
int main()
{
    string str[] = { "sahil", "shashanak", "sanjit",
                     "abhinav", "mohit" };
    string s = "abhinav";
    int n = sizeof(str) / sizeof(str[0]);
    int score = strScore(str, s, n);
    cout << score;
 
    return 0;
}


Java




// Java implementation of the approach
 
import java.util.*;
 
public class GFG {
 
    // Function to return the required string score
    static int strScore(String str[], String s, int n)
    {
        int a = 0;
 
        // Find the sum of character of given string s
        // and store into variable a
        for (char c : s.toCharArray())
            a += (c - 'a') + 1;
 
        int b = 0;
 
        // Find the position of given string s in str
        // and store into variable b
        for (int i = 0; i < n; i++) {
            if (str[i].equals(s)) {
                b = i + 1;
                break;
            }
        }
 
        // Find the product of a * b.
        return a * b;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str[] = { "sahil", "shashanak", "sanjit",
                         "abhinav", "mohit" };
        String s = "abhinav";
        int n = str.length;
        int score = strScore(str, s, n);
        System.out.println(score);
    }
}
 
// This code is contributed by Karandeep1234


Python3




# Python implementation of the approach
 
# Function to return the required string score
def strScore(str, s, n):
    a = 0;
 
    # Find the sum of character of given string s
    # and store into variable a
    for i in range(0,len(s)):
        a += (ord(s[i]) - ord('a')) + 1;
 
    b = 0;
 
    # Find the position of given string s in str
    # and store into variable b
    for i in range(0,n):
        if (str[i] == s):
            b = i + 1;
            break;
 
    # Find the product of a * b.
    return a * b;
 
# Driver code
str = [ "sahil", "shashanak", "sanjit",
                 "abhinav", "mohit" ];
s = "abhinav";
n = len(str);
score = strScore(str, s, n);
print(score);
 
# This code is contributed by poojaagarwal2.


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GfG {
 
    // Function to return the required string score
    static int strScore(String[] str, String s, int n)
    {
        int a = 0;
 
        // Find the sum of character of given string s
        // and store into variable a
        for (int i = 0; i < s.Length; i++)
             a += (s[i] - 'a') + 1;
       
       // Console.WriteLine(a);
 
        int b = 0;
 
        // Find the position of given string s in str
        // and store into variable b
        for (int i = 0; i < n; i++) {
            if (str[i] == s) {
                b = i + 1;
                break;
            }
        }
 
        // Find the product of a * b.
        return a * b;
    }
    
 
    // Driver code
    public static void Main()
    {
        string[] str
            = { "sahil", "shashanak", "sanjit",
                         "abhinav", "mohit"  };
        string s = "abhinav";
        int n = str.Length;
        Console.WriteLine(strScore(str, s, n));
    }
}


Javascript




// Javascript implementation of the approach
 
// Function to return the required string score
function strScore(str, s, n)
{
    let a = 0;
 
    // Find the sum of character of given string s
    // and store into variable a
    for (let i=0; i<s.length; i++)
    {
        a += s[i].charCodeAt(0)-'a'.charCodeAt(0) + 1;
    }
 
    let b = 0;
 
    // Find the position of given string s in str
    // and store into variable b
    for (let i = 0; i < n; i++) {
        if (str[i] == s) {
            b = i + 1;
            break;
        }
    }
 
    // Find the product of a * b.
    return a * b;
}
 
// Driver code
    let str = [ "sahil", "shashanak", "sanjit",
                     "abhinav", "mohit" ];
    let s = "abhinav";
    let n = str.length;
    let score = strScore(str, s, n);
    document.write(score);


Output

228

Time Complexity: O(max(N, M)), where N and M are the lengths of given string ‘str’ and the length of string ‘s’
Auxiliary Space: O(1)

Approach: 
In SET 1, we saw an approach where every time a query is being executed, the position of the string has to be found with a single traversal of str[]. This can be optimized when there are a number of queries using a hash table. 

  • Create a hash map of all the strings present in str[] along with their respective positions in the array.
  • Then for every query s, check if s is present in the map. If yes then calculate the sum of the alphabetical values of s and store it in sum.
  • Print sum * pos where pos is the value associated with s in map i.e. its position in str[].

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the required string score
int strScore(string str[], string s, int n)
{
    // create a hash map of strings in str
    unordered_map<string, int> m;
 
    // Store every string in the map
    // along with its position in the array
    for (int i = 0; i < n; i++)
        m[str[i]] = i + 1;
 
    // If given string is not present in str[]
    if (m.find(s) == m.end())
        return 0;
 
    int score = 0;
 
    for (int i = 0; i < s.length(); i++)
        score += s[i] - 'a' + 1;
 
    // Multiply sum of alphabets with position
    score = score * m[s];
 
    return score;
}
 
// Driver code
int main()
{
    string str[] = { "geeksforgeeks", "algorithms", "stack" };
    string s = "algorithms";
    int n = sizeof(str) / sizeof(str[0]);
    int score = strScore(str, s, n);
    cout << score;
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.HashMap;
import java.util.Map;
 
class GfG
{
    // Function to return the required string score
    static int strScore(String str[], String s, int n)
    {
        // create a hash map of strings in str
        HashMap<String, Integer> m = new HashMap<>();
     
        // Store every string in the map
        // along with its position in the array
        for (int i = 0; i < n; i++)
            m.put(str[i], i + 1);
     
        // If given string is not present in str[]
        if (!m.containsKey(s))
            return 0;
     
        int score = 0;
     
        for (int i = 0; i < s.length(); i++)
            score += s.charAt(i) - 'a' + 1;
     
        // Multiply sum of alphabets with position
        score = score * m.get(s);
     
        return score;
    }
 
    // Driver code
    public static void main(String []args)
    {
        String str[] = { "geeksforgeeks", "algorithms",
                                            "stack" };
        String s = "algorithms";
        int n = str.length;
        System.out.println(strScore(str, s, n));
         
    }
}
 
// This code is contributed by Rituraj Jain


Python3




# Python3 implementation of the approach
 
# Function to return the required
# string score
def strScore(string, s, n) :
 
    # create a hash map of strings in str
    m = {}
 
    # Store every string in the map
    # along with its position in the array
    for i in range(n) :
        m[string[i]] = i + 1
 
    # If given string is not present in str[]
    if s not in m.keys() :
        return 0
 
    score = 0
 
    for i in range(len(s)) :
        score += ord(s[i]) - ord('a') + 1
 
    # Multiply sum of alphabets
    # with position
    score = score * m[s]
 
    return score
 
# Driver code
if __name__ == "__main__" :
 
    string = [ "geeksforgeeks",
               "algorithms", "stack" ]
    s = "algorithms"
    n = len(string)
    score = strScore(string, s, n);
    print(score)
 
# This code is contributed by Ryuga


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GfG
{
    // Function to return the required string score
    static int strScore(string [] str, string s, int n)
    {
        // create a hash map of strings in str
        Dictionary<string, int> m = new Dictionary<string, int>();
         
        // Store every string in the map
        // along with its position in the array
        for (int i = 0; i < n; i++)
            m[str[i]] = i + 1;
     
        // If given string is not present in str[]
        if (!m.ContainsKey(s))
            return 0;
     
        int score = 0;
     
        for (int i = 0; i < s.Length; i++)
            score += s[i] - 'a' + 1;
     
        // Multiply sum of alphabets with position
        score = score * m[s];
     
        return score;
    }
 
    // Driver code
    public static void Main()
    {
        string [] str = { "geeksforgeeks", "algorithms",
                                            "stack" };
        string s = "algorithms";
        int n = str.Length;
        Console.WriteLine(strScore(str, s, n));
         
    }
}
 
// This code is contributed by ihritik


Javascript




<script>
 
// JavaScript Program to implement
// the above approach
 
    // Function to return the required string score
    function strScore(str, s, n)
    {
        // create a hash map of strings in str
        let m = new Map();
     
        // Store every string in the map
        // along with its position in the array
        for (let i = 0; i < n; i++)
            m.set(str[i], i + 1);
     
        // If given string is not present in str[]
        if (!m.has(s))
            return 0;
     
        let score = 0;
     
        for (let i = 0; i < s.length; i++)
            score += s[i].charCodeAt() - 'a'.charCodeAt() + 1;
     
        // Multiply sum of alphabets with position
        score = score * m.get(s);
     
        return score;
    }
 
// Driver Code
 
        let str = [ "geeksforgeeks", "algorithms",
                                            "stack" ];
        let s = "algorithms";
        let n = str.length;
        document.write(strScore(str, s, n));
 
</script>


Output

244

Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(n), for using map



Last Updated : 18 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads