VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reduce-given-array-by-replacing-adjacent-elements-with-their-difference/

⇱ Reduce given Array by replacing adjacent elements with their difference - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reduce given Array by replacing adjacent elements with their difference

Last Updated : 23 Jul, 2025

Given an array arr[] consisting of N elements(such that N = 2k for some k ? 0), the task is to reduce the array and find the last remaining element after merging all elements into one. The array is reduced by performing the following operation:

  • Merge the adjacent elements i.e merge elements at indices 0 and 1 into one, 2 and 3 into one and so on. 
  • Upon merging the newly formed element will become the absolute difference between the two elements merged.

Examples:

Input: N = 4, arr[] = [1, 2, 3, 4]
Output: 0
Explanation: First operation:
On merging 1st and 2nd elements we will have a element with value1. 
On merging 3rd and 4th elements, we will have a element with value1. 
Therefore, we are left with two elements where each of them having cost 1.
Second operation:
On merging the 1st and 2nd elements we will get a new element with value 0.
This is because both elements had the same value of 1.

Input: N = 1, arr[] = [20]
Output: 20
Explanation: We can't perform any operation because performing an operation requires at least 2 elements. Hence, 20 is cost of the last remaining element

Approach: This problem can be solved using the Divide and Conquer approach.

  • Create a recursive function.
    • The base condition for recursion will be if the size of the array is 1 then the answer will be the only array element in it.
    • Return the absolute difference between the first half of the array and the second half of the array by calling the recursive function for both halves.
    • Merge both halves and get the answer.

Below is the implementation of the above approach:


Output
0

Time Complexity: O(2log2N)
Auxiliary Space: O(N)

Comment
Article Tags: