Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Minimize increment/decrement of Array elements to make each modulo K equal
Next article icon

Smallest number to be added in first Array modulo M to make frequencies of both Arrays equal

Last Updated : 17 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays A[] and B[] consisting of N positive integers and an integer M, the task is to find the minimum value of X such that operation (A[i] + X) % M performed on every element of array A[] results in the formation of an array with frequency of elements same as that in another given array B[].

Examples: 

Input: N = 4, M = 3, A[] = {0, 0, 2, 1}, B[] = {2, 0, 1, 1} 
Output: 1 
Explanation: 
Modifying the given array A[] to { (0+1)%3, (0+1)%3, (2+1)%3, (1+1)%3 } 
= { 1%3, 1%3, 3%3, 2%3 }, 
= { 1, 1, 0, 2 }, which is equivalent to B[] in terms of frequency of distinct elements.

Input: N = 5, M = 10, A[] = {0, 0, 0, 1, 2}, B[] = {2, 1, 0, 0, 0} 
Output: 0 
Explanation: 
Frequency of elements in both the arrays are already equal.

Approach: This problem can be solved by using Greedy Approach. Follow the steps below: 

  • There will be at least one possible value of X such that for every index i, ( A[i] + X ) % M = B[0].
  • Find all the possible values of X that convert each element of A[] to the first element of B[].
  • Check whether these possible X values satisfy the other remaining values of B[].
  • If there are multiple answers, take the minimum value of X.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Utility function to find
// the answer
int moduloEquality(int A[], int B[],
                   int n, int m)
{
 
    // Stores the frequencies of
    // array elements
    map<int, int> mapA, mapB;
 
    for (int i = 0; i < n; i++) {
        mapA[A[i]]++;
        mapB[B[i]]++;
    }
 
    // Stores the possible values
    // of X
    set<int> possibleValues;
 
    int FirstElement = B[0];
    for (int i = 0; i < n; i++) {
        int cur = A[i];
 
        // Generate possible positive
        // values of X
        possibleValues
            .insert(
                cur > FirstElement
                    ? m - cur + FirstElement
                    : FirstElement - cur);
    }
 
    // Initialize answer
    // to MAX value
    int ans = INT_MAX;
 
    for (auto it :
         possibleValues) {
 
        // Flag to check if the
        // current element of the
        // set can be considered
        bool possible = true;
 
        for (auto it2 : mapA) {
 
            // If the frequency of an element
            // in A[] is not equal to that
            // in B[] after the operation
            if (it2.second
                != mapB[(it2.first + it) % m]) {
 
                // Current set element
                // cannot be considered
                possible = false;
                break;
            }
        }
 
        // Update minimum value of X
        if (possible) {
            ans = min(ans, it);
        }
    }
    return ans;
}
 
// Driver Code
int main()
{
    int n = 4;
    int m = 3;
 
    int A[] = { 0, 0, 2, 1 };
    int B[] = { 2, 0, 1, 1 };
 
    cout << moduloEquality(A, B, n, m)
         << endl;
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Utility function to find
// the answer
static int moduloEquality(int A[], int B[],
                          int n, int m)
{
     
    // Stores the frequencies of
    // array elements
    HashMap<Integer,
            Integer> mapA = new HashMap<Integer,
                                        Integer>();
    HashMap<Integer,
            Integer> mapB = new HashMap<Integer,
                                        Integer>();
 
    for(int i = 0; i < n; i++)
    {
        if (mapA.containsKey(A[i]))
        {
            mapA.put(A[i], mapA.get(A[i]) + 1);
        }
        else
        {
            mapA.put(A[i], 1);
        }
        if (mapB.containsKey(B[i]))
        {
            mapB.put(B[i], mapB.get(B[i]) + 1);
        }
        else
        {
            mapB.put(B[i], 1);
        }
    }
 
    // Stores the possible values
    // of X
    HashSet<Integer> possibleValues = new HashSet<Integer>();
 
    int FirstElement = B[0];
    for(int i = 0; i < n; i++)
    {
        int cur = A[i];
 
        // Generate possible positive
        // values of X
        possibleValues.add(cur > FirstElement ?
                       m - cur + FirstElement :
                  FirstElement - cur);
    }
 
    // Initialize answer
    // to MAX value
    int ans = Integer.MAX_VALUE;
 
    for(int it : possibleValues)
    {
         
        // Flag to check if the
        // current element of the
        // set can be considered
        boolean possible = true;
 
        for(Map.Entry<Integer,
                      Integer> it2 : mapA.entrySet())
        {
             
            // If the frequency of an element
            // in A[] is not equal to that
            // in B[] after the operation
            if (it2.getValue() !=
                mapB.get((it2.getKey() + it) % m))
            {
                 
                // Current set element
                // cannot be considered
                possible = false;
                break;
            }
        }
 
        // Update minimum value of X
        if (possible)
        {
            ans = Math.min(ans, it);
        }
    }
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 4;
    int m = 3;
 
    int A[] = { 0, 0, 2, 1 };
    int B[] = { 2, 0, 1, 1 };
 
    System.out.print(moduloEquality(A, B, n, m) + "\n");
}
}
 
// This code is contributed by Amit Katiyar
 
 

Python3




# Python3 program for the above approach
import sys
from collections import defaultdict
 
# Utility function to find
# the answer
def moduloEquality(A, B, n, m):
 
    # Stores the frequencies of
    # array elements
    mapA = defaultdict(int)
    mapB = defaultdict(int)
 
    for i in range(n):
        mapA[A[i]] += 1
        mapB[B[i]] += 1
 
    # Stores the possible values
    # of X
    possibleValues = set()
 
    FirstElement = B[0]
    for i in range(n):
        cur = A[i]
 
        # Generate possible positive
        # values of X
        if cur > FirstElement:
            possibleValues.add(m - cur + FirstElement)
        else:
            possibleValues.add(FirstElement - cur)
 
    # Initialize answer
    # to MAX value
    ans = sys.maxsize
 
    for it in possibleValues:
 
        # Flag to check if the
        # current element of the
        # set can be considered
        possible = True
 
        for it2 in mapA:
 
            # If the frequency of an element
            # in A[] is not equal to that
            # in B[] after the operation
            if (mapA[it2] !=
                mapB[(it2 + it) % m]):
 
                # Current set element
                # cannot be considered
                possible = False
                break
 
        # Update minimum value of X
        if (possible):
            ans = min(ans, it)
             
    return ans
 
# Driver Code
if __name__ == "__main__":
     
    n = 4
    m = 3
 
    A = [ 0, 0, 2, 1 ]
    B = [ 2, 0, 1, 1 ]
 
    print(moduloEquality(A, B, n, m))
 
# This code is contributed by chitranayal
 
 

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Utility function to find
// the answer
static int moduloEquality(int[] A, int[] B,
                          int n, int m)
{
     
    // Stores the frequencies of
    // array elements
    Dictionary<int,
               int> mapA = new Dictionary<int,
                                          int>();
                    
    Dictionary<int,
               int> mapB = new Dictionary<int,
                                          int>();
  
    for(int i = 0; i < n; i++)
    {
        if (mapA.ContainsKey(A[i]))
        {
            mapA[A[i]] = mapA[A[i]] + 1;
        }
        else
        {
            mapA.Add(A[i], 1);
        }
        if (mapB.ContainsKey(B[i]))
        {
            mapB[B[i]] = mapB[B[i]] + 1;
        }
        else
        {
            mapB.Add(B[i], 1);
        }
    }
  
    // Stores the possible values
    // of X
    HashSet<int> possibleValues = new HashSet<int>();
  
    int FirstElement = B[0];
    for(int i = 0; i < n; i++)
    {
        int cur = A[i];
  
        // Generate possible positive
        // values of X
        possibleValues.Add(cur > FirstElement ?
                       m - cur + FirstElement :
                  FirstElement - cur);
    }
  
    // Initialize answer
    // to MAX value
    int ans = Int32.MaxValue;
    
    foreach(int it in possibleValues)
    {
          
        // Flag to check if the
        // current element of the
        // set can be considered
        bool possible = true;
         
        foreach(KeyValuePair<int, int> it2 in mapA)
        {
              
            // If the frequency of an element
            // in A[] is not equal to that
            // in B[] after the operation
            if (it2.Value != mapB[(it2.Key + it) % m])
            {
                  
                // Current set element
                // cannot be considered
                possible = false;
                break;
            }
        }
  
        // Update minimum value of X
        if (possible)
        {
            ans = Math.Min(ans, it);
        }
    }
    return ans;
}
 
// Driver code
static void Main()
{
    int n = 4;
    int m = 3;
  
    int[] A = { 0, 0, 2, 1 };
    int[] B = { 2, 0, 1, 1 };
   
    Console.WriteLine(moduloEquality(A, B, n, m));
}
}
 
// This code is contributed by divyeshrabadiya07
 
 

Javascript




<script>
 
// JavaScript program for the above approach
 
// Utility function to find
// the answer
function moduloEquality(A, B, n, m)
{
 
    // Stores the frequencies of
    // array elements
    var mapA = new Map(), mapB = new Map();
 
    for (var i = 0; i < n; i++) {
        if(mapA.has(A[i]))
            mapA.set(A[i], mapA.get(A[i])+1)
        else
            mapA.set(A[i], 1)
 
        if(mapB.has(B[i]))
            mapB.set(B[i], mapB.get(B[i])+1)
        else
            mapB.set(B[i], 1)
 
    }
 
    // Stores the possible values
    // of X
    var possibleValues = new Set();
 
    var FirstElement = B[0];
    for (var i = 0; i < n; i++) {
        var cur = A[i];
 
        // Generate possible positive
        // values of X
        possibleValues
            .add(
                cur > FirstElement
                    ? m - cur + FirstElement
                    : FirstElement - cur);
    }
 
    // Initialize answer
    // to MAX value
    var ans = 1000000000;
 
    possibleValues.forEach(it => {
     
 
        // Flag to check if the
        // current element of the
        // set can be considered
        var possible = true;
 
        mapA.forEach((value, key) => {
         
 
            // If the frequency of an element
            // in A[] is not equal to that
            // in B[] after the operation
            if (value
                != mapB.get((key + it) % m)) {
 
                // Current set element
                // cannot be considered
                possible = false;
            }
        });
 
        // Update minimum value of X
        if (possible) {
            ans = Math.min(ans, it);
        }
    });
    return ans;
}
 
// Driver Code
var n = 4;
var m = 3;
var A = [0, 0, 2, 1];
var B = [2, 0, 1, 1];
document.write( moduloEquality(A, B, n, m));
 
 
</script>
 
 
Output: 
1

 

Time Complexity: O(N2) 
Auxiliary Space: O(N)
 



Next Article
Minimize increment/decrement of Array elements to make each modulo K equal

G

gauravak007
Improve
Article Tags :
  • Algorithms
  • Arrays
  • C++ Programs
  • DSA
  • Greedy
  • Hash
  • Mathematical
  • cpp-map
  • cpp-set
  • frequency-counting
  • Modular Arithmetic
Practice Tags :
  • Algorithms
  • Arrays
  • Greedy
  • Hash
  • Mathematical
  • Modular Arithmetic

Similar Reads

  • Minimize insertions and deletions in given array A[] to make it identical to array B[]
    Given two arrays A[] and B[] of length N and M respectively, the task is to find the minimum number of insertions and deletions on the array A[], required to make both the arrays identical.Note: Array B[] is sorted and all its elements are distinct, operations can be performed at any index not neces
    15+ min read
  • C++ Program for Frequencies of even and odd numbers in a matrix
    Given a matrix of order m*n then the task is to find the frequency of even and odd numbers in the matrix Examples: Input : m = 3, n = 3 { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } Output : Frequency of odd number = 5 Frequency of even number = 4 Input : m = 3, n = 3 { 10, 11, 12 }, { 13, 14, 15 }, { 16, 1
    3 min read
  • Digits of element wise sum of two arrays into a new array
    Given two arrays of positive integers A and B of sizes M and N respectively, the task is to push A[i] + B[i] into a new array for every i = 0 to min(M, N) and print the newly generated array in the end. If the sum is a two-digit number then break the digits into two elements i.e. every element of th
    8 min read
  • Minimize increment/decrement of Array elements to make each modulo K equal
    Given an array arr[] of length N and an integer K. In each operation any element(say arr[i]) can be selected from the array and can be changed to arr[i] + 1 or arr[i] - 1. The task is to find the minimum number of operations required to perform on the array such that each value of the array modulo K
    10 min read
  • C++ Program to check if two Arrays are Equal or not
    Given two arrays arr1[] and arr2[] of length N and M respectively, the task is to check if the two arrays are equal or not. Note: Arrays are said to be equal if and only if both arrays contain the same elements and the frequencies of each element in both arrays are the same. Examples: Input: arr1[]
    4 min read
  • Minimum elements to be added so that two matrices can be multiplied
    Given two matrices A and B of order p x q (or q X p) and r x s ( or s X r). The task is to find the minimum number of elements to be added to any of the two matrices to make them multiplicative. Two matrices are multiplicative if the number of columns in one matrix is equal to the number of rows in
    8 min read
  • C++ Program to Find the Frequency of Elements in an Array
    In C++, arrays are a type of data structure that can store a fixed-size sequential collection of elements of the same type. In this article, we will learn how to find the frequency of elements in an array in C++. Example: Input: Array: {1, 2, 3, 4, 2, 1, 3, 2, 4, 5} Output: Element: 1, Frequency: 2
    2 min read
  • Count common elements in two arrays containing multiples of N and M
    Given two arrays such that the first array contains multiples of an integer n which are less than or equal to k and similarly, the second array contains multiples of an integer m which are less than or equal to k.The task is to find the number of common elements between the arrays.Examples: Input :n
    4 min read
  • Count numbers whose maximum sum of distinct digit-sum is less than or equals M
    Given an array of integers arr[] and a number M, the task is to find the maximum count of the numbers whose sum of distinct digit-sum is less than or equal to the given number M. Examples: Input: arr[] = {1, 45, 16, 17, 219, 32, 22}, M = 10 Output: 3 Explanation: Digit-sum of the Array is - {1, 9, 7
    9 min read
  • Concatenate Two int Arrays into One Larger Array in C++
    In C++, an array is a linear data structure we use to store data in contiguous order. It helps to efficiently access any element in O(1) time complexity using its index. In this article, we will learn how to concatenate two integer arrays into one larger array in C++. Example: Input: arr1: {1, 2, 3,
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences