Reduce an array to a single element by repeatedly removing larger element from a pair with absolute difference at most K
Last Updated :
23 Jul, 2025
Given an array arr[] consisting of N integers and a positive integer K, the task is to check if the given array can be reduced to a single element by repeatedly removing the larger of the two elements present in a pair whose absolute difference is at most K. If the array can be reduced to a single element, then print "Yes". Otherwise, print "No".
Examples:
Input: arr[] = {2, 1, 1, 3}, K = 1
Output: Yes
Explanation:
Operation 1: Select the pair {arr[0], arr[3]} ( = (2, 3), as | 3 - 2 | ? 1. Now, remove 3 from the array. The array modifies to {2, 1, 1}.
Operation 2: Select the pair {arr[0], arr[1]} ( = (2, 1), as | 2 - 1 | ? 1. Now, remove 2 from the array. The array modifies to {1, 1}.
Operation 3: Remove 1 from the array. The array modifies to {1}.
Therefore, the last remaining array element is 1.
Input: arr[] = {1, 4, 3, 6}, K = 1
Output: No
Approach: The given problem can be solved using a Greedy Approach. The idea is to remove the element with a maximum value in every possible moves. Follow the given steps to solve the problem:
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if an array can be
// reduced to single element by removing
// maximum element among any chosen pairs
void canReduceArray(int arr[], int N, int K)
{
// Sort the array in descending order
sort(arr, arr + N, greater<int>());
// Traverse the array
for (int i = 0; i < N - 1; i++) {
// If the absolute difference
// of 2 consecutive array
// elements is greater than K
if (arr[i] - arr[i + 1] > K) {
cout << "No";
return;
}
}
// If the array can be reduced
// to a single element
cout << "Yes";
}
// Driver Code
int main()
{
int arr[] = { 2, 1, 1, 3 };
int N = sizeof(arr) / sizeof(arr[0]);
int K = 1;
// Function Call to check
// if an array can be reduced
// to a single element
canReduceArray(arr, N, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
// Function to check if an array can be
// reduced to single element by removing
// maximum element among any chosen pairs
static void canReduceArray(int arr[], int N, int K)
{
// Sort the array in descending order
Arrays.sort(arr);
int b[] = new int[N];
int j = N;
for (int i = 0; i < N; i++) {
b[j - 1] = arr[i];
j = j - 1;
}
// Traverse the array
for (int i = 0; i < N - 1; i++) {
// If the absolute difference
// of 2 consecutive array
// elements is greater than K
if (arr[i] - arr[i + 1] > K) {
System.out.print("No");
return;
}
}
// If the array can be reduced
// to a single element
System.out.print("Yes");
}
// Driven Code
public static void main(String[] args)
{
int arr[] = { 2, 1, 1, 3 };
int N = arr.length;
int K = 1;
// Function Call to check
// if an array can be reduced
// to a single element
canReduceArray(arr, N, K);
}
}
// This code is contributed by splevel62
Python3
# Python3 program for the above approach
# Function to check if an array can be
# reduced to single element by removing
# maximum element among any chosen pairs
def canReduceArray(arr, N, K):
# Sort the array in descending order
arr = sorted(arr)
# Traverse the array
for i in range(N - 1):
# If the absolute difference
# of 2 consecutive array
# elements is greater than K
if (arr[i] - arr[i + 1] > K):
print ("No")
return
# If the array can be reduced
# to a single element
print ("Yes")
# Driver Code
if __name__ == '__main__':
arr = [2, 1, 1, 3]
N = len(arr)
K = 1
# Function Call to check
# if an array can be reduced
# to a single element
canReduceArray(arr, N, K)
# This code is contributed by mohit kumar 29
C#
// C# program for the above approach
using System;
class GFG{
// Function to check if an array can be
// reduced to single element by removing
// maximum element among any chosen pairs
static void canReduceArray(int[] arr, int N,
int K)
{
// Sort the array in descending order
Array.Sort(arr);
int[] b = new int[N];
int j = N;
for(int i = 0; i < N; i++)
{
b[j - 1] = arr[i];
j = j - 1;
}
// Traverse the array
for(int i = 0; i < N - 1; i++)
{
// If the absolute difference
// of 2 consecutive array
// elements is greater than K
if (arr[i] - arr[i + 1] > K)
{
Console.WriteLine("No");
return;
}
}
// If the array can be reduced
// to a single element
Console.WriteLine("Yes");
}
// Driver Code
public static void Main(String []args)
{
int[] arr = { 2, 1, 1, 3 };
int N = arr.Length;
int K = 1;
// Function Call to check
// if an array can be reduced
// to a single element
canReduceArray(arr, N, K);
}
}
// This code is contributed by souravghosh0416
JavaScript
<script>
// JavaScript program for the above approach
// Function to check if an array can be
// reduced to single element by removing
// maximum element among any chosen pairs
function canReduceArray(arr, N, K)
{
// Sort the array in descending order
arr.sort();
let b = Array(N ).fill(0);
let j = N;
for (let i = 0; i < N; i++) {
b[j - 1] = arr[i];
j = j - 1;
}
// Traverse the array
for (let i = 0; i < N - 1; i++) {
// If the absolute difference
// of 2 consecutive array
// elements is greater than K
if (arr[i] - arr[i + 1] > K) {
document.write("No");
return;
}
}
// If the array can be reduced
// to a single element
document.write("Yes");
}
// Driver Code
let arr = [ 2, 1, 1, 3 ];
let N = arr.length;
let K = 1;
// Function Call to check
// if an array can be reduced
// to a single element
canReduceArray(arr, N, K);
</script>
Time Complexity: O(N * log N)
Auxiliary Space: O(1)
Using a loop to repeatedly find the maximum difference pair and remove the larger element until only one element remains:
Approach:
Define a function reduce_array that takes in an array arr and an integer k.
Use a while loop to repeatedly execute the following steps as long as the length of arr is greater than 1:
Initialize max_diff to -1 and max_diff_pair to None.
Use a for loop to iterate over each adjacent pair of elements in arr.
Calculate the absolute difference diff between the two elements and check if diff is less than or equal to k and greater than max_diff.
If diff meets the above criteria, update max_diff to diff and max_diff_pair to the indices of the pair.
If max_diff_pair is not None, remove the element at the higher index of max_diff_pair from arr using the pop method.
Otherwise, return "No" since no pairs with absolute difference at most k were found.
Return "Yes" since there is only one element left in arr.
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
string reduceArray(vector<int>& arr, int k) {
while (arr.size() > 1) {
int max_diff = -1;
pair<int, int> max_diff_pair;
for (int i = 0; i < arr.size() - 1; i++) {
int diff = abs(arr[i] - arr[i + 1]);
if (diff <= k && diff > max_diff) {
max_diff = diff;
max_diff_pair = make_pair(i, i + 1);
}
}
if (!max_diff_pair.first && !max_diff_pair.second) {
return "No";
} else {
arr.erase(arr.begin() + max_diff_pair.second);
}
}
return "Yes";
}
int main() {
vector<int> arr1 = {2, 1, 1, 3};
int k1 = 1;
cout << reduceArray(arr1, k1) << endl; // Output: Yes
vector<int> arr2 = {1, 4, 3, 6};
int k2 = 1;
cout << reduceArray(arr2, k2) << endl; // Output: No
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
// Function to reduce the array based on given conditions
static String reduceArray(List<Integer> arr, int k) {
// Continue the process until the array size becomes 1
while (arr.size() > 1) {
int maxDiff = -1;
int maxDiffIndex = -1;
// Iterate through the array to find the maximum difference within the given constraint
for (int i = 0; i < arr.size() - 1; i++) {
int diff = Math.abs(arr.get(i) - arr.get(i + 1));
if (diff <= k && diff > maxDiff) {
maxDiff = diff;
maxDiffIndex = i;
}
}
// If no valid pair is found, return "No"
if (maxDiffIndex == -1) {
return "No";
} else {
// Remove the second element of the pair with the maximum difference
arr.remove(maxDiffIndex + 1);
}
}
// If array size becomes 1, return "Yes"
return "Yes";
}
public static void main(String[] args) {
// Test case 1
List<Integer> arr1 = new ArrayList<>(List.of(2, 1, 1, 3));
int k1 = 1;
System.out.println(reduceArray(arr1, k1)); // Output: Yes
// Test case 2
List<Integer> arr2 = new ArrayList<>(List.of(1, 4, 3, 6));
int k2 = 1;
System.out.println(reduceArray(arr2, k2)); // Output: No
}
}
Python3
def reduce_array(arr, k):
while len(arr) > 1:
max_diff = -1
max_diff_pair = None
for i in range(len(arr)-1):
diff = abs(arr[i] - arr[i+1])
if diff <= k and diff > max_diff:
max_diff = diff
max_diff_pair = (i, i+1)
if max_diff_pair:
arr.pop(max_diff_pair[1])
else:
return "No"
return "Yes"
# Example usage:
arr1 = [2, 1, 1, 3]
k1 = 1
print(reduce_array(arr1, k1)) # Output: Yes
arr2 = [1, 4, 3, 6]
k2 = 1
print(reduce_array(arr2, k2)) # Output: No
C#
using System;
using System.Collections.Generic;
class GFG
{
static string ReduceArray(List<int> arr, int k)
{
while (arr.Count > 1)
{
int maxDiff = -1;
Tuple<int, int> maxDiffPair = null;
for (int i = 0; i < arr.Count - 1; i++)
{
int diff = Math.Abs(arr[i] - arr[i + 1]);
if (diff <= k && diff > maxDiff)
{
maxDiff = diff;
maxDiffPair = Tuple.Create(i, i + 1);
}
}
if (maxDiffPair == null)
{
return "No";
}
else
{
arr.RemoveAt(maxDiffPair.Item2);
}
}
return "Yes";
}
static void Main()
{
List<int> arr1 = new List<int> { 2, 1, 1, 3 };
int k1 = 1;
Console.WriteLine(ReduceArray(arr1, k1)); // Output: Yes
List<int> arr2 = new List<int> { 1, 4, 3, 6 };
int k2 = 1;
Console.WriteLine(ReduceArray(arr2, k2)); // Output: No
}
}
JavaScript
function reduceArray(arr, k) {
while (arr.length > 1) {
let maxDiff = -1;
let maxDiffPair = { first: -1, second: -1 };
// Find the pair of adjacent elements with the maximum difference
for (let i = 0; i < arr.length - 1; i++) {
const diff = Math.abs(arr[i] - arr[i + 1]);
if (diff <= k && diff > maxDiff) {
maxDiff = diff;
maxDiffPair.first = i;
maxDiffPair.second = i + 1;
}
}
// If no suitable pair is found, return "No"
if (maxDiffPair.first === -1 && maxDiffPair.second === -1) {
return "No";
} else {
// Remove the second element of the pair
arr.splice(maxDiffPair.second, 1);
}
}
// If only one element remains in the array, return "Yes"
return "Yes";
}
// Driver code
const arr1 = [2, 1, 1, 3];
const k1 = 1;
console.log(reduceArray(arr1, k1)); // Output: Yes
const arr2 = [1, 4, 3, 6];
const k2 = 1;
console.log(reduceArray(arr2, k2)); // Output: No
Time Complexity: O(n^2)
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem