Open In App

Check if frequency of each character is equal to its position in English Alphabet

Improve
Improve
Like Article
Like
Save
Share
Report

Given string str of lowercase alphabets, the task is to check if the frequency of each distinct characters in the string equals to its position in the English Alphabet. If valid, then print “Yes”, else print “No”.

Examples: 

Input: str = “abbcccdddd” 
Output: Yes 
Explanation: 
Since frequency of each distinct character is equals to its position in English Alphabet, i.e. 
F(a) = 1, 
F(b) = 2, 
F(c) = 3, and 
F(d) = 4 
Hence the output is Yes.

Input: str = “geeksforgeeks” 
Output: No 

Approach: 

  1. Store the frequency of each character in an array of 26, for hashing purpose.
  2. Now traverse the hash array and check if the frequency of each character at an index i is equal to (i + 1) or not.
  3. If yes, then print “Yes”, Else print “No”.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
 
#include "bits/stdc++.h"
using namespace std;
 
bool checkValidString(string str)
{
 
    // Initialise frequency array
    int freq[26] = { 0 };
 
    // Traverse the string
    for (int i = 0; str[i]; i++) {
 
        // Update the frequency
        freq[str[i] - 'a']++;
    }
 
    // Check for valid string
    for (int i = 0; i < 26; i++) {
 
        // If frequency is non-zero
        if (freq[i] != 0) {
 
            // If freq is not equals
            // to (i+1), then return
            // false
            if (freq[i] != i + 1) {
                return false;
            }
        }
    }
 
    // Return true;
    return true;
}
 
