Skip to content
Related Articles

Related Articles

Minimize swaps of same-indexed characters to make sum of ASCII value of characters of both the strings odd
  • Difficulty Level : Easy
  • Last Updated : 23 Feb, 2021

Given two N-length strings S and T consisting of lowercase alphabets, the task is to minimize the number of swaps of same indexed elements required to make the sum of ASCII value of characters of both the strings odd. If it is not possible to make the sum of ASCII values odd, then print “-1”.

Examples:

Input:S = ”acd”, T = ”dbf”
Output: 1
Explanation:
Swapping S[1] and T[1] modifies S to “abd” and T to “dcf”.
Sum of ASCII value of characters of the string S = 97 + 98 + 100 = 297 (Odd).
Sum of ASCII value of characters of the string T = 100 + 99 + 102 = 301 (Odd).

Input: S = “aey”, T = “cgj”
Output: -1

Approach: Follow the steps below to solve the problem:

  • Calculate the sum of ASCII values of the characters of the string S and T and store it in variables sum1 and sum2 respectively.
  • If sum1 and sum2 are already odd, then print 0, as no swaps are required.
  • If sum1 and sum2 are of different parities, print -1, as the sum cannot be of same parity for both the strings.
  • If sum1 and sum2 are both even, then traverse the given strings S and T. If there exists any character with odd ASCII value, sum of ASCII values of the characters of both the strings can be made odd by only 1 swap. Otherwise, print -1.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the number of swaps
// required to make the sum of ASCII values
// of the characters of both strings odd
void countSwaps(string S, string T)
{
    // Initialize alphabets with value
    int value[26];
 
    // Initialize values for each
    // alphabet
    for (int i = 0; i < 26; i++)
        value[i] = i + 1;
 
    // Size of the string
    int N = S.size();
 
    // Sum of string S
    int sum1 = 0;
 
    // Sum of string T
    int sum2 = 0;
 
    // Stores whether there is any
    // index i such that S[i] and
    // T[i] have different parities
    bool flag = false;
 
    // Traverse the strings
    for (int i = 0; i < N; i++) {
 
        // Update sum1 and sum2
        sum1 += value[S[i] - 'a'];
        sum2 += value[T[i] - 'a'];
 
        // If S[i] and T[i] have
        // different parities
        if ((value[S[i] - 'a'] % 2 == 0
             && value[T[i] - 'a'] % 2 == 1)
 
            || (value[S[i] - 'a'] % 2 == 1
                && value[T[i] - 'a'] % 2 == 0))
 
            flag = false;
    }
 
    // If sum1 and sum2 are both odd
    if (sum1 % 2 == 1
        && sum2 % 2 == 1)
        cout << "0\n";
 
    // If sum1 and sum2 are both even
    else if (sum1 % 2 == 0
             && sum2 % 2 == 0) {
 
        // If exists print 1
        if (flag)
            cout << "1";
 
        // Otherwise
        else
            cout << "-1";
    }
 
    // If sum1 and sum2 are
    // of different parities
    else {
        cout << "-1";
    }
}
 
// Driver Code
int main()
{
    string S = "acd";
    string T = "dbf";
 
    // Function Call
    countSwaps(S, T);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
class GFG
{
 
  // Function to count the number of swaps
  // required to make the sum of ASCII values
  // of the characters of both strings odd
  static void countSwaps(String S, String T)
  {
 
    // Initialize alphabets with value
    int[] value = new int[26];
 
    // Initialize values for each
    // alphabet
    for (int i = 0; i < 26; i++)
      value[i] = i + 1;
 
    // Size of the string
    int N = S.length();
 
    // Sum of string S
    int sum1 = 0;
 
    // Sum of string T
    int sum2 = 0;
 
    // Stores whether there is any
    // index i such that S[i] and
    // T[i] have different parities
    boolean flag = false;
 
    // Traverse the strings
    for (int i = 0; i < N; i++) {
 
      // Update sum1 and sum2
      sum1 += value[S.charAt(i) - 'a'];
      sum2 += value[T.charAt(i) - 'a'];
 
      // If S[i] and T[i] have
      // different parities
      if ((value[S.charAt(i) - 'a'] % 2 == 0
           && value[T.charAt(i) - 'a'] % 2 == 1)
 
          || (value[S.charAt(i) - 'a'] % 2 == 1
              && value[T.charAt(i) - 'a'] % 2 == 0))
 
        flag = false;
    }
 
    // If sum1 and sum2 are both odd
    if (sum1 % 2 == 1
        && sum2 % 2 == 1)
      System.out.println("0\n");
 
    // If sum1 and sum2 are both even
    else if (sum1 % 2 == 0
             && sum2 % 2 == 0) {
 
      // If exists print 1
      if (flag)
        System.out.println("1");
 
      // Otherwise
      else
        System.out.println("-1");
    }
 
    // If sum1 and sum2 are
    // of different parities
    else {
      System.out.println("-1");
    }
  }
 
  // Driver Code
  public static void main(String[] args)
  {
 
    String S = "acd";
    String T = "dbf";
 
    // Function Call
    countSwaps(S, T);
  }
}
 
// This code is contributed by susmitakundugoaldanga.

Python3




# Python3 program for the above approach
 
# Function to count the number of swaps
# required to make the sum of ASCII values
# of the characters of both strings odd
def countSwaps(S, T):
   
    # Initialize alphabets with value
    value = [0]*26
 
    # Initialize values for each
    # alphabet
    for i in range(26):
        value[i] = i + 1
 
    # Size of the string
    N = len(S)
 
    # Sum of S
    sum1 = 0
 
    # Sum of T
    sum2 = 0
 
    # Stores whether there is any
    # index i such that S[i] and
    # T[i] have different parities
    flag = False
 
    # Traverse the strings
    for i in range(N):
 
        # Update sum1 and sum2
        sum1 += value[ord(S[i]) - ord('a')]
        sum2 += value[ord(T[i]) - ord('a')]
 
        # If ord(S[i]) anord('a)rd(T[i]) haord('a)
        # different parities
        if (value[ord(S[i]) - ord('a')] % 2 == 0
            and value[ord(T[i]) - ord('a')] % 2 == 1
            or value[ord(S[i]) - ord('a')] % 2 == 1
            and value[ord(T[i]) - ord('a')] % 2 == 0):
             
            flag = False
 
    # If sum1 and sum2 are both odd
    if (sum1 % 2 == 1 and sum2 % 2 == 1):
        print("0")
 
    # If sum1 and sum2 are both even
    elif (sum1 % 2 == 0 and sum2 % 2 == 0):
 
        # If exists pr1
        if (flag):
            print("1")
 
        # Otherwise
        else:
            print("-1")
 
    # If sum1 and sum2 are
    # of different parities
    else:
        print("-1")
 
# Driver Code
if __name__ == '__main__':
    S = "acd"
    T = "dbf"
 
    # Function Call
    countSwaps(S, T)
 
    # This code is contributed by mohit kumar 29.

C#




// C# program for the above approach
using System;
 
public class GFG
{
   
// Function to count the number of swaps
// required to make the sum of ASCII values
// of the characters of both strings odd
static void countSwaps(string S, string T)
{
   
    // Initialize alphabets with value
    int[] value = new int[26];
 
    // Initialize values for each
    // alphabet
    for (int i = 0; i < 26; i++)
        value[i] = i + 1;
 
    // Size of the string
    int N = S.Length;
 
    // Sum of string S
    int sum1 = 0;
 
    // Sum of string T
    int sum2 = 0;
 
    // Stores whether there is any
    // index i such that S[i] and
    // T[i] have different parities
    bool flag = false;
 
    // Traverse the strings
    for (int i = 0; i < N; i++) {
 
        // Update sum1 and sum2
        sum1 += value[S[i] - 'a'];
        sum2 += value[T[i] - 'a'];
 
        // If S[i] and T[i] have
        // different parities
        if ((value[S[i] - 'a'] % 2 == 0
             && value[T[i] - 'a'] % 2 == 1)
 
            || (value[S[i] - 'a'] % 2 == 1
                && value[T[i] - 'a'] % 2 == 0))
 
            flag = false;
    }
 
    // If sum1 and sum2 are both odd
    if (sum1 % 2 == 1
        && sum2 % 2 == 1)
        Console.Write("0\n");
 
    // If sum1 and sum2 are both even
    else if (sum1 % 2 == 0
             && sum2 % 2 == 0) {
 
        // If exists print 1
        if (flag)
            Console.Write("1");
 
        // Otherwise
        else
            Console.Write("-1");
    }
 
    // If sum1 and sum2 are
    // of different parities
    else {
        Console.Write("-1");
    }
}
 
 
// Driver Code
public static void Main(String[] args)
{
    string S = "acd";
    string T = "dbf";
 
    // Function Call
    countSwaps(S, T);
}
}
 
// This code is contributed by code_hunt.
Output: 
-1

 

Time Complexity: O(N)
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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :