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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Find if it is possible to make all elements of an array equal by the given operations
Next article icon

Check whether it is possible to make both arrays equal by modifying a single element

Last Updated : 05 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two sequences of integers ‘A’ and ‘B’, and an integer ‘k’. The task is to check if we can make both sequences equal by modifying any one element from the sequence A in the following way: 
We can add any number from the range [-k, k] to any element of A. This operation must only be performed once. Print Yes if it is possible or No otherwise.

Examples: 

Input: K = 2, A[] = {1, 2, 3}, B[] = {3, 2, 1} 
Output: Yes 
0 can be added to any element and both the sequences will be equal.

Input: K = 4, A[] = {1, 5}, B[] = {1, 1} 
Output: Yes 
-4 can be added to 5 then the sequence A becomes {1, 1} which is equal to the sequence B. 

Approach: Notice that to make both the sequence equal with just one move there has to be only one mismatching element in both the sequences and the absolute difference between them must be less than or equal to ‘k’. 

  • Sort both the arrays and look for the mismatching elements.
  • If there are more than one mismatch elements then print ‘No’
  • Else, find the absolute difference between the elements.
  • If the difference <= k then print ‘Yes’ else print ‘No’.

Below is the implementation of the above approach: 

C++
// C++ implementation of the above approach #include<bits/stdc++.h> using namespace std;  // Function to check if both  // sequences can be made equal  static bool check(int n, int k,                      int *a, int *b)  {     // Sorting both the arrays      sort(a,a+n);     sort(b,b+n);      // Flag to tell if there are      // more than one mismatch      bool fl = false;      // To stores the index      // of mismatched element      int ind = -1;     for (int i = 0; i < n; i++)      {         if (a[i] != b[i])         {              // If there is more than one              // mismatch then return False              if (fl == true)              {                 return false;             }             fl = true;             ind = i;         }     }              // If there is no mismatch or the      // difference between the      // mismatching elements is <= k      // then return true      if (ind == -1 | abs(a[ind] - b[ind]) <= k)     {         return true;     }     return false;  }  // Driver code int main() {     int n = 2, k = 4;     int a[] = {1, 5};     int b[] = {1, 1};     if (check(n, k, a, b))      {         printf("Yes");     }     else     {         printf("No");     }     return 0; }  // This code is contributed by mits 
Java
// Java implementation of the above approach import java.util.Arrays; class GFG  {      // Function to check if both      // sequences can be made equal      static boolean check(int n, int k,                          int[] a, int[] b)      {          // Sorting both the arrays          Arrays.sort(a);         Arrays.sort(b);          // Flag to tell if there are          // more than one mismatch          boolean fl = false;          // To stores the index          // of mismatched element          int ind = -1;         for (int i = 0; i < n; i++)          {             if (a[i] != b[i])             {                  // If there is more than one                  // mismatch then return False                  if (fl == true)                  {                     return false;                 }                 fl = true;                 ind = i;             }         }                  // If there is no mismatch or the          // difference between the          // mismatching elements is <= k          // then return true          if (ind == -1 | Math.abs(a[ind] - b[ind]) <= k)         {             return true;         }         return false;      }      // Driver code     public static void main(String[] args)     {         int n = 2, k = 4;         int[] a = {1, 5};         int b[] = {1, 1};         if (check(n, k, a, b))          {             System.out.println("Yes");         }         else          {             System.out.println("No");         }     } }   // This code is contributed by 29AjayKumar 
Python
# Python implementation of the above approach  # Function to check if both  # sequences can be made equal def check(n, k, a, b):      # Sorting both the arrays     a.sort()     b.sort()      # Flag to tell if there are     # more than one mismatch     fl = False      # To stores the index      # of mismatched element     ind = -1     for i in range(n):         if(a[i] != b[i]):              # If there is more than one             # mismatch then return False             if(fl == True):                 return False             fl = True             ind = i      # If there is no mismatch or the      # difference between the      # mismatching elements is <= k     # then return true     if(ind == -1 or abs(a[ind]-b[ind]) <= k):         return True     return False  n, k = 2, 4 a =[1, 5] b =[1, 1] if(check(n, k, a, b)):     print("Yes") else:     print("No") 
C#
// C# implementation of the above approach using System;  class GFG  {      // Function to check if both      // sequences can be made equal      static bool check(int n, int k,                          int[] a, int[] b)      {          // Sorting both the arrays          Array.Sort(a);         Array.Sort(b);          // Flag to tell if there are          // more than one mismatch          bool fl = false;          // To stores the index          // of mismatched element          int ind = -1;         for (int i = 0; i < n; i++)          {             if (a[i] != b[i])             {                  // If there is more than one                  // mismatch then return False                  if (fl == true)                  {                     return false;                 }                 fl = true;                 ind = i;             }         }                  // If there is no mismatch or the          // difference between the          // mismatching elements is <= k          // then return true          if (ind == -1 | Math.Abs(a[ind] - b[ind]) <= k)         {             return true;         }         return false;     }      // Driver code     public static void Main()     {         int n = 2, k = 4;         int[] a = {1, 5};         int[] b = {1, 1};         if (check(n, k, a, b))          {             Console.WriteLine("Yes");         }         else         {             Console.WriteLine("No");         }     } }  // This code is contributed by Rajput-Ji 
JavaScript
<script>  // Javascript Implementation of above approach.       // Function to check if both      // sequences can be made equal      function check(n, k, a, b)      {            // Sorting both the arrays          a.sort();         b.sort();            // Flag to tell if there are          // more than one mismatch          let fl = false;            // To stores the index          // of mismatched element          let ind = -1;         for (let i = 0; i < n; i++)          {             if (a[i] != b[i])             {                    // If there is more than one                  // mismatch then return False                  if (fl == true)                  {                     return false;                 }                 fl = true;                 ind = i;             }         }                    // If there is no mismatch or the          // difference between the          // mismatching elements is <= k          // then return true          if (ind == -1 | Math.abs(a[ind] - b[ind]) <= k)         {             return true;         }         return false;        }          // Driver code       let n = 2, k = 4;         let a = [1, 5];         let b = [1, 1];         if (check(n, k, a, b))          {             document.write("Yes");         }         else          {             document.write("No");         }         </script> 
PHP
<?php  // PHP implementation of the  // above approach  // Function to check if both  // sequences can be made equal function check($n, $k, &$a, &$b) {      // Sorting both the arrays     sort($a);     sort($b);      // Flag to tell if there are     // more than one mismatch     $fl = False;      // To stores the index      // of mismatched element     $ind = -1;     for ($i = 0; $i < $n; $i++)     {         if($a[$i] != $b[$i])         {              // If there is more than one             // mismatch then return False             if($fl == True)                 return False;             $fl = True;             $ind = $i;         }     }      // If there is no mismatch or the      // difference between the      // mismatching elements is <= k     // then return true     if($ind == -1 || abs($a[$ind] -                           $b[$ind]) <= $k)         return True;     return False;      }  // Driver Code $n = 2; $k = 4; $a = array(1, 5); $b = array(1, 1); if(check($n, $k, $a, $b))     echo "Yes"; else     echo "No";      // This code is contributed by ita_c ?> 

Output
Yes

Complexity Analysis:

  • Time Complexity: O(nlog(n))
  • Auxiliary Space: O(1)

Approach: Hash Map 

Steps:

  • Initialize an empty hash map, freqMap.
  • Iterate over each element in sequence A and update the frequencies of elements in freqMap.
  • Iterate over each element in sequence B and decrement the frequencies of elements in freqMap.
  • If all frequencies in freqMap are 0 or within the range [-k, k], print “Yes”. 
  • Otherwise, print “No”.

Below is the implementation of the above approach: 

C++
// C++ implementation of the above approach #include <iostream> #include <unordered_map> #include <vector>  using namespace std;  bool makeSequencesEqual(int k, const vector<int>& A,                         const vector<int>& B) {     unordered_map<int, int> freqMap;      // Update frequencies for sequence A     for (int num : A) {         freqMap[num]++;     }      // Decrement frequencies for sequence B     for (int num : B) {         freqMap[num]--;     }      for (const auto& pair : freqMap) {         int num = pair.first;         int freq = pair.second;          // Check if frequencies are within the range [-k, k]         if (freq != 0 && abs(freq) > k) {             return false;         }     }      return true; }  // Driver Code int main() {     int k = 2;     vector<int> A = { 1, 2, 3 };     vector<int> B = { 3, 2, 1 };      // Check if sequences can be made equal     if (makeSequencesEqual(k, A, B)) {         cout << "Yes" << endl;     }     else {         cout << "No" << endl;     }      return 0; } 
Java
// Java implementation of the above approach import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.List;  public class GFG {          public static boolean makeSequencesEqual(int k, List<Integer> A, List<Integer> B) {         Map<Integer, Integer> freqMap = new HashMap<>();          // Update frequencies for sequence A         for (int num : A) {             freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);         }          // Decrement frequencies for sequence B         for (int num : B) {             freqMap.put(num, freqMap.getOrDefault(num, 0) - 1);         }          for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {             int num = entry.getKey();             int freq = entry.getValue();              // Check if frequencies are within the range [-k, k]             if (freq != 0 && Math.abs(freq) > k) {                 return false;             }         }          return true;     }      // Driver Code     public static void main(String[] args) {         int k = 2;         List<Integer> A = new ArrayList<>();         A.add(1);         A.add(2);         A.add(3);         List<Integer> B = new ArrayList<>();         B.add(3);         B.add(2);         B.add(1);          // Check if sequences can be made equal         if (makeSequencesEqual(k, A, B)) {             System.out.println("Yes");         } else {             System.out.println("No");         }     } }  // This code is contributed by Vaibhav Nandan 
Python
def make_sequences_equal(k, A, B):     freq_map = {}      # Update frequencies for sequence A     for num in A:         freq_map[num] = freq_map.get(num, 0) + 1      # Decrement frequencies for sequence B     for num in B:         freq_map[num] = freq_map.get(num, 0) - 1      for num, freq in freq_map.items():         # Check if frequencies are within the range [-k, k]         if freq != 0 and abs(freq) > k:             return False      return True   # Driver Code if __name__ == "__main__":     k = 2     A = [1, 2, 3]     B = [3, 2, 1]      # Check if sequences can be made equal     if make_sequences_equal(k, A, B):         print("Yes")     else:         print("No") 
C#
using System; using System.Collections.Generic;  class GFG {     static bool MakeSequencesEqual(int k, List<int> A,                                    List<int> B)     {         Dictionary<int, int> freqMap             = new Dictionary<int, int>();          // Update frequencies for sequence A         foreach(int num in A)         {             if (freqMap.ContainsKey(num))                 freqMap[num]++;             else                 freqMap[num] = 1;         }          // Decrement frequencies for sequence B         foreach(int num in B)         {             if (freqMap.ContainsKey(num))                 freqMap[num]--;             else                 freqMap[num] = -1;         }          foreach(KeyValuePair<int, int> pair in freqMap)         {             int num = pair.Key;             int freq = pair.Value;              // Check if frequencies are within the range             // [-k, k]             if (freq != 0 && Math.Abs(freq) > k) {                 return false;             }         }          return true;     }      // Driver Code     static void Main()     {         int k = 2;         List<int> A = new List<int>() { 1, 2, 3 };         List<int> B = new List<int>() { 3, 2, 1 };          // Check if sequences can be made equal         if (MakeSequencesEqual(k, A, B)) {             Console.WriteLine("Yes");         }         else {             Console.WriteLine("No");         }     } } 
JavaScript
function makeSequencesEqual(k, A, B) {     const freqMap = new Map();      // Update frequencies for sequence A     for (let num of A) {         freqMap.set(num, (freqMap.get(num) || 0) + 1);     }      // Decrement frequencies for sequence B     for (let num of B) {         freqMap.set(num, (freqMap.get(num) || 0) - 1);     }      for (let [num, freq] of freqMap) {         // Check if frequencies are within the range [-k, k]         if (freq !== 0 && Math.abs(freq) > k) {             return false;         }     }      return true; }  // Driver Code     const k = 2;     const A = [1, 2, 3];     const B = [3, 2, 1];      // Check if sequences can be made equal     if (makeSequencesEqual(k, A, B)) {         console.log("Yes");     } else {         console.log("No");     } 

Output
Yes

Time Complexity: O(n), where n is the total number of elements in sequences A and B.

Auxiliary Space: O(m), where m is the number of unique elements in sequences A and B. 



Next Article
Find if it is possible to make all elements of an array equal by the given operations

I

indrajit1
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Python
  • Sorting
Practice Tags :
  • Arrays
  • Greedy
  • python
  • Sorting

Similar Reads

  • Check if it is possible to make array equal by doubling or tripling
    Given an array of n elements.You can double or triple the elements in the array any number of times. After all the operations check whether it is possible to make all elements in the array equal. Examples : Input : A[] = {75, 150, 75, 50} Output : Yes Explanation : Here, 75 should be doubled twice a
    6 min read
  • Find if it is possible to make all elements of an array equal by the given operations
    Given an array arr[], the task is to make all the array elements equal with the given operation. In a single operation, any element of the array can be either multiplied by 3 or by 5 any number of times. If it's possible to make all the array elements equal with the given operation then print Yes el
    7 min read
  • Check if Arrays can be made equal by Replacing elements with their number of Digits
    Given two arrays A[] and B[] of length N, the task is to check if both arrays can be made equal by performing the following operation at most K times: Choose any index i and either change Ai to the number of digits Ai have or change Bi to the number of digits Bi have. Examples: Input: N = 4, K = 1,
    10 min read
  • Check if it is possible to make all strings of A[] equal to B[] using given operations
    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 opera
    9 min read
  • Check if Array Elemnts can be Made Equal with Given Operations
    Given an array arr[] consisting of N integers and following are the three operations that can be performed using any external number X. Add X to an array element once.Subtract X from an array element once.Perform no operation on the array element.Note : Only one operation can be performed on a numbe
    6 min read
  • Count of operations to make all elements of array a[] equal to its min element by performing a[i] – b[i]
    Given two array a[] and b[] of size N, the task is to print the count of operations required to make all the elements of array a[i] equal to its minimum element by performing a[i] - b[i] where its always a[i] >= b[i]. If it is not possible then return -1.Example: Input: a[] = {5, 7, 10, 5, 15} b[
    9 min read
  • Check whether two strings can be made equal by increasing prefixes
    In this problem we have to check. whether two strings can be made equal by increasing the ASCII value of characters of the prefix of first string. We can increase different prefixes multiple times. The strings consists of only lowercase alphabets and does not contain any special characters . Example
    9 min read
  • Minimum changes required to make all element in an array equal
    Given an array of length N, the task is to find minimum operation required to make all elements in the array equal. Operation is as follows: Replace the value of one element of the array by one of its adjacent elements. Examples: Input: N = 4, arr[] = {2, 3, 3, 4} Output: 2 Explanation: Replace 2 an
    5 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
    8 min read
  • Minimum Bitwise AND operations to make any two array elements equal
    Given an array of integers of size 'n' and an integer 'k', We can perform the Bitwise AND operation between any array element and 'k' any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make an
    10 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