Open In App

Check if it is possible to make all strings of A[] equal to B[] using given operations

Last Updated : 11 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Consider two arrays, A[] and B[], each containing N strings. These strings are composed solely of digits ranging from 0 to 9. Then your task is to output YES or NO, by following that all the strings of A[] can be made equal to B[] for each i (1 <= i <= N) in at most K cost. The following operations can be performed:

  • Select two distinct indices and swap a single digit in the strings at those indices in A[]. This operation has no cost.
  • Choose an index, say i, and replace a digit in the ith string of A[] with any other digit from 0 to 9. This operation has a cost equal to 1.

Examples:

Input: N = 3, K = 3, A[] = {25, 67, 66}, B[] = {27, 65, 66}
Output: YES
Explanation: Apply first operation by taking indices i = 1 and j = 2, then A1 = 25 and A2 = 67. Then swap 5 of A1 with 7 of A2. Then A1 = 27 and A2 = 65. Updated A[] is = {27, 65, 66}. Now it can be verified that all Ai = Bi for all i (1 <= i <= N). This operation required 0 cost, Which is less than or equal 3. Therefore, output is YES.

Input: N = 2, K = 2, A[] = {55, 5}, B[] = {5, 55}
Output: NO
Explanation: It can be verified that using the given operations it is not possible to make all Ai = Bi for all i (1 <= i <= N).

Approach: To solve the problem follow the below idea:

The problem can be solved by counting the frequency of digits of strings in A[]. Solving this problem requires HashMap Data – Structure.

One of the observation regarding this problem is that there is no way to increment or decrement number of digits in the string Ai , If it does not match with Bi, So no solution would exist if the number of digits in Ai and Bi does not match.

If we handled the first case, Then we need to check if the complete array A has sufficient count of all the digits that are required in B. The difference in the number of digits (0-9) would be the cost of adding them. If the cost is less than or equal to K then solution exist otherwise solution does not exist.

Steps were taken to solve the problem:

  • Create two arrays let say Count[] and Size[] of length 10 and N respectively.
  • Run a loop for i = 0 to i < N and follow below mentioned steps under the scope of loop:
    • Current element = A[i]
    • Add frequency of digits of current_element into Size[]
  • Create boolean variable let say Ans and mark it true initially.
  • Run a loop for i = 0 to i < N and follow below mentioned steps under the scope of loop:
    • Current element = B[i]
    • Subtract frequency of digits of current_element into Size[]
    • if (Size[digit] != 0), then mark Ans as false
  • If (Ans is false), then output NO.
  • Else
    • Create a variable let say Ct.
    • Run a loop for i = 0 to i < 10 and follow below mentioned steps under the scope of loop:
      • If(Count[i] < 0) Ct += Math.abs(Count[i])
    • If (Ct <= K), then output YES else NO.

Below is the implementation of the above approach:

C++




#include <iostream>
#include <cmath>
 
using namespace std;
 
// Function to check if it is possible to make two arrays equal
void Is_possible(int N, int K, long A[], long B[]) {
     
    // Array to count frequency of digits
    long count[10] = {0};
    int size[N];
 
    // Loop for traversing over strings of A and counting digits
    for (int i = 0; i < N; i++) {
        long x = A[i];
        while (x > 0) {
            int d = (int)(x % 10);
            count[d]++;
            x /= 10;
            size[i]++;
        }
    }
 
    // Loop for traversing over strings of B[] and counting digits
    bool ans = true;
    for (int i = 0; i < N; i++) {
        long x = B[i];
        while (x > 0) {
            int d = (int)(x % 10);
            count[d]--;
            x /= 10;
            size[i]--;
        }
        if (size[i] != 0)
            ans = false;
    }
 
    // Implementing the discussed idea and printing output
    if (!ans) {
        cout << "NO" << endl;
    } else {
        long ct = 0;
        for (int i = 0; i < 10; i++) {
            if (count[i] < 0)
                ct += abs(count[i]);
        }
        if (ct <= K)
            cout << "YES" << endl;
        else
            cout << "NO" << endl;
    }
}
 
// Driver Function
int main() {
 
    // Inputs
    int N = 2;
    int K = 2;
    long A[] = {11, 1};
    long B[] = {1, 11};
 
    // Function call
    Is_possible(N, K, A, B);
 
    return 0;
}


Java




// Java code to implement the approach
 
import java.util.*;
 
// Driver Class
class GFG {
 
    // Driver Function
    public static void main(String[] args)
        throws java.lang.Exception
    {
 
        // Inputs
        int N = 2;
        int K = 2;
        long[] A = { 11, 1 };
        long[] B = { 1, 11 };
 
        // Function call
        Is_possible(N, K, A, B);
    }
    public static void Is_possible(int N, int K, long[] A,
                                   long[] B)
    {
 
        // Array to count frequency of digitd
        long count[] = new long[10];
        int size[] = new int[N];
 
        // Loop for traversing over strings of
        // A and counting diigts
        for (int i = 0; i < N; i++) {
            long x = A[i];
            while (x > 0) {
                int d = (int)(x % 10);
                count[d]++;
                x /= 10;
                size[i]++;
            }
        }
 
        // Loop for traversing over strings of
        // B[] and counting diigts
        boolean ans = true;
        for (int i = 0; i < N; i++) {
            long x = B[i];
            while (x > 0) {
                int d = (int)(x % 10);
                count[d]--;
                x /= 10;
                size[i]--;
            }
            if (size[i] != 0)
                ans = false;
        }
 
        // Implementing the discussed idea
        // and printing output
        if (!ans) {
            System.out.println("NO");
        }
        else {
            long ct = 0;
            for (int i = 0; i < 10; i++) {
                if (count[i] < 0)
                    ct += Math.abs(count[i]);
            }
            if (ct <= K)
                System.out.println("YES");
            else
                System.out.println("NO");
        }
    }
}


Python3




def is_possible(N, K, A, B):
    # Array to count frequency of digits
    count = [0] * 10
    size = [0] * N
 
    # Loop for traversing over strings of A and counting digits
    for i in range(N):
        x = A[i]
        while x > 0:
            d = x % 10
            count[d] += 1
            x //= 10
            size[i] += 1
 
    # Loop for traversing over strings of B[] and counting digits
    ans = True
    for i in range(N):
        x = B[i]
        while x > 0:
            d = x % 10
            count[d] -= 1
            x //= 10
            size[i] -= 1
        if size[i] != 0:
            ans = False
 
    # Implementing the discussed idea and printing output
    if not ans:
        print("NO")
    else:
        ct = 0
        for i in range(10):
            if count[i] < 0:
                ct += abs(count[i])
        if ct <= K:
            print("YES")
        else:
            print("NO")
 
# Driver Function
def main():
    # Inputs
    N = 2
    K = 2
    A = [11, 1]
    B = [1, 11]
 
    # Function call
    is_possible(N, K, A, B)
 
# Call the main function
main()


C#




// C# program for the above approach
using System;
 
public class GFG {
    // Function to check if it is possible to make two
    // arrays equal
    static void IsPossible(int N, int K, long[] A, long[] B)
    {
        // Array to count frequency of digits
        long[] count = new long[10];
        int[] size = new int[N];
 
        // Loop for traversing over strings of A and
        // counting digits
        for (int i = 0; i < N; i++) {
            long x = A[i];
            while (x > 0) {
                int d = (int)(x % 10);
                count[d]++;
                x /= 10;
                size[i]++;
            }
        }
 
        // Loop for traversing over strings of B[] and
        // counting digits
        bool ans = true;
        for (int i = 0; i < N; i++) {
            long x = B[i];
            while (x > 0) {
                int d = (int)(x % 10);
                count[d]--;
                x /= 10;
                size[i]--;
            }
            if (size[i] != 0)
                ans = false;
        }
 
        // Implementing the discussed idea and printing
        // output
        if (!ans) {
            Console.WriteLine("NO");
        }
        else {
            long ct = 0;
            for (int i = 0; i < 10; i++) {
                if (count[i] < 0)
                    ct += Math.Abs(count[i]);
            }
            if (ct <= K)
                Console.WriteLine("YES");
            else
                Console.WriteLine("NO");
        }
    }
 
    // Driver Function
    static void Main()
    {
        // Inputs
        int N = 2;
        int K = 2;
        long[] A = { 11, 1 };
        long[] B = { 1, 11 };
 
        // Function call
        IsPossible(N, K, A, B);
    }
}
 
// This code is contributed by Susobhan Akhuli


Javascript




// JavaScript code to implement the above approach
 
// Function to check if it is possible to make two arrays equal
function isPossible(N, K, A, B) {
    // Array to count frequency of digits
    let count = new Array(10).fill(0);
    let size = new Array(N).fill(0);
 
    // Loop for traversing over strings of A and counting digits
    for (let i = 0; i < N; i++) {
        let x = A[i];
        while (x > 0) {
            let d = x % 10;
            count[d]++;
            x = Math.floor(x / 10);
            size[i]++;
        }
    }
 
    // Loop for traversing over strings of B[] and counting digits
    let ans = true;
    for (let i = 0; i < N; i++) {
        let x = B[i];
        while (x > 0) {
            let d = x % 10;
            count[d]--;
            x = Math.floor(x / 10);
            size[i]--;
        }
        if (size[i] !== 0)
            ans = false;
    }
 
    // Implementing the discussed idea and printing output
    if (!ans) {
        console.log("NO");
    } else {
        let ct = 0;
        for (let i = 0; i < 10; i++) {
            if (count[i] < 0)
                ct += Math.abs(count[i]);
        }
        if (ct <= K) {
            console.log("YES");
        } else {
            console.log("NO");
        }
    }
}
 
// Driver Function
function main() {
    // Inputs
    let N = 2;
    let K = 2;
    let A = [11, 1];
    let B = [1, 11];
 
    // Function call
    isPossible(N, K, A, B);
}
 
// Call the main function
main();
 
// This code is contributed by Abhinav Mahajan (abhinav_m22)


Output

NO

Time Complexity: O(N),N is the number of strings.
Auxiliary space: O(N), As frequency array used to store the frequency of digits.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads