Open In App

Minimize swaps of same-indexed characters to make sum of ASCII value of characters of both the strings odd

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given two N-length strings S and T consisting of lowercase alphabets, the task is to minimize the number of swaps of the same indexed elements required to make the sum of the 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.


Javascript




<script>
      // JavaScript 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
      function countSwaps(S, T)
      {
       
        // Initialize alphabets with value
        var value = [...Array(26)];
 
        // Initialize values for each
        // alphabet
        for (var i = 0; i < 26; i++) value[i] = i + 1;
 
        // Size of the string
        var N = S.length;
 
        // Sum of string S
        var sum1 = 0;
 
        // Sum of string T
        var sum2 = 0;
 
        // Stores whether there is any
        // index i such that S[i] and
        // T[i] have different parities
        var flag = false;
 
        // Traverse the strings
        for (var 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) document.write("0 <br>");
        // If sum1 and sum2 are both even
        else if (sum1 % 2 === 0 && sum2 % 2 === 0) {
          // If exists print 1
          if (flag) document.write("1");
          // Otherwise
          else document.write("-1");
        }
 
        // If sum1 and sum2 are
        // of different parities
        else {
          document.write("-1");
        }
      }
 
      // Driver Code
      var S = "aey";
      var T = "cgj";
       
      // Function Call
      countSwaps(S, T);
       
      // This code is contributed by rdtank.
    </script>


Output

-1

the



Previous Article
Next Article

Similar Reads

Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Minimize replacements or swapping of same indexed characters required to make two given strings palindromic
Given two strings, str1 and str2 consisting of N lowercase alphabets, the task is to find the minimum count of operations of the following two types to make both the strings palindromic string. Replace any character of the strings to any other character([a - z]).Swap any two characters present at the same index in both the strings. Examples: Input:
8 min read
Minimize operations to make both arrays equal by decrementing a value from either or both
Given two arrays A[] and B[] having N integers, the task is to find the minimum operations required to make all the elements of both the array equal where at each operation, the following can be done: Decrement the value of A[i] by 1 where i lies in the range [0, N).Decrement the value of B[i] by 1 where i lies in the range [0, N).Decrement the val
8 min read
Minimum swaps of same-indexed elements required to make sum of two given arrays even
Given two arrays arr1[] and arr2[] of size N, the task is to count the minimum number of swaps of same-indexed elements from both the arrays arr1[] and arr2[] required to make the sum of all elements of both the arrays even. If it is not possible, then print "-1". Examples: Input: arr1[] = {1, 4, 2, 3}, arr2[] = {2, 3, 4, 1}Output: 0Explanation: Su
9 min read
Make all the elements of array odd by incrementing odd-indexed elements of odd-length subarrays
Given an array arr[] of size N, the task is to make all the array elements odd by choosing an odd length subarray of arr[] and increment all odd positioned elements by 1 in this subarray. Print the count of such operations required. Examples: Input: arr[] = {2, 3, 4, 3, 5, 3, 2}Output: 2Explanation:In first operation, choose the subarray {2, 3, 4}
9 min read
Minimize swaps required to make all prime-indexed elements as prime
Given an array arr[] of size N. The task is to find the minimum number of swaps required to re-arrange the array such that all prime-indexed elements are prime, If the task can't be achieved, print "-1" Examples: Input: N = 5, arr[] = {1, 2, 3, 4, 5}Output: 0Explanation: All the prime indices {2, 3, 5} (one-based indexing) have prime elements prese
9 min read
Modify given array to make sum of odd and even indexed elements same
Given a binary array arr[] of size N, remove at most N/2 elements from the array such that the sum of elements at odd and even indices becomes equal. The task is to print the modified array.Note: N is always even. There can be more than one possible result, print any of them. Examples: Input: arr[] = {1, 1, 1, 0}Output: 1 1Explanation:For the given
10 min read
Minimize swaps of pairs of characters required such that no two adjacent characters in the string are same
Given a string S consisting of N characters, the task is to find the minimum number of pairs of characters that are required to be swapped such that no two adjacent characters are the same. If it is not possible to do so, then print "-1". Examples: Input: S = "ABAACD"Output: 1Explanation: Swapping S[3] and S[4] modifies the given string S to "ABACA
9 min read
Count of Pairs in given Array having both even or both odd or sum as K
Given an array arr[] of distinct integers of size N and an integer K, The task is to find the total no of possible pairs in the array such that, either both are even or both are odd or the sum of the pair is K Note: No element is part of more than one pair. Examples: Input: N = 6, K = 7, arr[] = {1, 2, 3, 4, 5, 6}Output: 3Explanation: Possible pair
7 min read
Divide array into two arrays with their sum as both odd or both even
Given an array arr[] consisting of N integers, the task is to check if it is possible to divide the entire array into two arrays such that the sum of elements in new arrays is either both odd or both even. Also, each new array must have at least one element. If it is possible, print “Yes”. Otherwise, print “No”. Examples: Input: arr[] = {3, 1, 1, 1
6 min read
Article Tags :
Practice Tags :