Check whether frequency of characters in a string makes Fibonacci Sequence

Given a string with lowercase English alphabets. The task is to check whether the frequency of the characters in the string can be arranged as a Fibonacci series. If yes, print “YES”, otherwise print “NO”.


  • Frequencies can be arranged in any way to form Fibonacci Series.
  • The Fibonacci Series starts from 1. That is the series is 1,1,2,3,5,…..


Input : str = "abeeedd"
Output : YES
Frequency of 'a' => 1
Frequency of 'b' => 1
Frequency of 'e' => 3
Frequency of 'd' => 2
These frequencies are first 4 terms of 
Fibonacci series => {1, 1, 2, 3}

Input : str = "dzzddz"
Output : NO
Frequencies are not in Fibonacci series


  • Store the frequencies of each character of the string in a map. Let the size of the map be n after storing frequencies.
  • Then, make a vector and insert first ‘n’ elements of the Fibonacci series in this vector.
  • Then, compare each element of the vector with values of the map. If both elements of vector and values of the map are same, print ‘YES’, otherwise print ‘NO’.

Below is the implementation of the above approach:





// C++ program to check whether frequency of
// characters in a string makes
// Fibonacci Sequence
#include <bits/stdc++.h>
using namespace std;
// Function to check if the frequencies
// are in Fibonacci series
string isFibonacci(string s)
    // map to store the
    // frequencies of character
    map<char, int> m;
    for (int i = 0; i < s.length(); i++) {
    // Vector to store first n
    // fibonacci numbers
    vector<int> v;
    // Get the size of the map
    int n = m.size();
    // a and b are first and second terms of
    // fibonacci series
    int a = 1, b = 1;
    int c;
    // vector v contains elements of fibonacci series
    for (int i = 0; i < n - 2; i++) {
        v.push_back(a + b);
        c = a + b;
        a = b;
        b = c;
    int flag = 1;
    int i = 0;
    // Compare vector elements with values in Map
    for (auto itr = m.begin(); itr != m.end(); itr++) {
        if (itr->second != v[i]) {
            flag = 0;
    if (flag == 1)
        return "YES";
        return "NO";
// Driver code
int main()
    string s = "abeeedd";
    cout << isFibonacci(s);
    return 0;




My Personal Notes arrow_drop_up