Minimum index i such that all the elements from index i to given index are equal

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 indexint 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 codeint 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 indexfunction 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 codeconst arr = [2, 1, 1, 1, 5, 2];const n = arr.length;const pos = 4;Â
// Function callconsole.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 codearr = [2, 1, 1, 1, 5, 2]n = len(arr)pos = 4Â
# Function callprint(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 indexint 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 codeint 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 approachimport 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 indexdef 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 codearr = [2, 1, 1, 1, 5, 2 ]n = len(arr)pos = 4Â
# Function Callprint(minIndex(arr, n, pos))Â
# This code is contributed by # Mohit Kumar 29 |
C#
// C# implementation of the approachusing 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 indexfunction 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 codevar arr = [ 2, 1, 1, 1, 5, 2 ];var n = arr.length;var pos = 4;Â
// Function Calldocument.write(minIndex(arr, n, pos));Â
Â
// This code is contributed by rrrtnx.</script> |
4
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 indexint 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 codeint 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 codearr = [2, 1, 1, 1, 5, 2]Â
print(minIndex(arr, 2))Â # Should be 1print(minIndex(arr, 3))Â # Should be 1print(minIndex(arr, 4))Â # Should be 4Â
# This code is contributed by# anshbikram |
C#
// C# implementation of the approachusing System;Â
class GFG{Â Â Â Â Â // Function to return the minimum // required indexstatic 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 codepublic 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> |
1 1 4
Time Complexity: O(log(n))
Space Complexity: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



