The Wayback Machine - https://web.archive.org/web/20240927173948/https://www.geeksforgeeks.org/find-whether-possible-make-array-elements-using-one-external-number/
Open In App

Find whether it is possible to make array elements same using one external number

Last Updated : 02 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an Array, three operations can be performed using any external number x.

  1. Add x to an element once
  2. Subtract x from an element once
  3. Perform no operation on the element
    1. Count of unique elements is 1. Answer is YES with x = 0
    2. Count of unique elements is 2. Answer is YES with x = Difference of two unique elements.
    3. Count of unique elements is 3.
      • If difference between mid and max is same as difference between mid and min, answer is YES with x = difference between mid and max or mid and min.
      • Otherwise answer is NO.

In Python, we can quickly find unique elements using set in Python.

C++




// C++ Program to find an element X
// that can be used to operate on an array and
// get equal elements
 
#include<bits/stdc++.h>
using namespace std;
 
// Prints "YES" and an element x if we can
// equalize array using x. Else prints "NO"
void canEqualise(int array[], int n)
{
    // We all the unique elements (using set
    // function).
    set<int> s;
    for(int i=0;i<n;i++)
    {
        s.insert(array[i]);
    }
   
    // if there are only 1 or 2 unique elements,
    // then we can add or subtract x from one of them
    // to get the other element
    if(s.size() == 1)
        cout<<"YES " << "0";
    else if (s.size() == 2)
    {
        auto x = s.begin();
        s.erase(x);
        auto y = s.begin();
        s.erase(y);
       cout<<"YES " << (*y-*x);
    }
         
   
    // If count of unique elements is three, then
    // difference between the middle and minimum
    // should be same as difference between maximum
    // and middle
    else if (s.size() == 3)
    {
        auto x = s.begin();
        s.erase(x);
        auto y = s.begin();
        s.erase(y);
        auto z = s.begin();
        s.erase(z);
         
        if ((*z-*y)==(*y-*x))
            cout<<"YES " << (*z-*y);
        else
            cout<<"NO";
    }
         
   
    // if there are more than three unique elements, then
    // we cannot add or subtract the same value from all
    // the elements.
    else
        cout<<"NO";
         
}
   
// Driver code
int main()
{
    int array[] = {55, 52, 52, 49, 52};
    int n = sizeof(array) / sizeof(array[0]);
    canEqualise(array,n);
}
 
// This code is contributed by Aarti_Rathi


Java




// Java Program to find an element X
// that can be used to operate on an array and
// get equal elements
 
// Importing generic java libraries
import java.util.*;
 
public class GFG {
 
    // Prints "YES" and an element x if we can
    // equalize array using x. Else prints "NO"
    static void canEqualise(int array[], int n)
    {
        // We all the unique elements (using set
        // function).
        Set<Integer> s = new HashSet<Integer>();
        for (int i = 0; i < n; i++) {
            s.add(array[i]);
        }
 
        // if there are only 1 or 2 unique elements,
        // then we can add or subtract x from one of them
        // to get the other element
        if (s.size() == 1)
            System.out.println("YES 0");
        else if (s.size() == 2) {
            int x = s.stream().findFirst().get();
            s.remove(x);
            int y = s.stream().findFirst().get();
            s.remove(y);
            System.out.println("YES " + (y - x));
        }
 
        // If count of unique elements is three, then
        // difference between the middle and minimum
        // should be same as difference between maximum
        // and middle
        else if (s.size() == 3) {
            int x = s.stream().findFirst().get();
            s.remove(x);
            int y = s.stream().findFirst().get();
            s.remove(y);
            int z = s.stream().findFirst().get();
            s.remove(z);
 
            if ((z - y) == (y - x))
                System.out.println("YES " + (z - y));
            else
                System.out.println("NO");
        }
 
        // if there are more than three unique elements,
        // then we cannot add or subtract the same value
        // from all the elements.
        else
            System.out.println("NO");
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int array[] = { 55, 52, 52, 49, 52 };
        int n = array.length;
        canEqualise(array, n);
    }
}
 
// This code is contributed by Aarti_Rathi


Python




# Program in python 2.x to find an element X
# that can be used to operate on an array and
# get equal elements
   
# Prints "YES" and an element x if we can
# equalize array using x. Else prints "NO"
def canEqualise(array):
   
    # We all the unique elements (using set
    # function). Then we sort unique elements.
    uniques = sorted(set(array))
   
    # if there are only 1 or 2 unique elements,
    # then we can add or subtract x from one of them
    # to get the other element
    if len(uniques) == 1:
        print("YES " + "0")
    elif len(uniques) == 2:
        print("YES " + str(uniques[1] - uniques[0]))
   
    # If count of unique elements is three, then
    # difference between the middle and minimum
    # should be same as difference between maximum
    # and middle
    elif len(uniques) == 3:
        if uniques[2] - uniques[1] == uniques[1] - uniques[0]:
            X = uniques[2] - uniques[1]
            print("YES " + str(X))
        else:
            print("NO")
   
    # if there are more than three unique elements, then
    # we cannot add or subtract the same value from all
    # the elements.
    else:
        print("NO")
   
# Driver code
array = [55, 52, 52, 49, 52]
canEqualise(array)


C#




using System;
using System.Collections.Generic;
 
public static class GFG {
  // C# Program to find an element X
  // that can be used to operate on an array and
  // get equal elements
 
  // Prints "YES" and an element x if we can
  // equalize array using x. Else prints "NO"
  public static void canEqualise(int[] array, int n)
  {
    // We all the unique elements (using set
    // function).
    HashSet<int> s = new HashSet<int>();
    for (int i = 0; i < n; i++) {
      s.Add(array[i]);
    }
 
    // if there are only 1 or 2 unique elements,
    // then we can add or subtract x from one of them
    // to get the other element
    if (s.Count == 1) {
      Console.Write("YES ");
      Console.Write("0");
    }
    else if (s.Count == 2) {
      int x = 0;
      int y = 0;
      int m = 0;
      Console.Write("YES ");
      foreach(var i in s)
      {
        if (m == 0) {
          x = i;
        }
        else {
          y = i;
        }
        m++;
      }
      Console.Write((y - x));
    }
 
    // If count of unique elements is three, then
    // difference between the middle and minimum
    // should be same as difference between maximum
    // and middle
    else if (s.Count == 3) {
      int x = 0;
      int y = 0;
      int z = 0;
      int m = 0;
      foreach(var i in s)
      {
        if (m == 0) {
          x = i;
        }
        else if (m == 1) {
          y = i;
        }
        else {
          z = i;
        }
        m++;
      }
 
      if ((z - y) == (y - x)) {
        Console.Write("YES ");
        Console.Write((z - y));
      }
      else {
        Console.Write("NO");
      }
    }
 
    // if there are more than three unique elements,
    // then we cannot add or subtract the same value
    // from all the elements.
    else {
      Console.Write("NO");
    }
  }
 
  // Driver code
  public static void Main()
  {
    int[] array = { 55, 52, 52, 49, 52 };
    int n = array.Length;
    canEqualise(array, n);
  }
}
  // This code is contributed by Aarti_Rathi


Javascript




// JavaScript program to find an element X
// that can be used to operate on an array and
// get equal elements
function canEqualise(array, n) {
    // We find all the unique elements (using Set function)
    let s = new Set(array);
 
 
    // If there are only 1 or 2 unique elements,
    // then we can add or subtract x from one of them
    // to get the other element
    if (s.size === 1)
        console.log("YES 0");
    else if (s.size === 2) {
        let x = s.values().next().value;
        s.delete(x);
        let y = s.values().next().value;
        s.delete(y);
        console.log(`YES ${y-x}`);
    }
 
    // If count of unique elements is three, then
    // difference between the middle and minimum
    // should be same as difference between maximum
    // and middle
    else if (s.size === 3) {
        let x = s.values().next().value;
        s.delete(x);
        let y = s.values().next().value;
        s.delete(y);
        let z = s.values().next().value;
        s.delete(z);
 
        if ((z - y) === (y - x))
            console.log(`YES ${z-y}`);
        else
            console.log("NO");
    }
 
    // If there are more than three unique elements, then
    // we cannot add or subtract the same value from all
    // the elements.
    else
        console.log("NO");
}
 
// Driver code
let array = [55, 52, 52, 49, 52];
let n = array.length;
canEqualise(array, n);


OUTPUT

YES 3

Time Complexity: O(n logn)//we are running a for loop for n times and inside the loop the set insert operation is taking place which takes log n time to compute
Auxiliary space: O(n). //since we are using a set to store all the elements of the array

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.



Previous Article
Next Article

Similar Reads

Find whether it is possible to make array elements same using one external number | Set 2
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. The task is to check whether there exists a number X, such that if the above operations are performed
11 min read
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
Minimum increments to make all array elements equal with sum same as the given array after exactly one removal
Given an array arr[] of size N and an integer K, the task is to check if all array elements can be made equal by removing an array element and incrementing the value of all other array elements such that the total sum of the array elements remains the same. If found to be true, then print "YES". Otherwise, print "NO". Examples : Input: arr[] = { 2,
7 min read
Check if end of a sorted Array can be reached by repeated jumps of one more, one less or same number of indices as previous jump
Given a sorted array arr[] of size N, the task is to check if it is possible to reach the end of the given array from arr[1] by jumping either arr[i] + k - 1, arr[i] + k, or arr[i] + k + 1 in each move, where k represents the number of indices jumped in the previous move. Consider K = 1 initially. If it is possible, then print "Yes". Otherwise, pri
11 min read
Check whether two strings contain same characters in same order
Given two strings s1 and s2, the task is to find whether the two strings contain the same characters that occur in the same order. For example string "Geeks" and string "Geks" contain the same characters in same order. Examples: Input: s1 = "Geeks", s2 = "Geks" Output: Yes Input: s1 = "Arnab", s2 = "Andrew" Output: No Approach: We have two strings
9 min read
Check whether the cost of going from any node to any other node via all possible paths is same
Given adjacency list representation of a directed graph, the task is to check whether the cost of going from any vertex to any other vertex via all possible paths is equal or not. If there is a cost c for going from vertex A to vertex B, then the cost to travel from vertex B to vertex A will be -c. Examples: Input: arr[][] = {{0, 2, 0, 1}, {-2, 0,
9 min read
Check if possible to make Array sum equal to Array product by replacing exactly one element
Given an array arr[] consisting of N non-negative integers, the task is to check if it is possible to make the sum of the array equal to the product of the array element by replacing exactly one array element with any non-negative integer. Examples: Input: arr[] = {1, 3, 4}Output: YesExplanation:Replacing the last element of the array with 2 modifi
7 min read
Length of array pair formed where one contains all distinct elements and other all same elements
Given an array arr[], the task is to determine the maximum possible size of two arrays of the same size that can be created using the given array elements, such that in one array all the elements are distinct and in the other, all elements are the same. Note: It is not mandatory to use all the elements of the given array to build the two arrays. Ex
6 min read
Check if set of first X elements of one Array is same as set of first Y elements of other
Given two arrays arr1[] and arr2[] of size N each and an array Q[][2] consisting of M queries of the form [x, y], the task for each query is to check if the set of values contained from first x elements of arr1[] is equal to set of values from in first y elements of arr2[]. Note: Two sets are equal when they have all their distinct elements equal.
15+ min read
Maximum possible sum of a window in an array such that elements of same window in other array are unique
Given two arrays A and B of equal number of elements. The task is to find the maximum sum possible of a window in array B such that elements of same window in A[] are unique. Examples: Input: A = [0, 1, 2, 3, 0, 1, 4] B = [9, 8, 1, 2, 3, 4, 5] Output: sum = 20 The maximum sum possible in B[] such that all corresponding elements in A[] are unique is
10 min read
Find smallest possible Number from a given large Number with same count of digits
Given a number K of length N, the task is to find the smallest possible number that can be formed from K of N digits by swapping the digits any number of times. Examples: Input: N = 15, K = 325343273113434 Output: 112233333344457 Explanation: The smallest number possible after swapping the digits of the given number is 112233333344457 Input: N = 7,
5 min read
Maximum number of pairs of distinct array elements possible by including each element in only one pair
Given an array arr[] consisting of N integers, the task is to find the maximum number of pairs of array elements such that each pair has a different element and each array element can exist in only one pair Examples: Input: arr[] = {4, 5, 4, 5, 4}Output: 2Explanation:There can be 2 pairs forms from the given array i.e., {{4, 5}, {4, 5}}. Therefore,
12 min read
Check whether it is possible to make both arrays equal by modifying a single element
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. Ex
11 min read
Minimum number of swaps required to make parity of array elements same as their indices
Given an array arr[] consisting of N integers, the task is to find the minimum number of swaps required to make the parity (i.e., even or odd) of all array elements same as their respective indices. If it is not possible to do so, then print "-1". Examples: Input: arr[] = {3, 2, 7, 6}Output: 2Explanation:Swap {arr[0], arr[1]} and {arr[2], arr[3]}.
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 else print No.Examples: Input: arr[] = {18, 30, 54,
7 min read
Sum of array elements possible by appending arr[i] / K to the end of the array K times for array elements divisible by K
Given an array arr[] consisting of N integers and an integer K, the task is to find the sum of the array elements possible by traversing the array and adding arr[i] / K, K number of times at the end of the array, if arr[i] is divisible by K. Otherwise, stop the traversal. Examples: Input: arr[] = {4, 6, 8, 2}, K = 2Output: 44Explanation:The followi
14 min read
Minimize Array elements to be reduced to make subsequences sum 1 to Array max possible
Given an array a[] of positive integers. Subtract any positive integer from any number of elements of the array such that there exists every possible subsequence with sum 1 to s, where s denotes the sum of all the elements of the array. Find the minimum possible number of the array element to be subtracted. Input: a[] = {4, 3, 2, 2, 1, 6}Output: 2E
6 min read
Rearrange Linked List to make XOR of nodes at same distance from start and end same
Given a linked list containing N nodes of binary numbers, the task is to check whether it is possible to rearrange the linked list in such a way that value of XOR between element at ith Node and N+1−ith node is the same for all 1 ≤ i ≤ N. Print Yes, if the Linked List can be rearranged, or else print No. Examples: Input: LL = 0 -> 0 -> 1Outpu
8 min read
Largest even number possible by using one swap operation in given number
Given an odd number in the form of a string, the task is to make the largest even number from the given number, and you are allowed to do only one swap operation. Examples : Input: 1235785Output: 1535782Explanation: Swap 2 and 5. Input: 536425Output: 536524Explanation: Swap 4 and 5 to make the largest even number. Recommended PracticeOdd to EvenTry
6 min read
Count of all possible pairs of array elements with same parity
Given an array A[] of integers, the task is to find the total number of pairs such that each pair contains either both even or both odd elements. A valid pair (A[ i ], A[ j ]) can only be formed if i != j. Examples: Input: A[ ] = {1, 2, 3, 1, 3} Output: 6 Explanation: Possible odd pairs = (1, 3), (1, 1), (1, 3), (3, 1), (3, 3), (1, 3) = 6 Possible
7 min read
Maximize Sum possible by subtracting same value from all elements of a Subarray of the given Array
Given an array a[] consisting of N integers, the task is to find the maximum possible sum that can be achieved by deducting any value, say X, from all elements of a subarray. Examples: Input: N = 3, a[] = {80, 48, 82} Output: 144 Explanation: 48 can be deducted from each array element. Therefore, sum obtained = 48 * 3 = 144Input: N = a[] = {8, 40,
11 min read
Check if it is possible to make x and y zero at same time with given operation
Given two numbers X and Y. The task is to check whether X and Y can be reduced to zero at the same time by performing the following operation any number of times: Choose any natural number (say z) and reduce X and Y as one of the following at each operation: X = X - z and Y = Y - 2*zX = X - 2*z and Y = Y - z Example: Input: X = 6, Y = 9 Output: YES
5 min read
Count number of ways array can be partitioned such that same numbers are present in same subarray
Given an array A[] of size N. The Task for this problem is to count several ways to partition the given array A[] into continuous subarrays such that the same integers are not present in different subarrays. Print the answer modulo 109 + 7. Examples: Input: A[] = {1, 2, 1, 3} Output: 2Explanation: There are two ways to break above array such that i
11 min read
Minimum operations in a binary matrix to make it same as initial one
Given a square binary matrix[][] of size n*n. Find the minimum number of operations (changes) needed in a binary matrix to make it the same as the initial one after rotating 0, 90, 180 and 270 degrees. In one operation, You can choose an element of the matrix and change it from 0 to 1 or from 1 to 0. Examples: Input: N = 3, mat[][] = {{1, 1, 0}, {1
8 min read
Make all array elements equal by reducing array elements to half minimum number of times
Given an array arr[] consisting of N integers, the task is to minimize the number of operations required to make all array elements equal by converting Ai to Ai / 2. in each operation Examples: Input: arr[] = {3, 1, 1, 3}Output: 2Explanation: Reducing A0 to A0 / 2 modifies arr[] to {1, 1, 1, 3}. Reducing A3 to A3 / 2 modifies arr[] to {1, 1, 1, 1}.
6 min read
Minimum number of bits of array elements required to be flipped to make all array elements equal
Given an array arr[] consisting of N positive integers, the task is to find the minimum number of bits of array elements required to be flipped to make all array elements equal. Examples: Input: arr[] = {3, 5}Output: 2Explanation:Following are the flipping of bits of the array elements required: For element arr[0](= 3): Flipping the 3rd bit from th
7 min read
Find all possible original Arrays using given Difference Array and range of array elements
Given an array arr[] of size N that contains the differences between the adjacents elements of an array. The task is to generate all possible arrays such that all the elements of the array lie in the range [L, R]. Examples: Input: arr[] = {1, -3, 4}, L = 1, R = 6Output: {3, 4, 1, 5}, {4, 5, 2, 6}Explanation: These two are the only possible sequence
6 min read
Find the angle between tangents drawn from a given external point to a Circle
Given a positive integer R representing the radius of the circle and the center of the circle (X1, Y1) and another point (X2, Y2) in the cartesian plane, the task is to find the angle between the pair of tangents drawn from the point (X2, Y2) to the circle. Examples: Input: R = 6, (X1, Y1) = (5, 1), (X2, Y2) = (6, 9)Output: 96.1851 Input: R = 4, (X
7 min read
Check whether an array can be fit into another array rearranging the elements in the array
Given two arrays A and B of the same size N. Check whether array A can be fit into array B. An array is said to fit into another array if by arranging the elements of both arrays, there exists a solution such that the ith element of the first array is less than or equal to ith element of the second array. Examples: Input : A[] = { 7, 5, 3, 2 }, B[]
6 min read
Possible to make a divisible by 3 number using all digits in an array
Given an array of integers, the task is to find whether it's possible to construct an integer using all the digits of these numbers such that it would be divisible by 3. If it is possible then print "Yes" and if not print "No". Examples: Input : arr[] = {40, 50, 90} Output : Yes We can construct a number which is divisible by 3, for example 945000.
4 min read
Article Tags :
Practice Tags :