Skip to content
Related Articles

Related Articles

Improve Article

Palindromic strings of length 3 possible by using characters of a given string

  • Last Updated : 03 Aug, 2021

Given a string S consisting of N characters, the task is to print all palindromic strings of length 3 in lexicographical order that can be formed using characters of the given string S.

Examples:

Input: S = “aabc”
Output:
aba
aca

Input: S = “ddadbac”
Output:
aba
aca
ada
dad
dbd
dcd
ddd

Approach: The given problem can be solved by using the concept of Hashing, by implementing it using a Map to store count of characters. Follow the steps below to solve the problem:



Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print all palindromic
// strings of length 3 that can be
// formed using characters of string S
void generatePalindrome(string S)
{
    // Stores the count of character
    unordered_map<char, int> Hash;
 
    // Traverse the string S
    for (auto ch : S) {
        Hash[ch]++;
    }
 
    // Stores all palindromic strings
    set<string> st;
 
    // Iterate over the charchaters
    // over the range ['a', 'z']
    for (char i = 'a'; i <= 'z'; i++) {
 
        // If Hash[ch] is equal to 2
        if (Hash[i] == 2) {
 
            // Iterate over the characters
            // over the range ['a', 'z']
            for (char j = 'a'; j <= 'z'; j++) {
 
                // Stores all the
                // palindromic string
                string s = "";
                if (Hash[j] && i != j) {
 
                    s += i;
                    s += j;
                    s += i;
 
                    // Push the s into
                    // the set st
                    st.insert(s);
                }
            }
        }
 
        // If Hash[i] is greater than
        // or equal to 3
        if (Hash[i] >= 3) {
 
            // Iterate over charchaters
            // over the range ['a', 'z']
            for (char j = 'a';
                 j <= 'z'; j++) {
 
                // Stores all the
                // palindromic string
                string s = "";
 
                // If Hash[j] is positive
                if (Hash[j]) {
                    s += i;
                    s += j;
                    s += i;
 
                    // Push s into
                    // the set st
                    st.insert(s);
                }
            }
        }
    }
 
    // Iterate over the set
    for (auto ans : st) {
        cout << ans << "\n";
    }
}
 
// Driver Code
int main()
{
    string S = "ddabdac";
    generatePalindrome(S);
 
    return 0;
}

Python3




# Python3 program for the above approach
 
# Function to print all palindromic
# strings of length 3 that can be
# formed using characters of string S
def generatePalindrome(S):
     
    # Stores the count of character
    Hash = {}
 
    # Traverse the string S
    for ch in S:
        Hash[ch] = Hash.get(ch,0) + 1
 
    # Stores all palindromic strings
    st = {}
 
    # Iterate over the charchaters
    # over the range ['a', 'z']
    for i in range(ord('a'), ord('z') + 1):
 
        # If Hash[ch] is equal to 2
        if (chr(i) in Hash and Hash[chr(i)] == 2):
             
            # Iterate over the characters
            # over the range ['a', 'z']
            for j in range(ord('a'), ord('z') + 1):
                 
                # Stores all the
                # palindromic string
                s = ""
                 
                if (chr(j) in Hash and i != j):
                    s += chr(i)
                    s += chr(j)
                    s += chr(i)
 
                    # Push the s into
                    # the set st
                    st[s] = 1
 
        # If Hash[i] is greater than
        # or equal to 3
        if ((chr(i) in Hash) and Hash[chr(i)] >= 3):
             
            # Iterate over charchaters
            # over the range ['a', 'z']
            for j in range(ord('a'), ord('z') + 1):
 
                # Stores all the
                # palindromic string
                s = ""
 
                # If Hash[j] is positive
                if (chr(j) in Hash):
                    s += chr(i)
                    s += chr(j)
                    s += chr(i)
 
                    # Push s into
                    # the set st
                    st[s] = 1
 
    # Iterate over the set
    for ans in st:
        print(ans)
 
# Driver Code
if __name__ == '__main__':
     
    S = "ddabdac"
     
    generatePalindrome(S)
 
# This code is contributed by mohit kumar 29

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
  
// Function to print all palindromic
// strings of length 3 that can be
// formed using characters of string S
static void generatePalindrome(string S)
{
     
    // Stores the count of character
    Dictionary<char,
               int> Hash = new Dictionary<char,
                                          int>();
 
    // Traverse the string S
    foreach (char ch in S)
    {
        if (Hash.ContainsKey(ch))
            Hash[ch]++;
        else
            Hash.Add(ch, 1);
    }
 
    // Stores all palindromic strings
    HashSet<string> st = new HashSet<string>();
 
    // Iterate over the charchaters
    // over the range ['a', 'z']
    for(char i = 'a'; i <= 'z'; i++)
    {
         
        // If Hash[ch] is equal to 2
        if (Hash.ContainsKey(i) && Hash[i] == 2)
        {
             
            // Iterate over the characters
            // over the range ['a', 'z']
            for(char j = 'a'; j <= 'z'; j++)
            {
                 
                // Stores all the
                // palindromic string
                string s = "";
                 
                if (Hash.ContainsKey(j) && i != j)
                {
                    s += i;
                    s += j;
                    s += i;
 
                    // Push the s into
                    // the set st
                    st.Add(s);
                }
            }
        }
 
        // If Hash[i] is greater than
        // or equal to 3
        if (Hash.ContainsKey(i) && Hash[i] >= 3)
        {
             
            // Iterate over charchaters
            // over the range ['a', 'z']
            for(char j = 'a'; j <= 'z'; j++)
            {
                 
                // Stores all the
                // palindromic string
                string s = "";
 
                // If Hash[j] is positive
                if (Hash.ContainsKey(j))
                {
                    s += i;
                    s += j;
                    s += i;
 
                    // Push s into
                    // the set st
                    st.Add(s);
                }
            }
        }
    }
 
    // Iterate over the set
    foreach(string ans in st)
    {
        Console.WriteLine(ans);
    }
}
 
// Driver Code
public static void Main()
{
    string S = "ddabdac";
     
    generatePalindrome(S);
}
}
 
// This code is contributed by SURENDRA_GANGWAR

Javascript




<script>
// Javascript program for the above approach
 
// Function to print all palindromic
// strings of length 3 that can be
// formed using characters of string S
function generatePalindrome(S)
{
    // Stores the count of character
    let Hash=new Map();
  
    // Traverse the string S
    for (let ch=0;ch< S.length;ch++) {
        if(!Hash.has(S[ch]))
            Hash.set(S[ch],1);
        else
        {
            Hash.set(S[ch],Hash.get(S[ch])+1)
        }
         
    }
  
    // Stores all palindromic strings
    let st=new Set();
  
    // Iterate over the charchaters
    // over the range ['a', 'z']
    for (let i = 'a'.charCodeAt(0); i <= 'z'.charCodeAt(0); i++) {
  
        // If Hash[ch] is equal to 2
        if (Hash.get(String.fromCharCode(i)) == 2) {
  
            // Iterate over the characters
            // over the range ['a', 'z']
            for (let j = 'a'.charCodeAt(0); j <= 'z'.charCodeAt(0); j++) {
  
                // Stores all the
                // palindromic string
                let s = "";
                if (Hash.get(String.fromCharCode(j)) && i != j) {
  
                    s += String.fromCharCode(i);
                    s += String.fromCharCode(j);
                    s += String.fromCharCode(i);
  
                    // Push the s into
                    // the set st
                    st.add(s);
                }
            }
        }
  
        // If Hash[i] is greater than
        // or equal to 3
        if (Hash.get(String.fromCharCode(i)) >= 3) {
  
            // Iterate over charchaters
            // over the range ['a', 'z']
            for (let j = 'a'.charCodeAt(0);
                 j <= 'z'.charCodeAt(0); j++) {
  
                // Stores all the
                // palindromic string
                let s = "";
  
                // If Hash[j] is positive
                if (Hash.get(String.fromCharCode(j))) {
                    s += String.fromCharCode(i);
                    s += String.fromCharCode(j);
                    s += String.fromCharCode(i);
  
                    // Push s into
                    // the set st
                    st.add(s);
                }
            }
        }
    }
  
    // Iterate over the set
    for (let item of st.values()) {
        document.write(item+"<br>")
    }
}
 
// Driver Code
let S = "ddabdac";
generatePalindrome(S);
 
// This code is contributed by unknown2108
</script>
Output: 
aba
aca
ada
dad
dbd
dcd
ddd

 

Time Complexity: O(26*26)
Auxiliary Space: O(26)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :