Find a Fixed Point in an array with duplicates allowed

Given an array of n duplicates or distinct integers sorted in ascending order, write a function that returns a Fixed Point in the array, if there is any Fixed Point present in the array, else returns -1. Fixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in the array can be negative.

Examples :

Input : arr[] = {-10, -1, 3, 3, 10, 30, 30, 50, 100} 
Output: 3  
Note : arr[3] == 3 

Input: arr[] = {0, 2, 5, 8, 17}
Output: 0  

Input: arr[] = {-10, -5, 3, 4, 7, 9}
Output: -1  
No Fixed Point

We have already discussed find a Fixed Point in a given array of n distinct integers.



If elements are not distinct, then previously discussed algorithm fails. Consider the following array:

 // with duplicates value 
 Input : arr[] = {-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13}; 
 Wrong Output : -1  // but arr[2] == 2 

When we see that A [mid] < mid, we cannot conclude which side the fixed index is on. It could be on the right side, as before. Or, it could be on the left side (as it, in fact, is).

Could it be anywhere on the left side? Not exactly. Since A[ 5] = 3, we know that A[ 4] couldn't be a fixed index. A[ 4] would need to be 4 to be the fixed index, but A[ 4] must be less than or equal to A[ 5].

In fact, when we see that A[ 5] = 3, we'll need to recursively search the right side as before. But, to search the left side, we can skip a bunch of elements and only recursively search elements A [ 0] through A [ 3]. A[ 3] is the first element that could be a fixed index.

The general pattern is that we compare mid Index and midValue for equality first. Then, if they are not equal, we recursively search the left and right sides as follows:

    Left side: search indices start through min (mid – 1, midValue ).
    Right side: search indices max(mid + 1, midValue) through end.

code below implements this algorithm.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find fixed 
// index using binary search
#include<bits/stdc++.h>
  
using namespace std;
  
// Main Function to find fixed 
// index using binary search
int binarySearch(int arr[], int low, 
                        int high)
{
    if (high < low)
        return -1;
      
    // low + (high - low) / 2
    int mid = (low + high) / 2; 
    int midValue = arr[mid];
  
    if (mid == arr[mid])
        return mid;
  
    // Search left 
    int leftindex = min(mid - 1, midValue);
    int left = binarySearch(arr, low, leftindex);
  
    if (left >= 0)
        return left;
  
    // Search right
    int rightindex = max(mid + 1, midValue);
    int right = binarySearch(arr, rightindex, high);
  
    return right;
}
  
// Driver code
int main()
{
    // input 1
    int arr[] = {-10, -5, 2, 2, 2,  
                 3, 4, 7, 9, 12, 13};
                   
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Fixed Point is "
         << binarySearch(arr, 0, n - 1);
  
    // input 2
    int arr1[] = {-10, -1, 3, 3, 10, 
                    30, 30, 50, 100};
                      
    int n1 = sizeof(arr) / sizeof(arr1[0]);
      
    cout << "\nFixed Point is "
         << binarySearch(arr1, 0, n1 - 1);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of find fixed 
// index using binary search
class GFG
{
    // Main Function to find fixed 
    // index using binary search
    static int binarySearch(int arr[], int low, 
                                      int high)
    {
        if (high < low)
            return -1;
      
        // low + (high - low) / 2
        int mid = (low + high) / 2
        int midValue = arr[mid];
      
        if (mid == arr[mid])
            return mid;
      
        // Search left
        int leftindex = Math.min(mid - 1, midValue);
        int left = binarySearch(arr, low, leftindex);
      
        if (left >= 0)
            return left;
      
        // Search right
        int rightindex = Math.max(mid + 1, midValue);
        int right = binarySearch(arr, rightindex, high);
  
        return right;
    }
      
    // Driver code
    public static void main(String[] args) 
    {
        // input 1
        int arr[] = {-10, -5, 2, 2, 2
                     3, 4, 7, 9, 12, 13};
                       
        System.out.println("Fixed Point is "
            binarySearch(arr, 0, arr.length - 1));
          
        // input 2
        int arr1[] = {-10, -1, 3, 3, 10,
                        30, 30, 50, 100};
                          
        System.out.println("Fixed Point is "
            binarySearch(arr1, 0, arr1.length - 1));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implementation to find fixed 
# index using binary search
  
# Main Function to find fixed 
# index using binary search
def binarySearch(arr, low, high):
    if (high < low):
        return -1
      
    # low + (high - low) / 2
    mid = int((low + high) / 2)
    midValue = arr[mid]
  
    if (mid == arr[mid]):
        return mid
  
    # Search left 
    leftindex = min(mid - 1, midValue)
    left = binarySearch(arr, low, leftindex)
  
    if (left >= 0):
        return left
  
    # Search right
    rightindex = max(mid + 1, midValue)
    right = binarySearch(arr, rightindex, high)
  
    return right
  
# Driver code
if __name__ == '__main__':
      
    # input 1
    arr = [-10, -5, 2, 2, 2, 3,
               4, 7, 9, 12, 13]
                  
    n = len(arr)
    print("Fixed Point is"
           binarySearch(arr, 0, n - 1))
  
    # input 2
    arr1 = [-10, -1, 3, 3, 10
              30, 30, 50, 100]
                      
    n1 = len(arr)
      
    print("Fixed Point is"
           binarySearch(arr1, 0, n1 - 1))
      
# This code is contributed by
# Shashank_Sharma

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of find fixed 
// index using binary search
using System;
  
class GFG
{
    // Main Function to find fixed 
    // index using binary search
    static int binarySearch(int []arr, int low,
                                      int high)
    {
        if (high < low)
            return -1;
      
        // low + (high - low) / 2
        int mid = (low + high) / 2; 
        int midValue = arr[mid];
      
        if (mid == arr[mid])
            return mid;
      
        // Search left
        int leftindex = Math.Min(mid - 1, midValue);
        int left = binarySearch(arr, low, leftindex);
      
        if (left >= 0)
            return left;
      
        // Search right
        int rightindex = Math.Max(mid + 1, midValue);
        int right = binarySearch(arr, rightindex, high);
      
        return right;
    }
      
    // Driver Code
    public static void Main() 
    {
        // input 1
        int []arr = {-10, -5, 2, 2, 2,  
                     3, 4, 7, 9, 12, 13};
                       
        Console.WriteLine("Fixed Point is "
            binarySearch(arr, 0, arr.Length - 1));
          
        // input 2
        int []arr1 = {-10, -1, 3, 3, 10, 
                       30, 30, 50, 100};
                         
        Console.Write("Fixed Point is "
            binarySearch(arr1, 0, arr1.Length - 1));
    }
}
  
// This code is contributed by nitin mittal.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP implementation to 
// find fixed index using
// binary search
  
// Main Function to find fixed 
// index using binary search
function binarySearch($arr
                      $low
                      $high)
{
    if ($high < $low)
        return -1;
      
    // low + (high - low) / 2
    $mid = floor(($low + $high) / 2); 
    $midValue = $arr[$mid];
  
    if ($mid == $arr[$mid])
        return $mid;
  
    // Search left 
    $leftindex = min($mid - 1, 
                     $midValue);
    $left = binarySearch($arr, $low
                         $leftindex);
  
    if ($left >= 0)
        return $left;
  
    // Search right
    $rightindex = max($mid + 1, 
                      $midValue);
    $right = binarySearch($arr
                          $rightindex
                          $high);
  
    return $right;
}
  
// Driver code
  
// input 1
$arr = array(-10, -5, 2, 2, 2, 3, 
                4, 7, 9, 12, 13);
              
$n = sizeof($arr) / sizeof($arr[0]);
echo "Fixed Point is "
      binarySearch($arr, 0, $n - 1);
  
// input 2
$arr1 = array(-10, -1, 3, 3, 10, 
               30, 30, 50, 100);
                  
$n1 = sizeof($arr) / sizeof($arr1[0]);
  
echo "\nFixed Point is ",
     binarySearch($arr1, 0, $n1 - 1);
  
// This code is contributed by nitin mittal.
?>

chevron_right



Output :

Fixed Point is  2
Fixed Point is  3

Algorithmic Paradigm : Divide & Conquer
Time Complexity : O(Logn)

This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.