Find Subarray ranges having difference between max and min exactly K
Last Updated :
20 Jul, 2022
Given an array arr[] of length N and integer K, the task is to print subarray ranges (starting index, ending index) of the array where difference between max and min elements of the subarray is exactly K.( 1-based index )
Examples:
Input: arr[] = {2, 1, 3, 4, 2, 6}, K = 2
Output: (1, 3), (2, 3), (3, 5), (4, 5)
Explanation: In the above array following sub array ranges have max min difference exactly K
(1, 3) => max = 3 and min = 1. Difference = 3 - 1 = 2
(2, 3) => max = 3 and min = 1. Difference = 3 - 1 = 2
(3, 5) => max = 4 and min = 2. Difference = 4 - 2 = 2
(4, 5) => max = 4 and min = 2. Difference = 4 - 2 = 2
Input: arr[] = {5, 3, 4, 6, 1, 2}, K = 6
Output: -1
Explanation: There is no such sub array ranges.
Approach: The basic idea to solve the problem is to form all the subarrays and find the minimum and maximum and their difference for each subarray. Follow the steps mentioned below to solve the problem.
- Iterate over the array from i = 0 to N-1:
- Iterate from j = i to N-1:
- Insert arr[j] current element in a set storing the current subarray starting from i.
- Find the minimum and maximum of the set.
- Get their difference and check if their difference is equal to K or not.
- If it is, then push this range in the answer.
- Return the ranges.
- If no such range then return -1.
Below is the implementation of the above approach.
C++
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
// Function to print index ranges
void printRanges(vector<int> arr, int n,
int K)
{
int i, j, f = 0;
for (i = 0; i < n; i++) {
// Set to store the elements
// of a subarray
set<int> s;
for (j = i; j < n; j++) {
// Insert current element in set
s.insert(arr[j]);
// Calculate max and min for
// any particular index range
int max = *s.rbegin();
int min = *s.begin();
// If we get max-min = K
// print 1 based index
if (max - min == K) {
cout << i + 1 << " " << j + 1
<< "\n";
f = 1;
}
}
}
// If we didn't find any index ranges
if (f == 0)
cout << -1 << endl;
}
// Driver Code
int main()
{
vector<int> arr = { 2, 1, 3, 4, 2, 6 };
int N = arr.size();
int K = 2;
// Function call
printRanges(arr, N, K);
return 0;
}
Java
// Java implementation of above approach
import java.util.*;
class GFG {
// Function to print index ranges
static void printRanges(int arr[], int n,
int K)
{
int i, j, f = 0;
for (i = 0; i < n; i++) {
// Set to store the elements
// of a subarray
Set<Integer> s = new HashSet<>();
for (j = i; j < n; j++) {
// Insert current element in set
s.add(arr[j]);
// Calculate max and min for
// any particular index range
int max = Collections.max(s);
int min = Collections.min(s);
// If we get max-min = K
// print 1 based index
if (max - min == K) {
System.out.println( (i + 1) + " " + (j + 1));
f = 1;
}
}
}
// If we didn't find any index ranges
if (f == 0)
System.out.println(-1);
}
// Driver Code
public static void main (String[] args) {
int arr[] = { 2, 1, 3, 4, 2, 6 };
int N = arr.length;
int K = 2;
// Function call
printRanges(arr, N, K);
}
}
// This code is contributed by hrithikgarg03188.
Python3
# python3 implementation of above approach
# Function to print index ranges
def printRanges(arr, n, K):
i, j, f = 0, 0, 0
for i in range(0, n):
# Set to store the elements
# of a subarray
s = set()
for j in range(i, n):
# Insert current element in set
s.add(arr[j])
# Calculate max and min for
# any particular index range
ma = max(list(s))
mi = min(list(s))
# If we get max-min = K
# print 1 based index
if (ma - mi == K):
print(f"{i + 1} {j + 1}")
f = 1
# If we didn't find any index ranges
if (f == 0):
print(-1)
# Driver Code
if __name__ == "__main__":
arr = [2, 1, 3, 4, 2, 6]
N = len(arr)
K = 2
# Function call
printRanges(arr, N, K)
# This code is contributed by rakeshsahni
C#
// C# implementation of above approach
using System;
using System.Collections.Generic;
class GFG {
// Function to print index ranges
static void printRanges(int[] arr, int n, int K)
{
int i, j, f = 0;
for (i = 0; i < n; i++) {
// Set to store the elements
// of a subarray
HashSet<int> s = new HashSet<int>();
for (j = i; j < n; j++) {
// Insert current element in set
s.Add(arr[j]);
// Calculate max and min for
// any particular index range
int max = int.MinValue,min = int.MaxValue;
foreach(var value in s)
{
max = Math.Max(max,value);
min = Math.Min(min,value);
}
// If we get max-min = K
// print 1 based index
if (max - min == K) {
Console.Write( (i + 1) + " " + (j + 1) + "\n");
f = 1;
}
}
}
// If we didn't find any index ranges
if (f == 0)
Console.Write(-1);
}
// Driver Code
public static void Main()
{
int[] arr = { 2, 1, 3, 4, 2, 6 };
int N = arr.Length;
int K = 2;
// Function call
printRanges(arr, N, K);
}
}
// This code is contributed by aditya942003patil.
JavaScript
<script>
// Javascript implementation of above approach
// Function to print index ranges
function printRanges(arr, n, K)
{
let i = 0, j = 0, f = 0;
for (i = 0; i < n; i++) {
// Set to store the elements
// of a subarray
const s = new Set();
for (j = i; j < n; j++) {
// Insert current element in set
s.add(arr[j]);
// Calculate max and min for
// any particular index range
let max = Math.max(...s);
let min = Math.min(...s);
// If we get max-min = K
// print 1 based index
if (max - min == K) {
document.write((i+1) + " " + (j+1) + "<br>");
f = 1;
}
}
}
// If we didn't find any index ranges
if (f == 0)
document.write(-1);
}
// Driver Code
let arr = [ 2, 1, 3, 4, 2, 6 ];
let N = arr.length;
let K = 2;
// Function call
printRanges(arr, N, K);
// This code is contributed by aditya942003patil.
</script>
Time Complexity: O(N2 * logN)
Auxiliary Space: O(N)
Efficient Approach: Instead of using the HashSet, keep a track of current maximum and minimum element while traversing the array.
C++
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
// Function to print index ranges
void printRanges(vector<int> arr, int n, int K)
{
int i = 0, j = 0, f = 0;
for (i = 0; i < n; i++) {
int mx = INT_MIN, mn = INT_MAX;
for (j = i; j < n; j++) {
// Calculate max and min for
// any particular index range
mx = max(mx, arr[j]);
mn = min(mn, arr[j]);
// If we get max-min = K
// print 1 based index
if (mx - mn == K) {
cout << (i + 1) << " " << (j + 1) << endl;
f = 1;
}
}
}
// If we didn't find any index ranges
if (f == 0)
cout << -1;
}
// Driver Code
int main()
{
vector<int> arr = { 2, 1, 3, 4, 2, 6 };
int N = arr.size();
int K = 2;
// Function call
printRanges(arr, N, K);
}
// This code is contributed by Samim Hossain Mondal.
Java
// Java implementation of above approach
import java.util.*;
public class GFG {
// Function to print index ranges
static void printRanges(int[] arr, int n, int K)
{
int i = 0, j = 0, f = 0;
for (i = 0; i < n; i++) {
int mx = Integer.MIN_VALUE, mn
= Integer.MAX_VALUE;
for (j = i; j < n; j++) {
// Calculate max and min for
// any particular index range
mx = Math.max(mx, arr[j]);
mn = Math.min(mn, arr[j]);
// If we get max-min = K
// print 1 based index
if (mx - mn == K) {
System.out.println((i + 1) + " "
+ (j + 1));
f = 1;
}
}
}
// If we didn't find any index ranges
if (f == 0)
System.out.print(-1);
}
// Driver Code
public static void main(String args[])
{
int[] arr = { 2, 1, 3, 4, 2, 6 };
int N = arr.length;
int K = 2;
// Function call
printRanges(arr, N, K);
}
}
// This code is contributed by Samim Hossain Mondal.
Python3
# Python3 implementation of above approach
# import the module
import sys
# Function to print index ranges
def printRanges(arr, n, K):
i, j, f = 0, 0, 0
for i in range(0, n):
mn = sys.maxsize
mx = -1*sys.maxsize
for j in range(i, n):
# Calculate max and min for
# any particular index range
mx = max(mx, arr[j])
mn = min(mn, arr[j])
# If we get max-min=K
# print 1 based index
if(mx - mn == K):
print(f"{i + 1} {j + 1}")
f=1
# If we didn't find any index ranges
if (f == 0):
print(-1)
# Driver Code
if __name__ == "__main__":
arr = [2, 1, 3, 4, 2, 6]
N = len(arr)
K = 2
# Function call
printRanges(arr, N, K)
# This code is contributed by Pushpesh Raj
C#
// C# implementation of above approach
using System;
class GFG {
// Function to print index ranges
static void printRanges(int[] arr, int n, int K)
{
int i = 0, j = 0, f = 0;
for (i = 0; i < n; i++) {
int mx = Int32.MinValue, mn = Int32.MaxValue;
for (j = i; j < n; j++) {
// Calculate max and min for
// any particular index range
mx = Math.Max(mx, arr[j]);
mn = Math.Min(mn, arr[j]);
// If we get max-min = K
// print 1 based index
if (mx - mn == K) {
Console.WriteLine((i + 1) + " "
+ (j + 1));
f = 1;
}
}
}
// If we didn't find any index ranges
if (f == 0)
Console.Write(-1);
}
// Driver Code
public static void Main()
{
int[] arr = { 2, 1, 3, 4, 2, 6 };
int N = arr.Length;
int K = 2;
// Function call
printRanges(arr, N, K);
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// Javascript implementation of above approach
// Function to print index ranges
function printRanges(arr, n, K)
{
let i = 0, j = 0, f = 0;
for (i = 0; i < n; i++) {
let mx = Number.MIN_SAFE_INTEGER, mn = Number.MAX_SAFE_INTEGER;
for (j = i; j < n; j++) {
// Calculate max and min for
// any particular index range
mx = Math.max(mx, arr[j]);
mn = Math.min(mn, arr[j]);
// If we get max-min = K
// print 1 based index
if (mx - mn == K) {
document.write((i + 1) + " " + (j + 1));
f = 1;
}
}
}
// If we didn't find any index ranges
if (f == 0)
document.write(-1);
}
// Driver Code
let arr = [ 2, 1, 3, 4, 2, 6 ];
let N = arr.length;
let K = 2;
// Function call
printRanges(arr, N, K);
// This code is contributed by Samim Hossain Mondal.
</script>
Time Complexity: O(N2)
Auxiliary Space: O(1)
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