Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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.



Last Updated : 02 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads