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
  • DSA
  • Interview Problems on Queue
  • Practice Queue
  • MCQs on Queue
  • Queue Tutorial
  • Operations
  • Applications
  • Implementation
  • Stack vs Queue
  • Types of Queue
  • Circular Queue
  • Deque
  • Priority Queue
  • Stack using Queue
  • Advantages & Disadvantages
Open In App
Next Article:
Difference Array | Range update query in O(1)
Next article icon

Reduce Array by replacing pair with their difference

Last Updated : 20 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

You are given an array of positive integers. You can perform the following operations on the array any number of times:

  • Select the two largest elements in the array, suppose a and b.
  • If a = b, remove both of them from the array.
  • If a > b, remove b and the new value of a will be a-b or vice-versa.

This process continues until there is either one element left or all the elements have been removed. You have to find the last element remaining or return 0 if there is none.

Examples:

Input: [1, 2, 3, 6, 7, 7]
Output: 0
Explanation: We start with two largest elements. In this case, they are two equal elements with value 7, so they both are removed. Then, the next elements are 3 and 6. Discard the smaller one and the larger one will now be of length 6-3 = 3. Then, the next elements are of 3 and 2. Again the smaller will be discarded and larger one will now be 3-2 = 1. Now there are two equal elements, 1, hence both will be discarded and output will be 0.

Input: [2, 4, 5]
Output: 1
Explanation: In this case, the two largest elements are 4 and 5. As 4 is smaller it will be discarded and the larger will become 5-4 = 1. Now there are only two elements remaining which are 1 and 2. Hence 1 will be discarded and the final output will be 2-1 = 1.

Approach:

As the problem has to repeatedly find the two largest items from a given array, we can think of a priority queue (Max heap) in this case. Using a max heap, we can perform the required operations until the given condition is reached.

Follow the below steps to implement the above idea:

  • Create a priority queue (max heap) named 'pq' to store the items in a decreasingly sorted manner.
  • Traverse through the array and insert each item into the heap.
  • Till there are atleast 2 items in the heap, perform the following operations as stated in the problem:
    • Store the two largest elements from the max-heap in two different variables named as 'a' and 'b'.
    • If the values of 'a' and 'b' are not equal, reduce the length of 'b' from 'a'.
    • Push the updated value of 'a' into the max-heap and continue performing these steps.
  • Once these above operations are performed, check if the size of pq is 1.
  • If it is equal to 1, that means one element is remaining which cannot be integrated further. So return the element as our answer.
  • If it is not 1, then all the elements have been removed and none is remaining. So we return 0 as our answer.

Implementation of the above approach:

C++
// C++ code for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to find the last element remaining int lastElement(vector<int>& arr) {     int n = arr.size();     // Create a max heap     priority_queue<int> pq;      // Push all the elements into the heap     for (int i = 0; i < n; i++) {         pq.push(arr[i]);     }      // Perform the operations till the size of heap is     // greater than 1     while (pq.size() > 1) {         // Pop the top two elements         int a = pq.top();         pq.pop();         int b = pq.top();         pq.pop();          // If both the elements are not equal         if (a != b) {             // Reduce the length of the larger element             a -= b;             // Push the updated value into the heap             pq.push(a);         }     }      // If one element is left return its value     if (pq.size() == 1) {         return pq.top();     }      // If no element is left return 0     return 0; }  // Driver Code int main() {     // Input vector     vector<int> arr = { 2, 4, 5 };     // Function call     cout << lastElement(arr) << endl;     return 0; } 
Java
// Java Code for the above approach  import java.util.*;  public class GFG {     // Function to find the last element remaining     public static int lastElement(int[] arr)     {         int n = arr.length;         // Create a max heap         PriorityQueue<Integer> pq = new PriorityQueue<>(             (a, b) -> Integer.compare(b, a));          // Push all the elements into the heap         for (int i = 0; i < n; i++) {             pq.add(arr[i]);         }          // Perform the operations until the size of the heap         // is greater than 1         while (pq.size() > 1) {             // Pop the top two elements             int a = pq.poll();             int b = pq.poll();              // If both the elements are not equal             if (a != b) {                 // Reduce the length of the larger element                 a -= b;                 // Push the updated value into the heap                 pq.add(a);             }         }          // If one element is left, return its value         if (pq.size() == 1) {             return pq.peek();         }          // If no element is left, return 0         return 0;     }      // Driver Code     public static void main(String[] args)     {         // Input array         int[] arr = { 1, 2, 3, 6, 7, 7 };         // Function call         System.out.println(lastElement(arr));     } } 
Python3
import heapq  # Function to find the last element remaining def last_element(arr):     n = len(arr)     # Create a max heap     pq = [-x for x in arr]     heapq.heapify(pq)      # Perform the operations till the size of heap is     # greater than 1     while len(pq) > 1:         # Pop the top two elements         a = -heapq.heappop(pq)         b = -heapq.heappop(pq)          # If both the elements are not equal         if a != b:             # Reduce the length of the larger element             a -= b             # Push the updated value into the heap             heapq.heappush(pq, -a)      # If one element is left return its value     if len(pq) == 1:         return -pq[0]      # If no element is left return 0     return 0  # Driver Code if __name__ == "__main__":     # Input list     arr = [2, 4, 5]     # Function call     print(last_element(arr)) 
C#
// C# program for the above approach using System; using System.Collections.Generic;  public class GFG {     // Function to find the last element remaining     static int LastElement(List<int> arr)     {         int n = arr.Count;          // Create a max heap         var pq = new PriorityQueue<int>();          // Push all the elements into the heap         for (int i = 0; i < n; i++) {             pq.Push(arr[i]);         }          // Perform the operations till the size of heap is         // greater than 1         while (pq.Count > 1) {             // Pop the top two elements             int a = pq.Pop();             int b = pq.Pop();              // If both the elements are not equal             if (a != b) {                 // Reduce the length of the larger element                 a -= b;                 // Push the updated value into the heap                 pq.Push(a);             }         }          // If one element is left return its value         if (pq.Count == 1) {             return pq.Top();         }          // If no element is left return 0         return 0;     }      // Driver Code     static void Main()     {         // Input list         List<int> arr = new List<int>{ 2, 4, 5 };         // Function call         Console.WriteLine(LastElement(arr));     } }  // Priority Queue Implementation public class PriorityQueue<T> where T : IComparable<T> {     private List<T> heap;      public PriorityQueue() { heap = new List<T>(); }      public int Count     {         get { return heap.Count; }     }      public void Push(T value)     {         heap.Add(value);         int currentIndex = heap.Count - 1;          while (currentIndex > 0) {             int parentIndex = (currentIndex - 1) / 2;             if (heap[currentIndex].CompareTo(                     heap[parentIndex])                 > 0) {                 Swap(currentIndex, parentIndex);                 currentIndex = parentIndex;             }             else {                 break;             }         }     }      public T Pop()     {         if (Count == 0) {             throw new InvalidOperationException(                 "Priority queue is empty");         }          T root = heap[0];         heap[0] = heap[Count - 1];         heap.RemoveAt(Count - 1);          int currentIndex = 0;         while (true) {             int leftChildIndex = currentIndex * 2 + 1;             int rightChildIndex = currentIndex * 2 + 2;              if (leftChildIndex >= Count) {                 break;             }              int childIndex = leftChildIndex;             if (rightChildIndex < Count                 && heap[rightChildIndex].CompareTo(                        heap[leftChildIndex])                        > 0) {                 childIndex = rightChildIndex;             }              if (heap[currentIndex].CompareTo(                     heap[childIndex])                 < 0) {                 Swap(currentIndex, childIndex);                 currentIndex = childIndex;             }             else {                 break;             }         }          return root;     }      public T Top()     {         if (Count == 0) {             throw new InvalidOperationException(                 "Priority queue is empty");         }         return heap[0];     }      private void Swap(int index1, int index2)     {         T temp = heap[index1];         heap[index1] = heap[index2];         heap[index2] = temp;     } }  // This code is contributed by Susobhan Akhuli 
JavaScript
// Javascript program for the above approach  // Function to find the last element remaining function lastElement(arr) {     const n = arr.length;     // Create a max heap     const pq = new MaxHeap();      // Push all the elements into the heap     for (let i = 0; i < n; i++) {         pq.push(arr[i]);     }      // Perform the operations until the size of heap is greater than 1     while (pq.size() > 1) {         // Pop the top two elements         const a = pq.pop();         const b = pq.pop();          // If both the elements are not equal         if (a !== b) {             // Reduce the length of the larger element             const diff = a - b;             // Push the updated value into the heap             pq.push(diff);         }     }      // If one element is left return its value     if (pq.size() === 1) {         return pq.pop();     }      // If no element is left return 0     return 0; }  // MaxHeap class to simulate max heap functionality class MaxHeap {     constructor() {         this.heap = [];     }      push(value) {         this.heap.push(value);         this.heapifyUp();     }      pop() {         if (this.isEmpty()) {             return null;         }         if (this.heap.length === 1) {             return this.heap.pop();         }         const root = this.heap[0];         this.heap[0] = this.heap.pop();         this.heapifyDown();         return root;     }      size() {         return this.heap.length;     }      isEmpty() {         return this.size() === 0;     }      heapifyUp() {         let index = this.size() - 1;         while (index > 0) {             const parentIndex = Math.floor((index - 1) / 2);             if (this.heap[index] > this.heap[parentIndex]) {                 this.swap(index, parentIndex);                 index = parentIndex;             } else {                 break;             }         }     }      heapifyDown() {         let index = 0;         const length = this.size();         while (true) {             const leftChildIndex = 2 * index + 1;             const rightChildIndex = 2 * index + 2;             let largest = index;             if (                 leftChildIndex < length &&                 this.heap[leftChildIndex] > this.heap[largest]             ) {                 largest = leftChildIndex;             }             if (                 rightChildIndex < length &&                 this.heap[rightChildIndex] > this.heap[largest]             ) {                 largest = rightChildIndex;             }             if (largest !== index) {                 this.swap(index, largest);                 index = largest;             } else {                 break;             }         }     }      swap(i, j) {         [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];     } }  // Driver Code const arr = [2, 4, 5]; // Function call console.log(lastElement(arr));  // This code is contributed by Susobhan Akhuli 

Output
1

Time Complexity: O(N*log(N)). The all insertions in a priority queue takes O(N*log(N)) time and the time for each pop and top operation takes O(log(N)) time.
Auxiliary space: O(N),as we have used an extra space of a priority queue data structure.


Next Article
Difference Array | Range update query in O(1)

A

abhinav_m22
Improve
Article Tags :
  • Heap
  • DSA
  • priority-queue
  • java-priority-queue
  • max-heap
Practice Tags :
  • Heap
  • priority-queue

Similar Reads

  • Smallest array that can be obtained by replacing adjacent pairs with their products
    Given an array arr[] of size N, the task is to print the least possible size the given array can be reduced to by performing the following operations: Remove any two adjacent elements, say arr[i] and arr[i+1] and insert a single element arr[i] * arr[i+1] at that position in the array.If all array el
    4 min read
  • Pair with the given difference
    Given an unsorted array and an integer x, the task is to find if there exists a pair of elements in the array whose absolute difference is x. Examples: Input: arr[] = [5, 20, 3, 2, 50, 80], x = 78Output: YesExplanation: The pair is {2, 80}. Input: arr[] = [90, 70, 20, 80, 50], x = 45Output: NoExplan
    14 min read
  • Minimize remaining array element by removing pairs and replacing them by their absolute difference
    Given an array arr[] consisting of N positive integers, the task is to minimize the remaining array element that can be obtained by repeatedly removing a pair of array elements and replacing them by their absolute difference. Examples: Input: arr[] ={ 2, 7, 4, 1, 8, 1 } Output: 1 Explanation: Removi
    15 min read
  • Difference Array | Range update query in O(1)
    You are given an integer array arr[] and a list of queries. Each query is represented as a list of integers where: [1, l, r, x]: Adds x to all elements from arr[l] to arr[r] (inclusive).[2]: Prints the current state of the array.You need to perform the queries in order. Examples : Input: arr[] = [10
    11 min read
  • Minimize Array Sum by replacing pairs with (X, Y) keeping their bitwise OR same
    Given an array arr[] of size N. Find the minimum sum of the array after performing given operations any number of times: Select two different indices i, j (1 ≤ i < j ≤ N),Replace arr[i] and arr[j] with X and Y respectively (X, Y>0), such that arr[i] | arr[j] = X | Y, where | denotes the bitwis
    5 min read
  • Minimum replacement of pairs by their LCM required to reduce given array to its LCM
    Given an array arr[] consisting of N positive integers, the task is to find the minimum number of pairs (arr[i], arr[j]) from the given array needed to be replaced with their LCM such that the array is reduced to a single element equal to the LCM of the initial array.Examples: Input: arr[] = {1, 2,
    9 min read
  • Reduce array to a single element by repeatedly replacing adjacent unequal pairs with their maximum
    Given an array arr[] consisting of N integers, the task is to reduce the given array to a single element by repeatedly replacing any pair of consecutive unequal elements, say arr[i] and arr[i+1] with max(arr[i], arr[i + 1]) + 1. If possible, print the index of the element from where the operation ca
    15 min read
  • Symmetric difference of two sorted array
    There are two sorted array arr1 and arr2. We have to find the symmetric difference of Aarr1 and arr2. Symmetric Difference basically contains all elements of two arrays except common elements. Symmetric difference of two array is the all array elements of both array except the elements that are pres
    7 min read
  • Pairs with Difference less than K
    Given an array of n integers, We need to find all pairs with a difference less than k Examples : Input : a[] = {1, 10, 4, 2} K = 3 Output : 2 We can make only two pairs with difference less than 3. (1, 2) and (4, 2) Input : a[] = {1, 8, 7} K = 7 Output : 2 Pairs with difference less than 7 are (1, 7
    13 min read
  • Count pairs from two arrays with difference exceeding K | set 2
    Given two integer arrays arr[] and brr[] consisting of distinct elements of size N and M respectively and an integer K, the task is to find the count of pairs (arr[i], brr[j]) such that (brr[j] – arr[i]) > K. Examples: Input: arr[] = {5, 9, 1, 8}, brr[] = {10, 12, 7, 4, 2, 3}, K = 3Output: 6Expla
    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