VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-distinct-elements-in-array-after-replacing-arri-with-arri-modulo-x/

⇱ Minimize distinct elements in Array after replacing arr[i] with arr[i] modulo X - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize distinct elements in Array after replacing arr[i] with arr[i] modulo X

Last Updated : 14 Oct, 2022

Given an array arr[] of size N, the task is to minimize the number of distinct elements in the array after performing the following operation once:

  • Choose an integer X and replace each element of the array with the remainder when arr[i] is divided by X (i.e., arr[i]%X).

Examples:

Input: N = 5, arr[] = {5, 10, 20, 35, 15}
Output: 1
Explanation: Lets take X = 5. On replacing each element 
as mentioned above we get arr = {0, 0, 0, 0, 0}. 
Now this array has only one distinct element (0).

Input: N = 4, arr[] = {1, 4, 8}
Output: 2

Approach: To solve the problem follow the below observation:

The answer would be at - most 2. 

This would be the case when we choose X = 2. The final array will contain only either 0 (for even numbers) or 1 (for odd numbers). 

So, now the task is to check for the condition when the answer would be 1.

We want to find X, such that A[1] % X = A[2] % X, A[2] % X = A[3] % X, and so on for the whole array.
Therefore, (A[1] - A[2]) % X = 0 and (A[2] - A[3]) % X = 0 and so on for the whole array.
Therefore, we need to find an X, such that all the consecutive differences are divisible by it. 

So, the following steps can be followed to solve the problem:

  • Initialize a variable gcdby 0.
  • Iterate through the array from 0 to N-1.
    • At each iteration take gcd of the variable gcdand difference between arr[i] and arr[i + 1].
  • At the end of the iteration, if gcd is 1, return 2.
  • Else, return 1.

Below is the implementation of the above approach.


Output
1

Time Complexity: O(N * log(M)) where M is the maximum value of the array
Auxiliary Space: O(1)

Comment