VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-minimised-number-using-given-operations/

⇱ Find the minimised number using given operations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the minimised number using given operations

Last Updated : 23 Jul, 2025

Given an array arr[] of n elements. In one operation you can pick two indices i and j, such that arr[i] ≥ arr[j] and replace the value of arr[i] with (arr[i] - arr[j]), the task is to minimize the values of the array after performing any number of such operations.

Examples:

Input: n = 3, arr[] = {3, 2, 4}
Output: 1
Explanation:

  • 1st Operation: We can pick 4 & 3, subtract 4-3 => {3, 2, 1}
  • 2nd Operation: We can pick 3 & 2, subtract 3-2 => {1, 2, 1}
  • 3rd Operation: We can pick 1 & 2, subtract 2-1 => {1, 1, 1}
  • 4th Operation: We can pick 1 & 1, subtract 1-1 => {1, 0, 1}
  • 5th Operation: We can pick 1 & 1, subtract 1-1 => {0, 0, 1}

After this, no operation can be performed, so the maximum no left in the array is 1, so the answer is 1.

Input: n = 2, arr[] = {2, 4}
Output: 2
Explanation:

  • 1st Operation : We can pick 4 & 2, subtract 4-2 => {2, 2}
  • 2nd Operation : We can pick 2 & 2, subtract 2-2 => {0, 2}

After this, no operation can be performed, so the maximum no left in the array is 2, so the answer is 2.

Approach: 

Intuition behind this approach is to use sorting in ascending order to bring the closest elements together. And by iterating over the sorted array, we calculate the difference between adjacent elements to find the minimum difference. then minimum difference between adjacent elements gives the minimum value after performing the operations.

To do this, we can use the following steps:

  • Sort the given array in ascending order.
  • Initialize the minimum_value variable to the maximum integer value.
    • Iterate over the array from the first element to the second-to-last element.
    • Calculate the difference between the current element and the next element.
  • If the difference is smaller than the minimum_value, update the minimum_value.
  • Return the minimum_value as the result.

Below is the implementation of the above approach:


Output
1

Time Complexity: O(N*logN)
Auxiliary Space: O(1)

Approach: This can be solved with the following idea:

This problem can be solved using Heap Data Structure.

Below are the steps involved in the implementation of the code:

  • If the size of the array is 1 then that element is the answer.
  • A max-heap is created and all elements of the array are put into the max-heap.
  • Now we take the top 2 elements of the heap until the second element is greater than zero.
  • We subtract the second element from the first element and push the first element back into the heap.
  • Finally, the answer is when the second element becomes the first element.

Below is the implementation of the above approach:


Output
1

Time Complexity: O(N*logN)
Auxiliary Space: O(N)

Comment
Article Tags: