Open In App

Count Fair pairs in a String with Uppercase-Lowercase operations

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S of length N that contains only uppercase and lowercase letters, the task is to find the maximum number of pairs that consist of an uppercase and a lowercase version of the same letter, and each character can only belong to one pair. You are allowed to perform K operations, wherein each operation, you can either change an uppercase letter to a lowercase or vice-versa.

Examples:

Input: S = “xyyxzzYYZ”, K = 1
Output: 3
Explanation: One possible operation is to change the “x” to “X”, resulting in the pair “xX”. The maximum number of pairs that can be formed after this operation is 3 (xX, yY, Zz).

Input: S = “xyyXzzYyxxZ”, K = 2
Output: 5

Approach: This can be solved with the following idea:

The approach is to first create a map to store the frequency of each character in the given string. Then, we iterate through each letter of the alphabet (a to z). For each letter, we count the number of pairs of the same letter by subtracting the frequency of lowercase and uppercase letters. If there are still uppercase letters remaining, we count pairs of different letters with an uppercase letter. Similarly, if there are still lowercase letters remaining, we count pairs of different letters with a lowercase letter. We repeat these steps for each letter of the alphabet. Finally, the total number of pairs is the sum of pairs counted in steps 3-5 for each letter of the alphabet.

Steps to implement the approach:

  • Initialize a map mp to store the frequency of each character in the input string.
  • Initialize xxx and yyy to the characters ‘a’ and ‘A’, respectively, and output to zero.
  • For each letter xxx in the range ‘a’ to ‘z’:
    • Count the frequency of lowercase and uppercase versions of the letter.
    • Count the number of pairs of the same letter (e.g. “Aa” or “Bb”) and subtract this count from the frequency of lowercase and uppercase letters.
    • If there are still uppercase letters remaining, count pairs of different letters with an uppercase letter.
    • If there are still lowercase letters remaining, count pairs of different letters with a lowercase letter.
    • Add the total count of pairs for this letter to output.
    • Increment xxx and yyy to move to the next letter in the alphabet.
  • Print output as the total number of fair pairs.

Below is the implementation of the above approach:

C++




// C++ Implementation
#include <bits/stdc++.h>
using namespace std;
 
// Function to count maximum
// number of pairs
void countPairs(string S, int n, int K)
{
 
    map<char, long long int> mp;
 
    // Count the frequency of each
    // character in the string
    for (long long int i = 0; i < n; i++) {
        mp[S[i]]++;
    }
 
    // Initialize variables for
    // counting pairs
    char xxx = 'a';
    char yyy = 'A';
 
    // Counter for the number of pairs
    long long int output = 0;
 
    // Iterate through each letter in the
    // alphabet
    for (long long int i = 0; i < 26; i++) {
 
        // Frequency of lowercase letter
        long long int l = mp[xxx];
 
        // Frequency of uppercase letter
        long long int u = mp[yyy];
 
        // Count pairs of the same letter
        // (e.g. "Aa" or "Bb")
        while (l > 0 && u > 0) {
            output++;
            l--;
            u--;
        }
 
        // Count pairs of different letters
        // with an uppercase letter
        // (e.g. "Ab" or "Cc")
        while (K > 0 && u > 1) {
            K--;
            output++;
            u -= 2;
        }
 
        // Count pairs of different letters
        // with a lowercase letter
        // (e.g. "aB" or "cC")
        while (K > 0 && l > 1) {
            K--;
            output++;
            l -= 2;
        }
 
        // Move to the next letter in the
        // alphabet
        xxx++;
        yyy++;
    }
 
    // Print the total number of pairs
    cout << output << endl;
}
 
// Driver code
int main()
{
 
    // Declare variables and initialize
    // some values
    long long int N, K = 2;
    string S = "xyyXzzYyxxZ";
    N = S.length();
 
    // Function call
    countPairs(S, N, K);
 
    return 0;
}


Java




import java.util.*;
 
public class Main {
  public static void countPairs(String S, int n, int K) {
 
    Map<Character, Long> mp = new HashMap<>();
 
    // Count the frequency of each character in the string
    for (long i = 0; i < n; i++) {
      char ch = S.charAt((int)i);
      mp.put(ch, mp.getOrDefault(ch, 0L) + 1);
    }
 
    // Initialize variables for counting pairs
    char xxx = 'a';
    char yyy = 'A';
 
    // Counter for the number of pairs
    long output = 0;
 
    // Iterate through each letter in the alphabet
    for (long i = 0; i < 26; i++) {
 
      // Frequency of lowercase letter
      long l = mp.getOrDefault(xxx, 0L);
 
      // Frequency of uppercase letter
      long u = mp.getOrDefault(yyy, 0L);
 
      // Count pairs of the same letter (e.g. "Aa" or "Bb")
      while (l > 0 && u > 0) {
        output++;
        l--;
        u--;
      }
 
      // Count pairs of different letters with an uppercase letter (e.g. "Ab" or "Cc")
      while (K > 0 && u > 1) {
        K--;
        output++;
        u -= 2;
      }
 
      // Count pairs of different letters with a lowercase letter (e.g. "aB" or "cC")
      while (K > 0 && l > 1) {
        K--;
        output++;
        l -= 2;
      }
 
      // Move to the next letter in the alphabet
      xxx++;
      yyy++;
    }
 
    // Print the total number of pairs
    System.out.println(output);
  }
 
  public static void main(String[] args) {
 
    // Declare variables and initialize some values
    int K = 2;
    String S = "xyyXzzYyxxZ";
    int N = S.length();
 
    // Function call
    countPairs(S, N, K);
  }
}
 
// This code is contributed by Prajwal Kandekar


Python3




#Python Implementation
def countPairs(S: str, n: int, K: int) -> None:
    mp = {}
 
    # Count the frequency of each character in the string
    for i in range(n):
        mp[S[i]] = mp.get(S[i], 0) + 1
 
    # Initialize variables for counting pairs
    xxx = 'a'
    yyy = 'A'
 
    # Counter for the number of pairs
    output = 0
 
    # Iterate through each letter in the alphabet
    for i in range(26):
        # Frequency of lowercase letter
        l = mp.get(xxx, 0)
 
        # Frequency of uppercase letter
        u = mp.get(yyy, 0)
 
        # Count pairs of the same letter (e.g. "Aa" or "Bb")
        while l > 0 and u > 0:
            output += 1
            l -= 1
            u -= 1
 
        # Count pairs of different letters with an uppercase letter (e.g. "Ab" or "Cc")
        while K > 0 and u > 1:
            K -= 1
            output += 1
            u -= 2
 
        # Count pairs of different letters with a lowercase letter (e.g. "aB" or "cC")
        while K > 0 and l > 1:
            K -= 1
            output += 1
            l -= 2
 
        # Move to the next letter in the alphabet
        xxx = chr(ord(xxx) + 1)
        yyy = chr(ord(yyy) + 1)
 
    # Print the total number of pairs
    print(output)
 
# Driver code
if __name__ == '__main__':
    # Declare variables and initialize some values
    N, K = 2, 2
    S = "xyyXzzYyxxZ"
    countPairs(S, len(S), K)


C#




using System;
using System.Collections.Generic;
 
class MainClass {
  public static void CountPairs(string S, int n, int K) {
    Dictionary<char, long> mp = new Dictionary<char, long>();
 
    // Count the frequency of each character in the string
    for (long i = 0; i < n; i++) {
      char ch = S[(int)i];
      if (mp.ContainsKey(ch)) {
        mp[ch]++;
      } else {
        mp[ch] = 1;
      }
    }
 
    // Initialize variables for counting pairs
    char xxx = 'a';
    char yyy = 'A';
 
    // Counter for the number of pairs
    long output = 0;
 
    // Iterate through each letter in the alphabet
    for (long i = 0; i < 26; i++) {
 
      // Frequency of lowercase letter
      long l = mp.ContainsKey(xxx) ? mp[xxx] : 0;
 
      // Frequency of uppercase letter
      long u = mp.ContainsKey(yyy) ? mp[yyy] : 0;
 
      // Count pairs of the same letter (e.g. "Aa" or "Bb")
      while (l > 0 && u > 0) {
        output++;
        l--;
        u--;
      }
 
      // Count pairs of different letters with an
      // uppercase letter (e.g. "Ab" or "Cc")
      while (K > 0 && u > 1) {
        K--;
        output++;
        u -= 2;
      }
 
      // Count pairs of different letters with a
      // lowercase letter (e.g. "aB" or "cC")
      while (K > 0 && l > 1) {
        K--;
        output++;
        l -= 2;
      }
 
      // Move to the next letter in the alphabet
      xxx++;
      yyy++;
    }
 
    // Print the total number of pairs
    Console.WriteLine(output);
  }
 
  public static void Main(string[] args) {
 
    // Declare variables and initialize some values
    int K = 2;
    string S = "xyyXzzYyxxZ";
    int N = S.Length;
 
    // Function call
    CountPairs(S, N, K);
  }
}


Javascript




// JavaScript implementation
 
// Function to count maximum
// number of pairs
function countPairs(S, N, K) {
 
    let mp = new Map();
 
    // Count the frequency of each character in the string
    for (let i = 0; i < N; i++) {
        let char = S.charAt(i);
        if (mp.has(char)) {
            mp.set(char, mp.get(char) + 1);
        }
        else {
            mp.set(char, 1);
        }
    }
 
    // Initialize variables for
    // counting pairs
    let xxx = 'a';
    let yyy = 'A';
 
    // Counter for the number of pairs
    let output = 0;
 
    // Iterate through each letter in the
    // alphabet
    for (let i = 0; i < 26; i++) {
 
 
        // Frequency of lowercase letter
        let l = mp.get(xxx) || 0;
     
        // Frequency of uppercase letter
        let u = mp.get(yyy) || 0;
 
        // Count pairs of the same letter
        // (e.g. "Aa" or "Bb")
        while (l > 0 && u > 0) {
            output++;
            l--;
            u--;
        }
 
        // Count pairs of different letters
        // with an uppercase letter
        // (e.g. "Ab" or "Cc")
        while (K > 0 && u > 1) {
            K--;
            output++;
            u -= 2;
        }
 
        // Count pairs of different letters
        // with a lowercase letter
        // (e.g. "aB" or "cC")
        while (K > 0 && l > 1) {
            K--;
            output++;
            l -= 2;
        }
 
        // Move to the next letter in the
        // alphabet
        xxx = String.fromCharCode(xxx.charCodeAt(0) + 1);
        yyy = String.fromCharCode(yyy.charCodeAt(0) + 1);
    }
 
    // Print the total number of pairs
    console.log(output);
}
 
// Driver code
 
// Declare variables and initialize
// some values
let N = 0;
let K = 2;
let S = "xyyXzzYyxxZ";
N = S.length;
 
// Function call
countPairs(S, N, K);


Output

5

Time Complexity:  O(n + log n)
Auxiliary Space: O(n)



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