Open In App

Minimize number of unique characters in string

Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings A and B. Minimize the number of unique characters in string A by either swapping A[i] with B[i] or keeping it unchanged. The number of swaps can be greater than or equal to 0. Note that A[i] can be swapped only with same index element in B. Print the minimum number of unique characters. Constraints: 0 < length of A ≤ 15. 

Examples:

Input : A = ababa
        B = babab
Output : 1
Swapping all b's in string A, with
a's in string B results in string
A having all characters as a. 

Input : A = abaaa
        B = bbabb
Output : 2
Initially string A has 2 unique
characters. Swapping at any index 
does not change this count.

Approach: The problem can be solved using backtracking. Create a map in which key is A[i] and value is count of corresponding character. The size of the map tells the number of distinct characters as only those elements which are present in string A are present as key in map. At every index position, there are two choices: either swap A[i] with B[i] or keep A[i] unchanged. Start from index 0 and do following for each index:

  1. Keep A[i] unchanged, increment count of A[i] by one in map and call recursively for next index.
  2. Backtrack by decreasing count of A[i] by one, swap A[i] with B[i], increment count of A[i] by one in map and again recursively call for next index.

Keep a variable ans to store overall minimum value of distinct characters. In both the cases mentioned above, when entire string is traversed compare current number of distinct characters with overall minimum in ans and update ans accordingly. 

Implementation: 

C++




// CPP program to minimize number of
// unique characters in a string.
 
#include <bits/stdc++.h>
using namespace std;
 
// Utility function to find minimum
// number of unique characters in string.
void minCountUtil(string A, string B,
                unordered_map<char, int>& ele,
                int& ans, int ind)
{
 
    // If entire string is traversed, then
    // compare current number of distinct
    // characters in A with overall minimum.
    if (ind == A.length()) {
        ans = min(ans, (int)ele.size());
        return;
    }
 
    // swap A[i] with B[i], increase count of
    // corresponding character in map and call
    // recursively for next index.
    swap(A[ind], B[ind]);
    ele[A[ind]]++;
    minCountUtil(A, B, ele, ans, ind + 1);
 
    // Backtrack (Undo the changes done)
    ele[A[ind]]--;
 
    // If count of character is reduced to zero,
    // then that character is not present in A.
    // So remove that character from map.
    if (ele[A[ind]] == 0)
        ele.erase(A[ind]);
     
 
    // Restore A to original form.
    // (Backtracking step)
    swap(A[ind], B[ind]);
 
    // Increase count of A[i] in map and
    // call recursively for next index.
    ele[A[ind]]++;
    minCountUtil(A, B, ele, ans, ind + 1);
 
    // Restore the changes done
    // (Backtracking step)
    ele[A[ind]]--;
    if (ele[A[ind]] == 0)
        ele.erase(A[ind]);   
}
 
// Function to find minimum number of
// distinct characters in string.
int minCount(string A, string B)
{
    // Variable to store minimum number
    // of distinct character.
    // Initialize it with length of A
    // as maximum possible value is
    // length of A.
    int ans = A.length();
 
    // Map to store count of distinct
    // characters in A. To keep
    // complexity of insert operation
    // constant unordered_map is used.
    unordered_map<char, int> ele;
 
    // Call utility function to find
    // minimum number of unique
    // characters.
    minCountUtil(A, B, ele, ans, 0);
 
    return ans;
}
 
int main()
{
    string A = "abaaa";
    string B = "bbabb";
 
    cout << minCount(A, B);
    return 0;
}


Java




// Java program to minimize number of
// unique characters in a string.
import java.util.*;
class GFG {
 
  // Utility function to find minimum
  // number of unique characters in string.
  public static int
    minCountUtil(String A, String B,
                 HashMap<Character, Integer> ele, int ans,
                 int ind)
  {
     
    // If entire string is traversed, then
    // compare current number of distinct
    // characters in A with overall minimum.
    if (ind == A.length()) {
      ans = Math.min(ans, ele.size());
      return ans;
    }
 
    char[] a = A.toCharArray();
    char[] b = B.toCharArray();
 
    // swap A[i] with B[i], increase count of
    // corresponding character in map and call
    // recursively for next index.
    char temp = a[ind];
    a[ind] = b[ind];
    b[ind] = temp;
    A = new String(a);
    B = new String(b);
 
    if (ele.containsKey(A.charAt(ind))) {
      ele.put(A.charAt(ind),
              ele.get(A.charAt(ind)) + 1);
    }
    else {
      ele.put(A.charAt(ind), 1);
    }
    ans = minCountUtil(A, B, ele, ans, ind + 1);
 
    // Backtrack (Undo the changes done)
    ele.put(A.charAt(ind), ele.get(A.charAt(ind)) - 1);
 
    // If count of character is reduced to zero,
    // then that character is not present in A.
    // So remove that character from map.
    if (ele.get(A.charAt(ind)) == 0) {
      ele.remove(A.charAt(ind));
    }
 
    // Restore A to original form.
    // (Backtracking step)
    temp = a[ind];
    a[ind] = b[ind];
    b[ind] = temp;
    A = new String(a);
    B = new String(b);
 
    // Increase count of A[i] in map and
    // call recursively for next index.
    if (ele.containsKey(A.charAt(ind))) {
      ele.put(A.charAt(ind),
              ele.get(A.charAt(ind)) + 1);
    }
    else {
      ele.put(A.charAt(ind), 1);
    }
    ans = minCountUtil(A, B, ele, ans, ind + 1);
 
    // Restore the changes done
    // (Backtracking step)
    ele.put(A.charAt(ind), ele.get(A.charAt(ind)) - 1);
    if (ele.get(A.charAt(ind)) == 0) {
      ele.remove(A.charAt(ind));
    }
 
    return ans;
  }
 
  // Function to find minimum number of
  // distinct characters in string.
  public static int minCount(String A, String B)
  {
    // Variable to store minimum number
    // of distinct character.
    // Initialize it with length of A
    // as maximum possible value is
    // length of A.
    int ans = A.length();
 
    // HashMap to store count of distinct
    // characters in A. To keep
    // complexity of insert operation
    // constant unordered_map is used.
    HashMap<Character, Integer> ele = new HashMap<>();
 
    // Call utility function to find
    // minimum number of unique
    // characters.
    return minCountUtil(A, B, ele, ans, 0);
  }
 
  public static void main(String[] args)
  {
    String A = "abaaa";
    String B = "bbabb";
    System.out.println(minCount(A, B));
  }
}
 
// This Code is Contributed by Prasad Kandekar(prasad264)


Python3




# Python program to minimize number of
# unique characters in a string.
 
# Utility function to find minimum
# number of unique characters in string.
def minCountUtil(A, B, ele, ans, ind):
     
    # If entire string is traversed, then
    # compare current number of distinct
    # characters in A with overall minimum.
    if ind == len(A):
        ans = min(ans, len(ele))
        return ans
     
    # swap A[i] with B[i], increase count of
    # corresponding character in map and call
    # recursively for next index.
    a = list(A)
    b = list(B)
    temp = a[ind]
    a[ind] = b[ind]
    b[ind] = temp
    A = "".join(a)
    B = "".join(b)
 
    if A[ind] in ele:
        ele[A[ind]] += 1
    else:
        ele[A[ind]] = 1
    ans = minCountUtil(A, B, ele, ans, ind + 1)
 
    # Backtrack (Undo the changes done)
    ele[A[ind]] -= 1
 
    # If count of character is reduced to zero,
    # then that character is not present in A.
    # So remove that character from map.
    if ele[A[ind]] == 0:
        ele.pop(A[ind], None)
         
    # Restore A to original form.
    # (Backtracking step)
    temp = a[ind]
    a[ind] = b[ind]
    b[ind] = temp
    A = "".join(a)
    B = "".join(b)
     
    # Increase count of A[i] in map and
    # call recursively for next index.
    if A[ind] in ele:
        ele[A[ind]] += 1
    else:
        ele[A[ind]] = 1
    ans = minCountUtil(A, B, ele, ans, ind + 1)
 
    # Restore the changes done
    # (Backtracking step)
    ele[A[ind]] -= 1
    if ele[A[ind]] == 0:
        ele.pop(A[ind], None)
 
    return ans
 
# Function to find minimum number of
# distinct characters in string.
def minCount(A, B):
     
    # Variable to store minimum number
    # of distinct character.
    # Initialize it with length of A
    # as maximum possible value is
    # length of A.
    ans = len(A)
     
    # dictionary to store count of distinct
    # characters in A. To keep
    # complexity of insert operation
    # constant dictionary is used.
    ele = {}
 
    # Call utility function to find
    # minimum number of unique
    # characters.
    return minCountUtil(A, B, ele, ans, 0)
 
A = "abaaa"
B = "bbabb"
print(minCount(A, B))
# This Code is Contributed by Prasad Kandekar(prasad264)


C#




// C# program to minimize number of
// unique characters in a string.
using System;
using System.Collections.Generic;
 
namespace MinCountString {
  class Program
  {
     
    // Utility function to find minimum number of unique
    // characters in string.
    static void MinCountUtil(string A, string B,
                             Dictionary<char, int> ele,
                             ref int ans, int ind)
    {
       
      // If entire string is traversed, then compare
      // current number of distinct characters in A with
      // overall minimum.
      if (ind == A.Length) {
        ans = Math.Min(ans, ele.Count);
        return;
      }
 
      // Swap A[i] with B[i], increase count of
      // corresponding character in map and call
      // recursively for next index.
      char[] charArray = A.ToCharArray();
      char temp = charArray[ind];
      charArray[ind] = B[ind];
      A = new string(charArray);
      if (ele.ContainsKey(A[ind]))
        ele[A[ind]]++;
      else
        ele.Add(A[ind], 1);
      MinCountUtil(A, B, ele, ref ans, ind + 1);
 
      // Backtrack (Undo the changes done)
      ele[A[ind]]--;
      // If count of character is reduced to zero, then
      // that character is not present in A. So remove
      // that character from map.
      if (ele[A[ind]] == 0)
        ele.Remove(A[ind]);
 
      // Restore A to original form. (Backtracking step)
      charArray[ind] = temp;
      A = new string(charArray);
 
      // Increase count of A[i] in map and call
      // recursively for next index.
      if (ele.ContainsKey(A[ind]))
        ele[A[ind]]++;
      else
        ele.Add(A[ind], 1);
      MinCountUtil(A, B, ele, ref ans, ind + 1);
 
      // Restore the changes done (Backtracking step)
      ele[A[ind]]--;
      if (ele[A[ind]] == 0)
        ele.Remove(A[ind]);
    }
 
    // Function to find minimum number of distinct
    // characters in string.
    static int MinCount(string A, string B)
    {
      // Variable to store minimum number of distinct
      // character. Initialize it with length of A as
      // maximum possible value is length of A.
      int ans = A.Length;
 
      // Map to store count of distinct characters in A.
      // To keep complexity of insert operation constant
      // Dictionary is used.
      Dictionary<char, int> ele
        = new Dictionary<char, int>();
 
      // Call utility function to find minimum number of
      // unique characters.
      MinCountUtil(A, B, ele, ref ans, 0);
 
      return ans;
    }
 
    static void Main(string[] args)
    {
      string A = "abaaa";
      string B = "bbabb";
 
      Console.WriteLine(MinCount(A, B));
    }
  }
}
 
// This code is contributed by prajwalkandekar123.


Javascript




// JavaScript program to minimize number of
// unique characters in a string.
 
// Utility function to find minimum number of unique
// characters in string.
function minCountUtil(A, B, ele, ans, ind) {
     
    // If entire string is traversed, then compare
    // current number of distinct characters in A with
    // overall minimum.
    if (ind == A.length) {
        ans[0] = Math.min(ans[0], Object.keys(ele).length);
        return;
    }
 
    // Swap A[i] with B[i], increase count of
    // corresponding character in map and call
    // recursively for next index.
    var charArray = A.split('');
    var temp = charArray[ind];
    charArray[ind] = B[ind];
    A = charArray.join('');
    if (ele.hasOwnProperty(A[ind])) {
        ele[A[ind]]++;
    }
    else {
        ele[A[ind]] = 1;
    }
    minCountUtil(A, B, ele, ans, ind + 1);
 
    // Backtrack (Undo the changes done)
    ele[A[ind]]--;
   
    // If count of character is reduced to zero, then
    // that character is not present in A. So remove
    // that character from map.
    if (ele[A[ind]] == 0) {
        delete ele[A[ind]];
    }
 
    // Restore A to original form. (Backtracking step)
    charArray[ind] = temp;
    A = charArray.join('');
     
    // Increase count of A[i] in map and call
    // recursively for next index.
    if (ele.hasOwnProperty(A[ind])) {
        ele[A[ind]]++;
    }
    else {
        ele[A[ind]] = 1;
    }
    minCountUtil(A, B, ele, ans, ind + 1);
 
    // Restore the changes done (Backtracking step)
    ele[A[ind]]--;
    if (ele[A[ind]] == 0) {
        delete ele[A[ind]];
    }
}
 
// Function to find minimum number of distinct
// characters in string.
function minCount(A, B) {
     
    // Variable to store minimum number of distinct
    // character. Initialize it with length of A as
    // maximum possible value is length of A.
    var ans = [A.length];
 
    // Map to store count of distinct characters in A.
    // To keep complexity of insert operation constant
    // object literal is used.
    var ele = {};
 
    // Call utility function to find minimum number of
    // unique characters.
    minCountUtil(A, B, ele, ans, 0);
 
    return ans[0];
}
 
var A = 'abaaa';
var B = 'bbabb';
 
console.log(minCount(A, B));
 
// This code is contributed by Prasad Kandekar(prasad264).


Output

2

Time Complexity: O(2n
Auxiliary Space: O(n)



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