Minimum index i such that all the elements from index i to given index are equal
Last Updated :
10 Apr, 2023
Given an array arr[] of integers and an integer pos, the task is to find the minimum index i such that all the elements from index i to index pos are equal.
Examples:
Input: arr[] = {2, 1, 1, 1, 5, 2}, pos = 3
Output: 1
Elements in index range [1, 3] are all equal to 1.
Input: arr[] = {2, 1, 1, 1, 5, 2}, pos = 5
Output: 5
Brute Force Approach:
A brute force approach to solve this problem is to use two nested loops. The outer loop iterates through all the indices from 0 to pos, and the inner loop checks if all the elements from the current index to pos are equal. If they are equal, the current index is the minimum required index, and the loops can be terminated.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the minimum required index
int minIndex(int arr[], int n, int pos)
{
for (int i = 0; i <= pos; i++) {
int j;
for (j = i + 1; j <= pos; j++) {
if (arr[j] != arr[i]) {
break;
}
}
if (j == pos + 1) {
return i;
}
}
return -1; // If no such index exists
}
// Driver code
int main()
{
int arr[] = { 2, 1, 1, 1, 5, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
int pos = 4;
// Function Call
cout << minIndex(arr, n, pos);
return 0;
}
Java
import java.util.*;
public class Main {
// Function to return the minimum required index
static int minIndex(int arr[], int n, int pos) {
for (int i = 0; i <= pos; i++) {
int j;
for (j = i + 1; j <= pos; j++) {
if (arr[j] != arr[i]) {
break;
}
}
if (j == pos + 1) {
return i;
}
}
return -1; // If no such index exists
}
// Driver code
public static void main(String[] args) {
int arr[] = { 2, 1, 1, 1, 5, 2 };
int n = arr.length;
int pos = 4;
// Function Call
System.out.println(minIndex(arr, n, pos));
}
}
// This code is contributed by Prajwal kandekar
JavaScript
// Function to return the minimum required index
function minIndex(arr, n, pos) {
for (let i = 0; i <= pos; i++) {
let j;
for (j = i + 1; j <= pos; j++) {
if (arr[j] !== arr[i]) {
break;
}
}
if (j === pos + 1) {
return i;
}
}
return -1; // If no such index exists
}
// Driver code
const arr = [2, 1, 1, 1, 5, 2];
const n = arr.length;
const pos = 4;
// Function call
console.log(minIndex(arr, n, pos));
Python3
def minIndex(arr, n, pos):
# Function to return the minimum required index
for i in range(pos+1):
j = i + 1
while j <= pos:
if arr[j] != arr[i]:
break
j += 1
if j == pos + 1:
return i
return -1 # If no such index exists
# Driver code
arr = [2, 1, 1, 1, 5, 2]
n = len(arr)
pos = 4
# Function call
print(minIndex(arr, n, pos))
C#
using System;
class Program {
// Function to return the minimum required index
static int minIndex(int[] arr, int n, int pos) {
for (int i = 0; i <= pos; i++) {
int j;
for (j = i + 1; j <= pos; j++) {
if (arr[j] != arr[i]) {
break;
}
}
if (j == pos + 1) {
return i;
}
}
return -1; // If no such index exists
}
static void Main(string[] args) {
int[] arr = { 2, 1, 1, 1, 5, 2 };
int n = arr.Length;
int pos = 4;
// Function Call
Console.WriteLine(minIndex(arr, n, pos));
}
}
Output: 4
Time Complexity: O(n^2)
Space Complexity: O(1)
Simple Approach: Starting from index pos - 1, traverse the array in reverse and for the first index i such that arr[i] != arr[pos] print i + 1 which is the required index.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the minimum required index
int minIndex(int arr[], int n, int pos)
{
int num = arr[pos];
// Start from arr[pos - 1]
int i = pos - 1;
while (i >= 0) {
if (arr[i] != num)
break;
i--;
}
// All elements are equal
// from arr[i + 1] to arr[pos]
return i + 1;
}
// Driver code
int main()
{
int arr[] = { 2, 1, 1, 1, 5, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
int pos = 4;
// Function Call
cout << minIndex(arr, n, pos);
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
public class GFG {
// Function to return the minimum required index
static int minIndex(int arr[], int n, int pos)
{
int num = arr[pos];
// Start from arr[pos - 1]
int i = pos - 1;
while (i >= 0) {
if (arr[i] != num)
break;
i--;
}
// All elements are equal
// from arr[i + 1] to arr[pos]
return i + 1;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 2, 1, 1, 1, 5, 2 };
int n = arr.length;
int pos = 4;
// Function Call
System.out.println(minIndex(arr, n, pos));
}
}
// This code is contributed by Code_Mech.
Python3
# Python3 implementation of the approach
# Function to return the minimum
# required index
def minIndex(arr, n, pos):
num = arr[pos]
# Start from arr[pos - 1]
i = pos - 1
while (i >= 0):
if (arr[i] != num):
break
i -= 1
# All elements are equal
# from arr[i + 1] to arr[pos]
return i + 1
# Driver code
arr = [2, 1, 1, 1, 5, 2 ]
n = len(arr)
pos = 4
# Function Call
print(minIndex(arr, n, pos))
# This code is contributed by
# Mohit Kumar 29
C#
// C# implementation of the approach
using System;
class GFG {
// Function to return the minimum required index
static int minIndex(int[] arr, int n, int pos)
{
int num = arr[pos];
// Start from arr[pos - 1]
int i = pos - 1;
while (i >= 0) {
if (arr[i] != num)
break;
i--;
}
// All elements are equal
// from arr[i + 1] to arr[pos]
return i + 1;
}
// Driver code
public static void Main()
{
int[] arr = { 2, 1, 1, 1, 5, 2 };
int n = arr.Length;
int pos = 4;
// Function Call
Console.WriteLine(minIndex(arr, n, pos));
}
}
// This code is contributed
// by Akanksha Rai
PHP
<?php
// PHP implementation of the approach
// Function to return the minimum
// required index
function minIndex($arr, $n, $pos)
{
$num = $arr[$pos];
// Start from arr[pos - 1]
$i = $pos - 1;
while ($i >= 0)
{
if ($arr[$i] != $num)
break;
$i--;
}
// All elements are equal
// from arr[i + 1] to arr[pos]
return $i + 1;
}
// Driver code
$arr = array(2, 1, 1, 1, 5, 2 );
$n = sizeof($arr);
$pos = 4;
echo minIndex($arr, $n, $pos);
// This code is contributed by Ryuga
?>
JavaScript
<script>
// Javascript implementation of the approach
// Function to return the minimum required index
function minIndex(arr, n, pos)
{
var num = arr[pos];
// Start from arr[pos - 1]
var i = pos - 1;
while (i >= 0) {
if (arr[i] != num)
break;
i--;
}
// All elements are equal
// from arr[i + 1] to arr[pos]
return i + 1;
}
// Driver code
var arr = [ 2, 1, 1, 1, 5, 2 ];
var n = arr.length;
var pos = 4;
// Function Call
document.write(minIndex(arr, n, pos));
// This code is contributed by rrrtnx.
</script>
Time Complexity: O(N)
Space Complexity: O(1)
Efficient Approach :
Do a binary search in the sub-array [0, pos-1]. Stop condition will be if arr[mid] == arr[pos] && arr[mid-1] != arr[pos]. Go-left or Go-right will depend on if arr[mid] == arr[pos] or not respectively.
Implementation:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the minimum required index
int minIndex(int arr[], int pos)
{
int low = 0;
int high = pos;
int i = pos;
while (low < high) {
int mid = (low + high) / 2;
if (arr[mid] != arr[pos]) {
low = mid + 1;
}
else {
high = mid - 1;
i = mid;
if (mid > 0 && arr[mid - 1] != arr[pos]) {
// Short-circuit more comparisons as found
// the border point
break;
}
}
}
// For cases were high = low + 1 and arr[high] will
// match with
// arr[pos] but not arr[low] or arr[mid]. In such
// iteration the if condition will satisfy and loop will
// break post that low will be updated. Hence i will not
// point to the correct index.
return arr[low] == arr[pos] ? low : i;
}
// Driver code
int main()
{
int arr[] = { 2, 1, 1, 1, 5, 2 };
cout << minIndex(arr, 2) << endl; // Should be 1
cout << minIndex(arr, 3) << endl; // Should be 1
cout << minIndex(arr, 4) << endl; // Should be 4
return 0;
}
// This code is contributed by
// anshbikram
Java
// Java implementation of the approach
public class GFG {
// Function to return the minimum required index
static int minIndex(int arr[], int pos)
{
int low = 0;
int high = pos;
int i = pos;
while (low < high) {
int mid = (low + high) / 2;
if (arr[mid] != arr[pos]) {
low = mid + 1;
}
else {
high = mid - 1;
i = mid;
if (mid > 0 && arr[mid - 1] != arr[pos]) {
// Short-circuit more comparisons as
// found the border point
break;
}
}
}
// For cases were high = low + 1 and arr[high] will
// match with arr[pos] but not arr[low] or arr[mid].
// In such iteration the if condition will satisfy
// and loop will break post that low will be
// updated. Hence i will not point to the correct
// index.
return arr[low] == arr[pos] ? low : i;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 2, 1, 1, 1, 5, 2 };
System.out.println(minIndex(arr, 2)); // Should be 1
System.out.println(minIndex(arr, 3)); // Should be 1
System.out.println(minIndex(arr, 4)); // Should be 4
}
}
// This code is contributed by
// anshbikram
Python3
# Python3 implementation of the approach
# Function to return the minimum
# required index
def minIndex(arr, pos):
low = 0
high = pos
i = pos
while low < high:
mid = (low + high)//2
if arr[mid] != arr[pos]:
low = mid + 1
else:
high = mid - 1
i = mid
if mid > 0 and arr[mid-1] != arr[pos]:
# Short-circuit more comparisons as found the border point
break
# For cases were high = low + 1 and arr[high] will match with
# arr[pos] but not arr[low] or arr[mid]. In such iteration
# the if condition will satisfy and loop will break post that
# low will be updated. Hence i will not point to the correct index.
return low if arr[low] == arr[pos] else i
# Driver code
arr = [2, 1, 1, 1, 5, 2]
print(minIndex(arr, 2)) # Should be 1
print(minIndex(arr, 3)) # Should be 1
print(minIndex(arr, 4)) # Should be 4
# This code is contributed by
# anshbikram
C#
// C# implementation of the approach
using System;
class GFG{
// Function to return the minimum
// required index
static int minIndex(int []arr, int pos)
{
int low = 0;
int high = pos;
int i = pos;
while (low < high)
{
int mid = (low + high) / 2;
if (arr[mid] != arr[pos])
{
low = mid + 1;
}
else
{
high = mid - 1;
i = mid;
if (mid > 0 && arr[mid - 1] != arr[pos])
{
// Short-circuit more comparisons as
// found the border point
break;
}
}
}
// For cases were high = low + 1 and arr[high] will
// match with arr[pos] but not arr[low] or arr[mid].
// In such iteration the if condition will satisfy
// and loop will break post that low will be
// updated. Hence i will not point to the correct
// index.
return arr[low] == arr[pos] ? low : i;
}
// Driver code
public static void Main()
{
int []arr = { 2, 1, 1, 1, 5, 2 };
Console.WriteLine(minIndex(arr, 2)); // Should be 1
Console.WriteLine(minIndex(arr, 3)); // Should be 1
Console.WriteLine(minIndex(arr, 4)); // Should be 4
}
}
// This code is contributed by chitranayal
JavaScript
<script>
// javascript implementation of the approach
// Function to return the minimum required index
function minIndex(arr , pos) {
var low = 0;
var high = pos;
var i = pos;
while (low < high) {
var mid = parseInt((low + high) / 2);
if (arr[mid] != arr[pos]) {
low = mid + 1;
} else {
high = mid - 1;
i = mid;
if (mid > 0 && arr[mid - 1] != arr[pos]) {
// Short-circuit more comparisons as
// found the border point
break;
}
}
}
// For cases were high = low + 1 and arr[high] will
// match with arr[pos] but not arr[low] or arr[mid].
// In such iteration the if condition will satisfy
// and loop will break post that low will be
// updated. Hence i will not point to the correct
// index.
return arr[low] == arr[pos] ? low : i;
}
// Driver code
var arr = [ 2, 1, 1, 1, 5, 2 ];
document.write(minIndex(arr, 2)+"<br/>"); // Should be 1
document.write(minIndex(arr, 3)+"<br/>"); // Should be 1
document.write(minIndex(arr, 4)+"<br/>"); // Should be 4
// This code is contributed by todaysgaurav
</script>
Time Complexity: O(log(n))
Space Complexity: O(1)
Similar Reads
Queries for the minimum element in an array excluding the given index range
Given an array arr[] of N integers and Q queries where each query consists of an index range [L, R]. For each query, the task is to find the minimum element in the array excluding the elements from the given index range. Examples: Input: arr[] = {3, 2, 1, 4, 5}, Q[][] = {{1, 2}, {2, 3}} Output: 3 2
15+ min read
Minimum 0s to be inserted in Array such that no element is same as its index
Given an array A = [A0, A1, A2, . . ., AN-1]. Perform the following operation: Total count of indices with value same as their positions.At each step, insert 0 at one of such positions.Repeat till no more elements exist whose value is same as the index. The task is to find the minimum number of inse
6 min read
Minimum sum of two elements from two arrays such that indexes are not same
Given two arrays a[] and b[] of same size. Task is to find minimum sum of two elements such that they belong to different arrays and are not at same index in their arrays. Examples: Input : a[] = {5, 4, 13, 2, 1} b[] = {2, 3, 4, 6, 5}Output : 3We take 1 from a[] and 2 from b[]Sum is 1 + 2 = 3.Input
15+ min read
Number of indexes with equal elements in given range
Given N numbers and Q queries, every query consists of L and R, task is to find the number of such integers i (L<=i<R) such that Ai=Ai+1. Consider 0-based indexing. Examples : Input : A = [1, 2, 2, 2, 3, 3, 4, 4, 4] Q = 2 L = 1 R = 8 L = 0 R = 4 Output : 5 2 Explanation: We have 5 index i whic
12 min read
Find the index with minimum score from a given array
Given an array A[] of size N(1 ? N ? 105), consisting of positive integers, where the score of an index i in range [0, N - 1] is defined as: Score[i] = A[i] * ((i + A[i] < N) ? Score(i + A[i]) : 1) The task is to find the index with minimum score. Examples: Input: A[] = {1, 2, 3, 4, 5}Output: 2Ex
5 min read
Minimum steps to reach a given index in the Array based on given conditions
Given an array arr[ ] of size N consisting of integers -1, 0, 1 only and an array q[ ] consisting of queries. In the array arr[ ], -1 signifies that any index to the left of it is reachable and 1 signifies that any index to the right of it is reachable from that index. The index in a particular quer
10 min read
Minimum number of increment-other operations to make all array elements equal.
We are given an array consisting of n elements. At each operation we can select any one element and increase rest of n-1 elements by 1. We have to make all elements equal performing such operation as many times you wish. Find the minimum number of operations needed for this. Examples: Input: arr[] =
5 min read
Minimum cost to make all elements with same frequency equal
Given an array arr[] of integers, the task is to find the minimum cost for making all the integers that have the same frequency equal. By performing one operation you can either increase the current integer by 1 or decrease it by 1. Examples: Input: arr[] = {1, 2, 3, 2, 6, 5, 6}Output: 12Explanation
9 min read
Find the minimum number of operations required to make all array elements equal
Given an array arr[] of size N. The task is to make all the array elements equal by applying the below operations minimum number of times: Choose a pair of indices (i, j) such that |i - j| = 1 (indices i and j are adjacent) and set arr[i] = arr[i] + |arr[i] - arr[j]|Choose a pair of indices (i, j) s
6 min read
Minimum operation to make all elements equal in array
Given an array consisting of n positive integers, the task is to find the minimum number of operations to make all elements equal. In each operation, we can perform addition, multiplication, subtraction, or division with any number and an array element. Examples: Input : arr[] = [1, 2, 3, 4]Output :
11 min read