Open In App

Palindromic concatenation of two integers

Last Updated : 21 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two positive integers, check if it is possible to rearrange the digits of each integer, such that after rearranging, the concatenation of two integers form a palindromic integer.

Note: For example, given two integers 1223 and 5412235. You can rearrange the digits of the first string as 3221 and rearrange the characters of the second string as 5451223. And now the concatenation of these two integers forms a new string 32215451223, which is a palindromic integer.

Examples:

Input: 123 324
Output: NO

Input: 12344 12
Output: YES
Explanation: First Number can be changed to 12434 and the second number can be changed to 21, thus after concatenating the number becomes 1243421.                    

Input: 1 112
Output: NO 

Approach: The above problem can be solved using the following approach along with some observations.

An integer number can be a palindrome if there is at most one digit with an odd frequency and all other digits with an even frequency.

Steps were to follow the approach:

  • First take an unordered map, which is used to check the frequency.
  • Run two while loops to check the digits of integers.
  • Then take the incremental frequency of a greater integer and the decremental frequency of a smaller integer. (In greater integer, you traverse the map this way– map[digits_of_greater_integer]++ and in smaller integer traverse the map this way– map[digits_of_smaller_integer]–)
  • If there is a negative frequency then there is a digit in a smaller integer with more frequency than a greater integer. So, we can’t form a palindrome after concatenating two integers.
  • If there is more than one digit with an odd frequency then we also can’t form a palindrome after concatenating two digits.
  • If there is no negative frequency and also at most one odd frequency then it can form a palindrome after concatenating two integers.

Below is the implementation of the above approach:

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check the concatenated
// number is palindrome or not.
bool checkConcatPal(int first, int second)
{
 
    // Taking unordered_map to
    // count frequency
    unordered_map<int, int> mp;
 
    // If first is greater than second
    // increment the frequency of digits
    // in first decrement the frequency
    // of digits in second
    if (first > second) {
 
        // By this while loop we take all
        // the digits of the integer first
        // and count the frequency of
        // digits in an incremental way.
        while (first != 0) {
            int temp = first % 10;
            mp[temp]++;
            first = first / 10;
        }
 
        // By this while loop we take all
        // the digits of the integer
        // second and count the frequency
        // of digits in an decremental way
        while (second != 0) {
            int temp = second % 10;
            mp[temp]--;
            second = second / 10;
        }
    }
 
    // if second is greater than first
    // increment the frequency of digits
    // of seconddecrement the frequency
    // of digits of first
    else {
        while (second != 0) {
            int temp = second % 10;
            mp[temp]++;
            second = second / 10;
        }
        while (first != 0) {
            int temp = first % 10;
            mp[temp]--;
            first = first / 10;
        }
    }
 
    // Check is a boolean variable to
    // check is it possible or not
    // oddCount is a variable to check is
    // there is a odd frequency
    // of chracters
    bool check = true;
    int oddCount = 0;
 
    for (auto it = mp.begin(); it != mp.end(); it++) {
 
        // First check if any frequency
        // is in negative value, if yes
        // then the digit's frequency is
        // not same in two integer so
        // it is not a palindrome.
        if (it->second < 0) {
            check = false;
            break;
        }
        if (it->second % 2 == 0) {
            continue;
        }
        else {
 
            // if there is more than one
            // digit which has a odd
            // frequency in greater integer,
            // then it does not form
            // a palindrome
            if (oddCount == 1) {
                check = false;
            }
            else {
                oddCount = 1;
            }
        }
    }
    return check;
}
 
// Driver's code
int main()
{
 
    // Given two integers.
    int first = 1223;
    int second = 41223;
 
    // Check concat palindrome.
    bool ans = checkConcatPal(first, second);
 
    if (ans) {
        cout << "YES" << endl;
    }
    else {
        cout << "NO" << endl;
    }
 
    return 0;
}


Java




// Java code for the above approach
import java.util.*;
class GFG {
 
    // Function to check the concatenated
    // number is palindrome or not.
    static boolean checkConcatPal(int first, int second)
    {
 
        // Taking HashMap to
        // count frequency
        HashMap<Integer, Integer> mp
            = new HashMap<Integer, Integer>();
 
        // If first is greater than second
        // increment the frequency of digits
        // in first decrement the frequency
        // of digits in second
        if (first > second) {
 
            // By this while loop we take all
            // the digits of the integer first
            // and count the frequency of
            // digits in an incremental way.
            while (first != 0) {
                int temp = first % 10;
                if (mp.containsKey(temp)) {
                    mp.put(temp, mp.get(temp) + 1);
                }
                else {
                    mp.put(temp, 1);
                }
                first = first / 10;
            }
 
            // By this while loop we take all
            // the digits of the integer
            // second and count the frequency
            // of digits in an decremental way
            while (second != 0) {
                int temp = second % 10;
                if (mp.containsKey(temp)) {
                    mp.put(temp, mp.get(temp) - 1);
                }
                else {
                    mp.put(temp, -1);
                }
                second = second / 10;
            }
        }
 
        // if second is greater than first
        // increment the frequency of digits
        // of seconddecrement the frequency
        // of digits of first
        else {
            while (second != 0) {
                int temp = second % 10;
                if (mp.containsKey(temp)) {
                    mp.put(temp, mp.get(temp) + 1);
                }
                else {
                    mp.put(temp, 1);
                }
                second = second / 10;
            }
            while (first != 0) {
                int temp = first % 10;
                if (mp.containsKey(temp)) {
                    mp.put(temp, mp.get(temp) - 1);
                }
                else {
                    mp.put(temp, -1);
                }
                first = first / 10;
            }
        }
 
        // Check is a boolean variable to
        // check is it possible or not
        // oddCount is a variable to check is
        // there is a odd frequency
        // of characters
        boolean check = true;
        int oddCount = 0;
 
        for (Map.Entry<Integer, Integer> entry :
             mp.entrySet()) {
 
            // First check if any frequency
            // is in negative value, if yes
            // then the digit's frequency is
            // not same in two integer so
            // it is not a palindrome.
            if (entry.getValue() < 0) {
                check = false;
                break;
            }
            if (entry.getValue() % 2 == 0) {
                continue;
            }
            else {
 
                // if there is more than one
                // digit which has a odd
                // frequency in greater integer,
                // then it does not form
                // a palindrome
                if (oddCount == 1) {
                    check = false;
                }
                else {
                    oddCount = 1;
                }
            }
        }
        return check;
    }
 
    // Driver's code
    public static void main(String[] args)
    {
 
        // Given two integers.
        int first = 1223;
        int second = 41223;
 
        // Check concat palindrome.
        boolean ans = checkConcatPal(first, second);
 
        if (ans) {
            System.out.println("YES");
        }
        else {
            System.out.println("NO");
        }
    }
}
 
// This code is contributed by prasad264


Python3




# Python code for the above approach
 