// Driver Code
int main()
{
 
    // Given string str
    string str = "abbcccdddd";
 
    if (checkValidString(str))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Java




// Java program for the above approach
class GFG{
 
static boolean checkValidString(String str)
{
     
    // Initialise frequency array
    int freq[] = new int[26];
 
    // Traverse the String
    for(int i = 0; i < str.length(); i++)
    {
        
       // Update the frequency
       freq[str.charAt(i) - 'a']++;
    }
 
    // Check for valid String
    for(int i = 0; i < 26; i++)
    {
        
       // If frequency is non-zero
       if (freq[i] != 0)
       {
            
           // If freq is not equals
           // to (i+1), then return
           // false
           if (freq[i] != i + 1)
           {
               return false;
           }
       }
    }
     
    // Return true;
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
 
    // Given String str
    String str = "abbcccdddd";
 
    if (checkValidString(str))
    {
        System.out.print("Yes");
    }
    else
    {
        System.out.print("No");
    }
}
}
 
// This code is contributed by sapnasingh4991


Python3




# Python3 program for the
# above approach
def checkValidString(str):
 
    # Initialise frequency array
    freq = [0 for i in range(26)]
 
    # Traverse the string
    for i in range(len(str)):
 
        # Update the frequency
        freq[ord(str[i]) - ord('a')] += 1
 
    # Check for valid string
    for i in range(26):
 
        # If frequency is non-zero
        if(freq[i] != 0):
 
            # If freq is not equals
            # to (i+1), then return
            # false
            if(freq[i] != i + 1):
                return False
    # Return true
    return True
 
# Driver Code
 
# Given string str
str = "abbcccdddd"
 
if(checkValidString(str)):
    print("Yes")
else:
    print("No")
 
# This code is contributed by avanitrachhadiya2155


C#




// C# program for the above approach
using System;
class GFG{
 
static bool checkValidString(String str)
{
     
    // Initialise frequency array
    int []freq = new int[26];
 
    // Traverse the String
    for(int i = 0; i < str.Length; i++)
    {
         
        // Update the frequency
        freq[str[i] - 'a']++;
    }
 
    // Check for valid String
    for(int i = 0; i < 26; i++)
    {
         
        // If frequency is non-zero
        if (freq[i] != 0)
        {
                 
            // If freq is not equals
            // to (i+1), then return
            // false
            if (freq[i] != i + 1)
            {
                return false;
            }
        }
    }
     
    // Return true;
    return true;
}
 
// Driver Code
public static void Main(String[] args)
{
 
    // Given String str
    String str = "abbcccdddd";
 
    if (checkValidString(str))
    {
        Console.Write("Yes");
    }
    else
    {
        Console.Write("No");
    }
}
}
 
// This code is contributed by sapnasingh4991


Javascript




<script>
 
// Javascript program for the above approach
function checkValidString(str)
{
     
    // Initialise frequency array
    var freq = new Array(26).fill(0);
     
    // Traverse the String
    for(var i = 0; i < str.length; i++)
    {
         
        // Update the frequency
        freq[str[i].charCodeAt(0) -
                "a".charCodeAt(0)]++;
    }
     
    // Check for valid String
    for(var i = 0; i < 26; i++)
    {
         
        // If frequency is non-zero
        if (freq[i] !== 0)
        {
             
            // If freq is not equals
            // to (i+1), then return
            // false
            if (freq[i] !== i + 1)
            {
                return false;
            }
        }
    }
     
    // Return true;
    return true;
}
 
// Driver Code
 
// Given String str
var str = "abbcccdddd";
 
if (checkValidString(str))
{
    document.write("Yes");
}
else
{
    document.write("No");
}
 
// This code is contributed by rdtank
 
</script>


Output

Yes







Time Complexity: O(N), where N is the length of the string. 
Auxiliary Space: O(26)

Method: Using Map

Algorithm :

  • Create a HashMap map with character and integer as key and value pairs respectively.
  • Loop through each character of the string str and count the frequency.
  • Loop through each character in the string str again and check if its frequency is equal to its position in the English alphabet.
  • If any character fails to satisfy the condition, set the boolean variable isEqual to false and break out of the loop.
  • Print the result based on the value of isEqual.

C++




#include <iostream>
#include <unordered_map>
using namespace std;
 
bool check(string str) {
    unordered_map<char, int> map;
 
    // Count frequency of each character in the string
    for (char c : str) {
        if (map.find(c) != map.end()) {
            map++;
        } else {
            map = 1;
        }
    }
 
    // Check if frequency of each character is equal to its position in English alphabet
    bool isEqual = true;
    for (char c : str) {
        int frequency = map;
        int position = c - 'a' + 1;
        if (frequency != position) {
            isEqual = false;
            break;
        }
    }
 
    return isEqual;
}
 
int main() {
    string str = "abbcccdddd";
    bool ans = check(str);
 
    if (ans) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
 
    return 0;
}
 
//This code is contributed by aeroabrar_31


Java




import java.util.*;
 
public class Main {
 
    public static void main(String[] args)
    {
        String str = "abbcccdddd";
        boolean ans = check(str);
 
        if (ans) {
            System.out.println("Yes");
        }
        else {
            System.out.println("No");
        }
    }
 
    public static boolean check(String str)
    {
 
        Map<Character, Integer> map = new HashMap<>();
 
        // Count frequency of each character in the string
        for (char c : str.toCharArray()) {
            if (map.containsKey(c)) {
                map.put(c, map.get(c) + 1);
            }
            else {
                map.put(c, 1);
            }
        }
 
        // Check if frequency of each character is equal to
        // its position in English alphabet
        boolean isEqual = true;
        for (char c : str.toCharArray())
        {
            int frequency = map.get(c);
            int position = c - 'a' + 1;
            if (frequency != position)
            {
                isEqual = false;
                break;
            }
        }
 
        return isEqual;
    }
}
//This code is contributed by aeroabrar_31


Python3




def check(s):
    char_count = {}  # Use a dictionary to store character frequencies
 
    # Count the frequency of each character in the string
    for char in s:
        if char in char_count:
            char_count[char] += 1
        else:
            char_count[char] = 1
 
    # Check if the frequency of each character is equal to its position in the English alphabet
    is_equal = True
    for char in s:
        frequency = char_count[char]
        position = ord(char) - ord('a') + 1
        if frequency != position:
            is_equal = False
            break
 
    return is_equal
 
if __name__ == "__main__":
    input_str = "abbcccdddd"
    result = check(input_str)
 
    if result:
        print("Yes")
    else:
        print("No")
 
#This code is contributed by aeroabrar_31


C#




using System;
using System.Collections.Generic;
 
public class GFG
{
    public static void Main(string[] args)
    {
        string str = "abbcccdddd";
        bool ans = Check(str);
 
        if (ans)
        {
            Console.WriteLine("Yes");
        }
        else
        {
            Console.WriteLine("No");
        }
    }
 
    public static bool Check(string str)
    {
        Dictionary<char, int> map = new Dictionary<char, int>();
 
        // Count frequency of each character in the string
        foreach (char c in str)
        {
            if (map.ContainsKey(c))
            {
                map++;
            }
            else
            {
                map = 1;
            }
        }
 
        // Check if frequency of each character is equal to
        // its position in English alphabet
        bool isEqual = true;
        foreach (char c in str)
        {
            int frequency = map;
            int position = c - 'a' + 1;
            if (frequency != position)
            {
                isEqual = false;
                break;
            }
        }
 
        return isEqual;
    }
}
 
//This code is contributed by aeroabrar_31


Javascript




function check(str) {
    const map = new Map();
 
    // Count frequency of each character in the string
    for (const c of str) {
        if (map.has(c)) {
            map.set(c, map.get(c) + 1);
        } else {
            map.set(c, 1);
        }
    }
 
    // Check if frequency of each character is equal to its position in English alphabet
    let isEqual = true;
    for (const c of str) {
        const frequency = map.get(c);
        const position = c.charCodeAt(0) - 'a'.charCodeAt(0) + 1;
        if (frequency !== position) {
            isEqual = false;
            break;
        }
    }
 
    return isEqual;
}
 
const str = "abbcccdddd";
const ans = check(str);
 
if (ans) {
    console.log("Yes");
} else {
    console.log("No");
}


Output

Yes








Time Complexity: O(N), where N is the length of the string. 
Auxiliary Space: O(1)

Note: The size of the map never exceeds 26 here as the lower case English alphabets are only 26, so the Auxiliary space is 1 (constant).



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