Open In App

Cost to make a string Pangram

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given an array arr[] containing the cost of adding each alphabet from (a – z) and a string str which may or may not be a Pangram. The task is to find the total cost to make the string Pangram.

Examples: 

Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26}, 
str = “abcdefghijklmopqrstuvwz ” 
Output : 63 
n, x and y are the only characters missing to convert the string into a Pangram. 
And their costs are 14, 24 and 25 respectively. 
Hence, total cost = 14 + 24 + 25 = 63

Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26}, 
str = “thequickbrownfoxjumpsoverthelazydog” 
Output:
The string is already a Pangram as it contains all the characters from (a – z). 

Approach: Mark all the alphabets from (a – z) that occurred in str then find the missing alphabets from the string. Add the cost of these missing alphabets to get the total cost required to make the string Pangram.

Algorithm:

  •   Initialize a variable cost to 0 and a boolean array happened with a size of 26, with all entries initialized to false.
  •  Mark every instance of an alphabet in the string where it appeared by iterating through the string str and setting the occurred index for each instance to true.
  • Iterate through every element of the array arr, and if an index’s value in the occurred boolean array is false, add that index’s value in arr to the cost variable.
  • Return the cost variable as the total cost required to make the string Pangram.

Below is the implementation of the above approach: 

C++




// C++ program to find the cost to make a string Pangram
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the total cost required
// to make the string Pangram
int pangramCost(int arr[], string str)
{
    int cost = 0;
    bool occurred[26] = { false };
 
    // Mark all the alphabets that occurred in the string
    for (int i = 0; i < str.size(); i++)
        occurred[str[i] - 'a'] = true;
 
    // Calculate the total cost for the missing alphabets
    for (int i = 0; i < 26; i++) {
        if (!occurred[i])
            cost += arr[i];
    }
 
    return cost;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
                  16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 };
    string str = "abcdefghijklmopqrstuvwz";
 
    cout << pangramCost(arr, str);
    return 0;
}


Java




// Java program to find the cost to make a string Pangram
 
class GFG
{
        // Function to return the total cost required
        // to make the string Pangram
        static  int pangramCost(int arr[], String str)
        {
            int cost = 0;
            boolean []occurred=new boolean[26];
             
            for(int i=0;i<26;i++)
             occurred[i]=false;
         
            // Mark all the alphabets that occurred in the string
            for (int i = 0; i < str.length(); i++)
                occurred[str.charAt(i) - 'a'] = true;
         
            // Calculate the total cost for the missing alphabets
            for (int i = 0; i < 26; i++) {
                if (occurred[i]==false)
                    cost += arr[i];
            }
         
            return cost;
        }
         
        // Driver Code
        public static void main(String []args)
        {
            int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
                        16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 };
            String str = "abcdefghijklmopqrstuvwz";
         
            System.out.println(pangramCost(arr, str));
         
    }
}
 
 
// This code is contributed by ihritik


Python3




# Python3 program to find the cost
# to make a string Pangram
 
# Function to return the total cost
# required to make the string Pangram
def pangramCost(arr, string) :
     
    cost = 0
    occurred = [False] * 26
 
    # Mark all the alphabets that
    # occurred in the string
    for i in range(len(string)) :
        occurred[ord(string[i]) - ord('a')] = True
 
    # Calculate the total cost for
    # the missing alphabets
    for i in range(26) :
        if (not occurred[i]) :
            cost += arr[i]
 
    return cost
 
# Driver Code
if __name__ == "__main__" :
 
    arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9,
            10, 11, 12, 13, 14, 15, 16,
            17, 18, 19, 20, 21, 22, 23,
            24, 25, 26 ]
    string = "abcdefghijklmopqrstuvwz"
 
    print(pangramCost(arr, string))
 
# This code is contributed by Ryuga


C#




// C# program to find the cost to make a string Pangram
 
using System;
class GFG
{
        // Function to return the total cost required
        // to make the string Pangram
        static  int pangramCost(int []arr, string str)
        {
            int cost = 0;
            bool []occurred=new bool[26];
             
            for(int i=0;i<26;i++)
             occurred[i]=false;
         
            // Mark all the alphabets that occurred in the string
            for (int i = 0; i < str.Length; i++)
                occurred[str[i] - 'a'] = true;
         
            // Calculate the total cost for the missing alphabets
            for (int i = 0; i < 26; i++) {
                if (occurred[i]==false)
                    cost += arr[i];
            }
         
            return cost;
        }
         
        // Driver Code
        public static void Main(string []args)
        {
            int []arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
                        16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 };
            string str = "abcdefghijklmopqrstuvwz";
         
            Console.WriteLine(pangramCost(arr, str));
         
    }
}
 
 
// This code is contributed by ihritik


Javascript




<script>
 
// Javascript program to find the cost to
// make a string Pangram
 
// Function to return the total cost required
// to make the string Pangram
function pangramCost(arr, str)
{
    var cost = 0;
    var occurred = new Array(26);
     
    for(let i = 0; i < 26; i++)
        occurred[i] = false;
     
    // Mark all the alphabets that occurred
    // in the string
    for(let i = 0; i < str.length; i++)
        occurred[str[i].charCodeAt() -
                    'a'.charCodeAt()] = true;
     
    // Calculate the total cost for
    // the missing alphabets
    for(let i = 0; i < 26; i++)
    {
        if (occurred[i] == false)
            cost += arr[i];
    }
    return cost;
}
 
// Driver Code
var arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
            11, 12, 13, 14, 15, 16, 17, 18,
            19, 20, 21, 22, 23, 24, 25, 26 ];
var str = "abcdefghijklmopqrstuvwz";
 
document.write(pangramCost(arr, str));
 
// This code is contributed by bunnyram19
 
</script>


PHP




<?php
// PHP program to find the cost to make
// a string Pangram
 
// Function to return the total cost
// required to make the string Pangram
function pangramCost($arr, $str)
{
    $cost = 0;
    $occurred = array();
     
    for($i = 0; $i < 26; $i++)
        $occurred[$i] = false;
 
    // Mark all the alphabets that occurred
    // in the string
    for($i = 0; $i < strlen($str); $i++)
    {
         
        $idx = ord($str[$i]) - 97;
        $occurred[$idx] = true;
    }
     
    // Calculate the total cost for the
    // missing alphabets
    for($i = 0; $i < 26; $i++)
    {
        if ($occurred[$i] == false)
            $cost += $arr[$i];
    }
 
    return $cost;
}
 
// Driver Code
$arr = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
             11, 12, 13, 14, 15, 16, 17, 18,
             19, 20, 21, 22, 23, 24, 25, 26 );
$str = "abcdefghijklmopqrstuvwz";
 
echo pangramCost($arr, $str);
 
// This code is contributed by ihritik
?>


Output

63

Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(26) ? O(1), no extra space is required, so it is a constant.

New Approach:-   

Alternative Approach to find the cost to make a string Pangram:

  • Instead of using a boolean array to keep track of the occurrence of each alphabet, we can use a HashSet to store the distinct alphabets that appeared in the string. We can then iterate over all the alphabets from ‘a’ to ‘z’, and if an alphabet is not present in the HashSet, we add the corresponding cost from the given array to the total cost.

Algorithm:

  1. Initialize a variable cost to 0.
  2. Create a HashSet distinct to store the distinct alphabets that appeared in the string.
  3. Iterate through the string str, and for each character c, add it to the distinct set.
  4. Iterate over all the alphabets from ‘a’ to ‘z’, and if an alphabet is not present in the distinct set, add the corresponding cost from the given array to the total cost.
  5. Return the total cost.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to return the total cost required
// to make the string Pangram
int pangramCost(int arr[], string str)
{
    int cost = 0;
    unordered_set<char> distinct;
    // Add all distinct alphabets that appeared in the
    // string
    for (int i = 0; i < str.length(); i++) {
        char c = str[i];
        distinct.insert(c);
    }
 
    // Iterate over all the alphabets from 'a' to 'z',
    // and add the corresponding cost for missing
    // alphabets
    for (char c = 'a'; c <= 'z'; c++) {
        if (distinct.find(c) == distinct.end()) {
            cost += arr;
        }
    }
 
    return cost;
}
 
// Driver Code
int main()
{
    int arr[] = { 1,  2,  3,  4,  5,  6,  7,  8,  9,
                  10, 11, 12, 13, 14, 15, 16, 17, 18,
                  19, 20, 21, 22, 23, 24, 25, 26 };
    string str = "abcdefghijklmopqrstuvwz";
 
    cout << pangramCost(arr, str) << endl;
 
    return 0;
}


Java




// Java program to find the cost to make a string Pangram
 
import java.util.HashSet;
 
class GFG {
    // Function to return the total cost required
    // to make the string Pangram
    static int pangramCost(int arr[], String str)
    {
        int cost = 0;
        HashSet<Character> distinct
            = new HashSet<Character>();
        // Add all distinct alphabets that appeared in the
        // string
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            distinct.add(c);
        }
 
        // Iterate over all the alphabets from 'a' to 'z',
        // and add the corresponding cost for missing
        // alphabets
        for (char c = 'a'; c <= 'z'; c++) {
            if (!distinct.contains(c)) {
                cost += arr;
            }
        }
 
        return cost;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 123456789,
                      10, 11, 12, 13, 14, 15, 16, 17, 18,
                      19, 20, 21, 22, 23, 24, 25, 26 };
        String str = "abcdefghijklmopqrstuvwz";
 
        System.out.println(pangramCost(arr, str));
    }
}


Python3




# Python program to find the cost to make a string Pangram
 
def pangramCost(arr, str):
    cost = 0
    distinct = set()
 
    # Add all distinct alphabets that appeared in the string
    for c in str:
        distinct.add(c)
 
    # Iterate over all the alphabets from 'a' to 'z',
    # and add the corresponding cost for missing alphabets
    for c in 'abcdefghijklmnopqrstuvwxyz':
        if c not in distinct:
            cost += arr[ord(c) - ord('a')]
 
    return cost
 
# Driver code
if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
           16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
    str = "abcdefghijklmopqrstuvwz"
 
    print(pangramCost(arr, str))


C#




using System;
using System.Collections.Generic;
 
class GFG
{
   
    // Function to return the total cost required
    // to make the string Pangram
    static int pangramCost(int[] arr, string str)
    {
        int cost = 0;
        HashSet<char> distinct = new HashSet<char>();
       
        // Add all distinct alphabets that appeared in the
        // string
        for (int i = 0; i < str.Length; i++) {
            char c = str[i];
            distinct.Add(c);
        }
 
        // Iterate over all the alphabets from 'a' to 'z',
        // and add the corresponding cost for missing
        // alphabets
        for (char c = 'a'; c <= 'z'; c++) {
            if (!distinct.Contains(c)) {
                cost += arr;
            }
        }
 
        return cost;
    }
 
    // Driver Code
    static void Main(string[] args)
    {
        int[] arr = { 1,  2,  3,  4,  5,  6,  7,  8,  9,
                      10, 11, 12, 13, 14, 15, 16, 17, 18,
                      19, 20, 21, 22, 23, 24, 25, 26 };
        string str = "abcdefghijklmopqrstuvwz";
 
        Console.WriteLine(pangramCost(arr, str));
    }
}
 
// This code is contributed by sarojmcy2e


Javascript




// Function to return the total cost required
// to make the string Pangram
function pangramCost(arr, str) {
    let cost = 0;
    let distinct = new Set();
 
    // Add all distinct alphabets that appeared in the
    // string
    for (let i = 0; i < str.length; i++) {
        let c = str.charAt(i);
        distinct.add(c);
    }
 
    // Iterate over all the alphabets from 'a' to 'z',
    // and add the corresponding cost for missing
    // alphabets
    for (let c = 'a'; c <= 'z'; c = String.fromCharCode(c.charCodeAt(0) + 1)) {
        if (!distinct.has(c)) {
            cost += arr;
        }
    }
 
    return cost;
}
 
// Driver Code
    let arr = [
        1, 2, 3, 4, 5, 6, 7, 8, 9,
        10, 11, 12, 13, 14, 15, 16, 17, 18,
        19, 20, 21, 22, 23, 24, 25, 26
    ];
    let str = "abcdefghijklmopqrstuvwz";
 
    console.log(pangramCost(arr, str));


Output:-

63

Time Complexity: The time complexity of the given program is O(N), where N is the length of the input string. The loop to add distinct characters in HashSet takes O(N) time, and the loop to iterate over all the alphabets takes O(26) time, which is a constant value. Thus, the overall time complexity is O(N + 26), which can be simplified to O(N).

Auxiliary Space: The auxiliary space used by the given program is O(1), which is constant space. The space used by HashSet is proportional to the number of distinct characters in the string, which in this case is at most 26 (the number of alphabets in the English language). Therefore, the overall space complexity is O(26), which is constant space.



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