# Function to check the concatenated number is
# palindrome or not.
def checkConcatPal(first, second):
 
    # Taking dictionary to count frequency
    mp = {}
 
    # If first is greater than second increment the
    # frequency of digits in first decrement the frequency
    # of digits in second
    if first > second:
        # By this while loop we take all the digits of the
        # integer first and count the frequency of digits
        # in an incremental way.
        while first != 0:
            temp = first % 10
            if temp in mp:
                mp[temp] += 1
            else:
                mp[temp] = 1
            first = first // 10
 
        # By this while loop we take all the digits of
        # the integer second and count the frequency of
        # digits in an decremental way
        while second != 0:
            temp = second % 10
            if temp in mp:
                mp[temp] -= 1
            else:
                mp[temp] = -1
            second = second // 10
 
    # if second is greater than first increment the
    # frequency of digits of second decrement the
    # frequency of digits of first
    else:
        while second != 0:
            temp = second % 10
            if temp in mp:
                mp[temp] += 1
            else:
                mp[temp] = 1
            second = second // 10
        while first != 0:
            temp = first % 10
            if temp in mp:
                mp[temp] -= 1
            else:
                mp[temp] = -1
            first = first // 10
 
    # Check is a boolean variable to check is it
    # possible or not oddCount is a variable to
    # check is there is a odd frequency of characters
    check = True
    oddCount = 0
 
    for key, value in mp.items():
 
        # First check if any frequency is in negative
        # value, if yes then the digit's frequency is
        # not same in two integer so it is not a palindrome.
        if value < 0:
            check = False
            break
        if value % 2 == 0:
            continue
        else:
            # if there is more than one digit which has a
            # odd frequency in greater integer, then it does
            # not form a palindrome
            if oddCount == 1:
                check = False
            else:
                oddCount = 1
    return check
 
 
# Given two integers.
first = 1223
second = 41223
 
# Check concat palindrome.
ans = checkConcatPal(first, second)
 
if ans:
    print("YES")
else:
    print("NO")
 
# This code is contributed by lokesh.


C#




// C# code for the above approach
using System;
using System.Collections.Generic;
 
public class GFG {
 
  // Function to check the concatenated number is
  // palindrome or not.
  static bool checkConcatPal(int first, int second)
  {
    // Taking Dictionary to count frequency
    Dictionary<int, int> mp
      = new Dictionary<int, int>();
 
    // If first is greater than second increment the
    // frequency of digits in first decrement the
    // frequency of digits in second
    if (first > second) {
      // By this while loop we take all the digits of
      // the integer first and count the frequency of
      // digits in an incremental way.
      while (first != 0) {
        int temp = first % 10;
        if (mp.ContainsKey(temp)) {
          mp[temp]++;
        }
        else {
          mp[temp] = 1;
        }
        first = first / 10;
      }
 
      // By this while loop we take all the digits of
      // the integer second and count the frequency of
      // digits in an decremental way
      while (second != 0) {
        int temp = second % 10;
        if (mp.ContainsKey(temp)) {
          mp[temp]--;
        }
        else {
          mp[temp] = -1;
        }
        second = second / 10;
      }
    }
 
    // if second is greater than first increment the
    // frequency of digits of seconddecrement the
    // frequency of digits of first
    else {
      while (second != 0) {
        int temp = second % 10;
        if (mp.ContainsKey(temp)) {
          mp[temp]++;
        }
        else {
          mp[temp] = 1;
        }
        second = second / 10;
      }
      while (first != 0) {
        int temp = first % 10;
        if (mp.ContainsKey(temp)) {
          mp[temp]--;
        }
        else {
          mp[temp] = -1;
        }
        first = first / 10;
      }
    }
 
    // Check is a boolean variable to check is it
    // possible or not oddCount is a variable to check
    // is there is a odd frequency of characters
    bool check = true;
    int oddCount = 0;
 
    foreach(KeyValuePair<int, int> entry in mp)
    {
      // First check if any frequency is in negative
      // value, if yes then the digit's frequency is
      // not same in two integer so it is not a
      // palindrome.
      if (entry.Value < 0) {
        check = false;
        break;
      }
      if (entry.Value % 2 == 0) {
        continue;
      }
      else {
        // if there is more than one digit which has
        // a odd frequency in greater integer, then
        // it does not form a palindrome
        if (oddCount == 1) {
          check = false;
        }
        else {
          oddCount = 1;
        }
      }
    }
 
    return check;
  }
 
  static public void Main()
  {
 
    // Code
    // Given two integers.
    int first = 1223;
    int second = 41223;
 
    // Check concat palindrome.
    bool ans = checkConcatPal(first, second);
 
    if (ans) {
      Console.WriteLine("YES");
    }
    else {
      Console.WriteLine("NO");
    }
  }
}
 
// This code is contributed by karthik.


Javascript




<script>
 
// JavaScript code for the above approach
 
// Function to check the concatenated number is palindrome or not.
function checkConcatPal(first, second) {
 
    // Taking Map to count frequency
    let mp = new Map();
 
    // If first is greater than second increment the frequency
    // of digits in first decrement the frequency of digits in
    // second
    if (first > second) {
        // By this while loop we take all the digits of the
        // integer firstand count the frequency of digits in
        // an incremental way.
        while (first != 0) {
            let temp = first % 10;
            if (mp.has(temp)) {
                mp.set(temp, mp.get(temp) + 1);
            } else {
                mp.set(temp, 1);
            }
            first = Math.floor(first / 10);
        }
 
        // By this while loop we take all the digits of the
        // integer second and count the frequency of digits
        // in an decremental way
        while (second != 0) {
            let temp = second % 10;
            if (mp.has(temp)) {
                mp.set(temp, mp.get(temp) - 1);
            } else {
                mp.set(temp, -1);
            }
            second = Math.floor(second / 10);
        }
    }
 
    // if second is greater than first increment the
    // frequency of digits of second decrement the
    // frequency of digits of first
    else {
        while (second != 0) {
            let temp = second % 10;
            if (mp.has(temp)) {
                mp.set(temp, mp.get(temp) + 1);
            } else {
                mp.set(temp, 1);
            }
            second = Math.floor(second / 10);
        }
        while (first != 0) {
            let temp = first % 10;
            if (mp.has(temp)) {
                mp.set(temp, mp.get(temp) - 1);
            } else {
                mp.set(temp, -1);
            }
            first = Math.floor(first / 10);
        }
    }
 
    // Check is a boolean variable to check is it possible
    // or not oddCount is a variable to check is there is a
    // odd frequency of characters
    let check = true;
    let oddCount = 0;
 
    for (let [key, value] of mp) {
        // First check if any frequency is in negative value,
        // if yes then the digit's frequency is not same in
        // two integer so it is not a palindrome.
        if (value < 0) {
            check = false;
            break;
        }
        if (value % 2 == 0) {
            continue;
        }
        else {
            // if there is more than one digit which has a odd
            // frequency in greater integer, then it does not
            // form a palindrome
            if (oddCount == 1) {
                check = false;
            } else {
                oddCount = 1;
            }
        }
    }
    return check;
}
 
// Given two integers:
let first = 1223;
let second = 41223;
 
// Check concat palindrome.
let ans = checkConcatPal(first, second);
 
if (ans) {
    document.write("YES");
}
else {
    document.write("NO");
}
 
// This code is contributed by karthik.
 
</script>


Output

YES










Time Complexity: O(N+M), where N is the length of the first integer and M is the length of the second integer
Auxiliary Space: O(1) As the Maximum size of HashMap can go up to 10 size as Hashmap storing unit digits so irrespect of the length of the number. It will use constant space

Approach 2: Checking if the combined frequency of characters can form a palindrome

Step-by-step Explanation:

  1. Count the frequency of characters in both strings using an unordered_map.
  2. Check if the combined frequency of characters can form a palindrome.
  3. If there is at most one character with an odd frequency, return true. Otherwise, return false.

C++




#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
 
bool checkConcatPal(string str1, string str2) {
    unordered_map<char, int> freq;
    for (char c : str1) {
        freq++;
    }
    for (char c : str2) {
        freq++;
    }
    int oddCount = 0;
    for (auto it = freq.begin(); it != freq.end(); it++) {
        if (it->second % 2 != 0) {
            oddCount++;
        }
    }
    return oddCount <= 1;
}
 
int main() {
    string str1 = "1223";
    string str2 = "41223";
    bool ans = checkConcatPal(str1, str2);
    if (ans) {
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
    }
    return 0;
}


