Minimum distance between any special pair in the given array
Last Updated :
15 Jul, 2025
Given an array arr[] of N integers, the task is to find the minimum possible absolute difference between indices of a special pair.
A special pair is defined as a pair of indices (i, j) such that if arr[i] ? arr[j], then there is no element X (where arr[i] < X < arr[j]) present in between indices i and j.
For example:
arr[] = {1, -5, 5}
Here, {1, 5} forms a special pair as there are no elements in the range (1 to 5) in between arr[0] and arr[2].
Print the minimum absolute difference abs(j - i) such that pair (i, j) forms a special pair.
Examples:
Input: arr[] = {0, -10, 5, -5, 1}
Output: 2
Explanation:
The elements 1 and 5 forms a special pair since there is no elements X in the range 1 < X < 5 in between them, and they are 2 indices away from each other.
Input: arr[] = {3, 3}
Output: 1
Naive Approach: The simplest approach is to consider every pair of elements of the array and check if they form a special pair or not. If found to be true, then print the minimum distance among all the pairs formed.
Time Complexity: O(N3)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to observe that we have to only consider the distance between the position of adjacent elements in the sorted array since those pair of elements will not have any value X between it. Below are the steps:
- Store the initial indices of array elements in a Map.
- Sort the given array arr[].
- Now, find the distance between the indices of adjacent elements of the sorted array using the Map.
- Maintain the minimum distance for each pair of adjacent elements in the step above.
- After the completing the above steps, print the minimum distance formed.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function that finds the minimum
// difference between two vectors
int mindist(vector<int>& left,
vector<int>& right)
{
int res = INT_MAX;
for (int i = 0; i < left.size(); ++i) {
int num = left[i];
// Find lower bound of the index
int index
= lower_bound(right.begin(),
right.end(), num)
- right.begin();
// Find two adjacent indices
// to take difference
if (index == 0)
res = min(res,
abs(num
- right[index]));
else if (index == right.size())
res = min(res,
abs(num
- right[index - 1]));
else
res = min(res,
min(abs(num
- right[index - 1]),
abs(num
- right[index])));
}
// Return the result
return res;
}
// Function to find the minimum distance
// between index of special pairs
int specialPairs(vector<int>& nums)
{
// Stores the index of each element
// in the array arr[]
map<int, set<int> > m;
vector<int> vals;
// Store the indexes
for (int i = 0;
i < nums.size(); ++i) {
m[nums[i]].insert(i);
}
// Get the unique values in list
for (auto p : m) {
vals.push_back(p.first);
}
int res = INT_MAX;
for (int i = 0;
i < vals.size(); ++i) {
vector<int> vec(m[vals[i]].begin(),
m[vals[i]].end());
// Take adjacent difference
// of same values
for (int i = 1;
i < vec.size(); ++i)
res = min(res,
abs(vec[i]
- vec[i - 1]));
if (i) {
int a = vals[i];
// Left index array
vector<int> left(m[a].begin(),
m[a].end());
int b = vals[i - 1];
// Right index array
vector<int> right(m[b].begin(),
m[b].end());
// Find the minimum gap between
// the two adjacent different
// values
res = min(res,
mindist(left, right));
}
}
return res;
}
// Driver Code
int main()
{
// Given array
vector<int> arr{ 0, -10, 5, -5, 1 };
// Function Call
cout << specialPairs(arr);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class Main {
// Function that finds the minimum
// difference between two vectors
public static int Mindist(List<Integer> left, List<Integer> right) {
int res = Integer.MAX_VALUE;
for (int i = 0; i < left.size(); i++) {
int num = left.get(i);
// Find lower bound of the index
int index = right.indexOf(right.stream().filter(x -> x <= num).findFirst().orElse(right.get(right.size() - 1)));
// Find two adjacent indices
// to take difference
if (index == 0) {
res = Math.min(res, Math.abs(num - right.get(index)));
} else if (index == right.size()) {
res = Math.min(
res,
Math.min(
Math.abs(num - right.get(index - 1)),
Math.abs(num - right.get(index))
)
);
}
}
// Return the result
return res;
}
// Function to find the minimum distance
// between index of special pairs
public static int SpecialPairs(int[] nums) {
// Stores the index of each element
// in the array arr[]
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
List<Integer> vals = new ArrayList<Integer>();
for (int i = 0; i < nums.length; i++) {
m.put(nums[i], i);
}
for (int p : m.keySet()) {
vals.add(p);
}
int res = Integer.MAX_VALUE;
for (int i = 1; i < vals.size(); i++) {
List<Integer> vec = new ArrayList<Integer>();
vec.add(m.get(vals.get(i)));
// Take adjacent difference
// of same values
for (int j = 1; j < vec.size(); j++) {
res = Math.min(res, Math.abs(vec.get(j) - vec.get(j - 1)));
}
if (i > 0) {
int a = vals.get(i);
// Left index array
List<Integer> left = new ArrayList<Integer>();
left.add(m.get(a));
int b = vals.get(i - 1);
// Right index array
List<Integer> right = new ArrayList<Integer>();
right.add(m.get(b));
// Find the minimum gap between
// the two adjacent different
// values
res = Math.min(res, Mindist(left, right)) + 1;
}
}
return res;
}
// Driver Code
public static void main(String[] args) {
int[] arr = {0, -10, 5, -5, 1};
System.out.println(SpecialPairs(arr));
}
}
// This code is contributed by princekumaras
Python3
# Python3 program for the above approach
import sys
# Function that finds the minimum
# difference between two vectors
def mindist(left, right):
res = sys.maxsize
for i in range(len(left)):
num = left[i]
# Find lower bound of the index
index = right.index(min(
[i for i in right if num >= i]))
# Find two adjacent indices
# to take difference
if (index == 0):
res = min(res,
abs(num - right[index]))
elif (index == len(right)):
res = min(res,
min(abs(num - right[index -1]),
abs(num - right[index])))
# Return the result
return res
# Function to find the minimum distance
# between index of special pairs
def specialPairs(nums):
# Stores the index of each element
# in the array arr[]
m = {}
vals = []
for i in range(len(nums)):
m[nums[i]] = i
for p in m:
vals.append(p)
res = sys.maxsize
for i in range(1, len(vals)):
vec = [m[vals[i]]]
# Take adjacent difference
# of same values
for i in range(1, len(vec)):
res = min(res,
abs(vec[i] - vec[i - 1]))
if (i):
a = vals[i]
# Left index array
left = [m[a]]
b = vals[i - 1]
# Right index array
right = [m[b]]
# Find the minimum gap between
# the two adjacent different
# values
res = min(res,
mindist(left, right)) + 1
return res
# Driver Code
if __name__ == "__main__":
# Given array
arr = [ 0, -10, 5, -5, 1 ]
# Function call
print(specialPairs(arr))
# This code is contributed by dadi madhav
JavaScript
// Function that finds the minimum
// difference between two vectors
function mindist(left, right) {
let res = Number.MAX_SAFE_INTEGER;
for (let i = 0; i < left.length; i++) {
const num = left[i];
// Find lower bound of the index
const index = right.findIndex((i) => num >= i);
// Find two adjacent indices
// to take difference
if (index === 0) {
res = Math.min(res, Math.abs(num - right[index]));
} else if (index === right.length) {
res = Math.min(
res,
Math.min(
Math.abs(num - right[index - 1]),
Math.abs(num - right[index])
)
);
}
}
// Return the result
return res;
}
// Function to find the minimum distance
// between index of special pairs
function specialPairs(nums) {
// Stores the index of each element
// in the array arr[]
const m = new Map();
const vals = [];
for (let i = 0; i < nums.length; i++) {
m.set(nums[i], i);
}
for (const p of m.keys()) {
vals.push(p);
}
let res = Number.MAX_SAFE_INTEGER;
for (let i = 1; i < vals.length; i++) {
const vec = [m.get(vals[i])];
// Take adjacent difference
// of same values
for (let j = 1; j < vec.length; j++) {
res = Math.min(res, Math.abs(vec[j] - vec[j - 1]));
}
if (i) {
const a = vals[i];
// Left index array
const left = [m.get(a)];
const b = vals[i - 1];
// Right index array
const right = [m.get(b)];
// Find the minimum gap between
// the two adjacent different
// values
res = Math.min(res, mindist(left, right)) + 1;
}
}
return res;
}
// Driver Code
const arr = [0, -10, 5, -5, 1];
console.log(specialPairs(arr));
// This code is contributed by Aditya Sharma
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
// Function that finds the minimum
// difference between two vectors
static int mindist(List<int> left, List<int> right)
{
int res = int.MaxValue;
for (int i = 0; i < left.Count; i++) {
int num = left[i];
// Find lower bound of the index
int index = right.IndexOf(
right.Where(i = > num >= i).Min());
// Find two adjacent indices
// to take difference
if (index == 0)
res = Math.Min(
res, Math.Abs(num - right[index]));
else if (index == right.Count)
res = Math.Min(
res,
Math.Min(
Math.Abs(num - right[index - 1]),
Math.Abs(num - right[index])));
}
// Return the result
return res;
}
// Function to find the minimum distance
// between index of special pairs
static int specialPairs(List<int> nums)
{
// Stores the index of each element
// in the array arr[]
Dictionary<int, int> m = new Dictionary<int, int>();
List<int> vals = new List<int>();
for (int i = 0; i < nums.Count; i++)
m[nums[i]] = i;
vals = m.Keys.ToList();
int res = int.MaxValue;
for (int i = 1; i < vals.Count; i++) {
List<int> vec = new List<int>();
vec.Add(m[vals[i]]);
// Take adjacent difference
// of same values
for (int j = 1; j < vec.Count; j++)
res = Math.Min(
res, Math.Abs(vec[j] - vec[j - 1]));
if (i > 0) {
int a = vals[i];
// Left index array
List<int> left = new List<int>();
left.Add(m[a]);
int b = vals[i - 1];
// Right index array
List<int> right = new List<int>();
right.Add(m[b]);
// Find the minimum gap between
// the two adjacent different
// values
res = Math.Min(res, mindist(left, right))
+ 1;
}
}
return res;
}
static void Main(string[] args)
{
// Given array
List<int> arr
= new List<int>() { 0, -10, 5, -5, 1 };
// Function call
Console.Write(specialPairs(arr));
}
}
// This code is contributed by Prince Kumar
Time Complexity: O(N*log N)
Auxiliary Space: O(N) , since N extra space has been taken.
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