Java




import java.util.HashMap;
import java.util.Map;
 
class GFG {
    public static boolean checkConcatPal(String str1,
                                         String str2)
    {
        Map<Character, Integer> freq = new HashMap<>();
        for (char c : str1.toCharArray()) {
            freq.put(c, freq.getOrDefault(c, 0) + 1);
        }
        for (char c : str2.toCharArray()) {
            freq.put(c, freq.getOrDefault(c, 0) + 1);
        }
        int oddCount = 0;
        for (Map.Entry<Character, Integer> entry :
             freq.entrySet()) {
            if (entry.getValue() % 2 != 0) {
                oddCount++;
            }
        }
        return oddCount <= 1;
    }
 
    public static void main(String[] args)
    {
        String str1 = "1223";
        String str2 = "41223";
        boolean ans = checkConcatPal(str1, str2);
        if (ans) {
            System.out.println("YES");
        }
        else {
            System.out.println("NO");
        }
    }
}


Python3




def check_concat_pal(str1, str2):
    freq = {}
    for c in str1:
        freq = freq.get(c, 0) + 1
    for c in str2:
        freq = freq.get(c, 0) + 1
    odd_count = 0
    for key, value in freq.items():
        if value % 2 != 0:
            odd_count += 1
    return odd_count <= 1
 
def main():
    str1 = "1223"
    str2 = "41223"
    ans = check_concat_pal(str1, str2)
    if ans:
        print("YES")
    else:
        print("NO")
 
if __name__ == "__main__":
    main()
 
#Contributed by Aditi Tyagi


C#




using System;
using System.Collections.Generic;
 
public class GFG {
    static bool CheckConcatPal(string str1, string str2)
    {
        Dictionary<char, int> freq
            = new Dictionary<char, int>();
 
        foreach(char c in str1)
        {
            if (freq.ContainsKey(c))
                freq++;
            else
                freq = 1;
        }
 
        foreach(char c in str2)
        {
            if (freq.ContainsKey(c))
                freq++;
            else
                freq = 1;
        }
 
        int oddCount = 0;
        foreach(var kvp in freq)
        {
            if (kvp.Value % 2 != 0)
                oddCount++;
        }
 
        return oddCount <= 1;
    }
 
    static public void Main()
    {
        string str1 = "1223";
        string str2 = "41223";
        bool ans = CheckConcatPal(str1, str2);
        if (ans)
            Console.WriteLine("YES");
        else
            Console.WriteLine("NO");
    }
}


Javascript




// Function to check if a palindrome can
// be formed by concatenating two strings
function checkConcatPal(str1, str2) {
     
    // Create an object to store the
    // frequency of each character
    let freq = {};
 
    // Count the frequency of characters in str1
    for (let char of str1) {
        if (freq[char]) {
            freq[char]++;
        } else {
            freq[char] = 1;
        }
    }
 
    // Count the frequency of characters in str2
    for (let char of str2) {
        if (freq[char]) {
            freq[char]++;
        } else {
            freq[char] = 1;
        }
    }
 
    let oddCount = 0;
 
    // Iterate through the frequency object
    for (let char in freq) {
        if (freq[char] % 2 !== 0) {
            oddCount++;
        }
    }
 
    // Check if it's possible to form a palindrome
    return oddCount <= 1;
}
 
let str1 = "1223";
let str2 = "41223";
 
let ans = checkConcatPal(str1, str2);
 
if (ans) {
    console.log("YES");
} else {
    console.log("NO");
}


Output

YES










Time Complexity: O(n), where n is the length of the concatenated string.
Auxiliary Space: O(1), as the unordered_map can have at most 26 entries for lowercase English alphabets.

Explanation: The time complexity is O(n) because we need to iterate over all characters in both strings to count their frequency. The space complexity is O(1) because the unordered_map can have at most 26 entries for lowercase English alphabets.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads