Given an array of n 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, -5, 0, 3, 7} Output: 3 // arr[3] == 3 Input: arr[] = {-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13} Output: 2 // arr[2] == 2 Input: arr[] = {-10, -5, 3, 4, 7, 9} Output: -1 // No Fixed Point
We have a solution to find fixed point in an array of distinct elements. In this post, solution for an array with duplicate values is discussed.
Consider the arr[] = {-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13}, arr[mid] = 3
If elements are not distinct, then we see arr[mid] < mid, we cannot conclude which side the fixed is on. It could be on the left side or on the right side. We know for sure that since arr[5] = 3, arr[4] couldn’t be magic index because arr[4] must be less than or equal to arr[5] (the array is Sorted). So, the general pattern of our search would be:Â
- Left Side: start = start, end = min(arr[midIndex], midIndex-1)
- Right Side: start = max(arr[midIndex], midIndex+1), end = end
Below is the code for the above Algorithm.
C++
// CPP Program to find magic index. #include <bits/stdc++.h> using namespace std; Â
int magicIndex( int * arr, int start, int end) { Â Â Â Â // If No Magic Index return -1; Â Â Â Â if (start > end) Â Â Â Â Â Â Â Â return -1; Â
    int midIndex = (start + end) / 2;     int midValue = arr[midIndex]; Â
    // Magic Index Found, return it.     if (midIndex == midValue)         return midIndex; Â
    // Search on Left side     int left = magicIndex(arr, start, min(midValue,                                      midIndex - 1)); Â
    // If Found on left side, return.     if (left >= 0)         return left; Â
    // Return ans from right side.     return magicIndex(arr, max(midValue, midIndex + 1),                                                   end); } Â
// Driver program int main() {     int arr[] = { -10, -5, 2, 2, 2, 3, 4, 7,                                  9, 12, 13 };     int n = sizeof (arr) / sizeof (arr[0]);     int index = magicIndex(arr, 0, n - 1);     if (index == -1)         cout << "No Magic Index" ;     else         cout << "Magic Index is : " << index;     return 0; } |
Java
// Java Program to find magic index. Â
class GFG {          static int magicIndex( int arr[], int start, int end)     {         // If No Magic Index return -1;         if (start > end)             return - 1 ;              int midIndex = (start + end) / 2 ;         int midValue = arr[midIndex];              // Magic Index Found, return it.         if (midIndex == midValue)             return midIndex;              // Search on Left side         int left = magicIndex(arr, start, Math.min(midValue,                                             midIndex - 1 ));              // If Found on left side, return.         if (left >= 0 )             return left;              // Return ans from right side.         return magicIndex(arr, Math.max(midValue,                                 midIndex + 1 ),end);     } Â
    // Driver code     public static void main (String[] args)     {         int arr[] = { - 10 , - 5 , 2 , 2 , 2 , 3 , 4 , 7 ,                     9 , 12 , 13 };         int n = arr.length;         int index = magicIndex(arr, 0 , n - 1 );         if (index == - 1 )             System.out.print( "No Magic Index" );         else             System.out.print( "Magic Index is : " +index);     } } Â
// This code is contributed by Anant Agarwal. |
Python 3
# Python 3 Program to find # magic index. Â
def magicIndex(arr, start, end): Â
    # If No Magic Index return -1     if (start > end):         return - 1 Â
    midIndex = int ((start + end) / 2 )     midValue = arr[midIndex] Â
    # Magic Index Found, return it.     if (midIndex = = midValue):         return midIndex Â
    # Search on Left side     left = magicIndex(arr, start, min (midValue,                                 midIndex - 1 )) Â
    # If Found on left side, return.     if (left > = 0 ):         return left Â
    # Return ans from right side.     return magicIndex(arr, max (midValue,                         midIndex + 1 ),                                     end) Â
# Driver program arr = [ - 10 , - 5 , 2 , 2 , 2 , 3 , 4 , 7 , 9 , 12 , 13 ] n = len (arr) Â
index = magicIndex(arr, 0 , n - 1 ) Â
if (index = = - 1 ): Â Â Â Â print ( "No Magic Index" ) else : Â Â Â Â print ( "Magic Index is :" , index) Â
# This code is contributed by Smitha Dinesh Semwal |
C#
// C# Program to find magic index. using System; Â
class GFG {          static int magicIndex( int []arr, int start,                                     int end)     {         // If No Magic Index return -1;         if (start > end)             return -1;              int midIndex = (start + end) / 2;         int midValue = arr[midIndex];              // Magic Index Found, return it.         if (midIndex == midValue)             return midIndex;              // Search on Left side         int left = magicIndex(arr, start, Math.Min(midValue,                                             midIndex - 1));              // If Found on left side, return.         if (left >= 0)             return left;              // Return ans from right side.         return magicIndex(arr, Math.Max(midValue,                                 midIndex + 1),end);     } Â
    // Driver code     public static void Main ()     {         int []arr = { -10, -5, 2, 2, 2, 3,                         4, 7, 9, 12, 13 };                  int n = arr.Length;                  int index = magicIndex(arr, 0, n - 1);                  if (index == -1)             Console.WriteLine( "No Magic Index" );         else             Console.WriteLine( "Magic Index is : " +                                             index);     } } Â
// This code is contributed by vt_m. |
PHP
<?php // PHP Program to find magic index. Â
function magicIndex( $arr , $start , $end ) { Â Â Â Â Â Â Â Â Â // If No Magic Index return -1; Â Â Â Â if ( $start > $end ) Â Â Â Â Â Â Â Â return -1; Â
    $midIndex = floor (( $start + $end ) / 2);     $midValue = $arr [ $midIndex ]; Â
    // Magic Index Found, return it.     if ( $midIndex == $midValue )         return $midIndex ; Â
    // Search on Left side     $left = magicIndex( $arr , $start ,             min( $midValue , $midIndex - 1)); Â
    // If Found on left side, return.     if ( $left >= 0)         return $left ; Â
    // Return ans from right side.     return magicIndex( $arr , max( $midValue ,                      $midIndex + 1), $end ); }          // Driver Code     $arr = array (-10, -5, 2, 2, 2, 3,                      4, 7, 9, 12, 13);     $n = sizeof( $arr );     $index = magicIndex( $arr , 0, $n - 1);     if ( $index == -1)         echo "No Magic Index" ;     else         echo "Magic Index is : " , $index ;      // This code is contributed by nitin mittal ?> |
Javascript
<script> // JavaScript Program to find magic index. Â
function magicIndex(arr, start, end) { Â Â Â Â // If No Magic Index return -1; Â Â Â Â if (start > end) Â Â Â Â Â Â Â Â return -1; Â
    let midIndex = Math.floor((start + end) / 2);     let midValue = arr[midIndex]; Â
    // Magic Index Found, return it.     if (midIndex == midValue)         return midIndex; Â
    // Search on Left side     let left = magicIndex(arr, start, Math.min(midValue,                                     midIndex - 1)); Â
    // If Found on left side, return.     if (left >= 0)         return left; Â
    // Return ans from right side.     return magicIndex(arr, Math.max(midValue, midIndex + 1),                                                 end); } Â
// Driver program     let arr = [ -10, -5, 2, 2, 2, 3, 4, 7,                                 9, 12, 13 ];     let n = arr.length;     let index = magicIndex(arr, 0, n - 1);     if (index == -1)         document.write( "No Magic Index" );     else         document.write( "Magic Index is : " + index); Â
Â
Â
Â
// This code is contributed by Surbhi Tyagi. </script> |
Magic Index is : 2
Time Complexity: O(N)
Auxiliary Space: O(1)
Approach 2: Using a linear search
In this approach, we use a linear search to traverse the array and check if any element is equal to its index. If we find such an element, we return its index as the fixed point. If no such element is found, we return -1 to indicate that no fixed point exists.
- Initialize an integer variable n to the size of the input array.
- Traverse the array from left to right using a for loop with index variable i running from 0 to n-1.
- Check if the element at index i is equal to i.
- If it is, return i as the fixed point.
- If no fixed point is found in the entire array, return -1 to indicate that no fixed point exists.
C++
#include <iostream> #include <vector> using namespace std; Â
int findFixedPoint(vector< int >& arr) { Â Â Â Â int n = arr.size(); Â Â Â Â for ( int i = 0; i < n; i++) { Â Â Â Â Â Â Â Â if (arr[i] == i) { Â Â Â Â Â Â Â Â Â Â Â Â return i; Â Â Â Â Â Â Â Â } Â Â Â Â } Â Â Â Â return -1; } Â
int main() { Â Â Â Â vector< int > arr = { -10, -5, 2, 2, 2, 3, 4, 7, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 9, 12, 13 }; Â Â Â Â int fixedPoint = findFixedPoint(arr); Â Â Â Â if (fixedPoint == -1) { Â Â Â Â Â Â Â cout << "No Magic Index" ; Â Â Â Â } else { Â Â Â Â Â Â Â Â Â cout << "Magic Index is : " << fixedPoint << endl; Â Â Â Â } Â Â Â Â return 0; } |
Java
import java.util.*; Â
class Main { Â
  // Define a function to find the magic index in an array   static int findFixedPoint( int [] arr)   { Â
    // Get the length of the array     int n = arr.length; Â
    // Loop through the array     for ( int i = 0 ; i < n; i++)     { Â
      // If the value at the current index is equal to       // the index itself       if (arr[i] == i)       { Â
        // Return the index         return i;       }     }     // If no magic index is found, return -1     return - 1 ;   } Â
  public static void main(String[] args)   { Â
    // Create an array     int [] arr       = { - 10 , - 5 , 2 , 2 , 2 , 3 , 4 , 7 , 9 , 12 , 13 }; Â
    // Call the findFixedPoint function to find the     // magic index     int fixedPoint = findFixedPoint(arr); Â
    // If no magic index is found, print "No Magic     // Index"     if (fixedPoint == - 1 ) {       System.out.println( "No Magic Index" );     }     // If a magic index is found, print the index     else {       System.out.println( "Magic Index is : "                          + fixedPoint);     }   } } |
Python3
# Define a function to find the magic index in an array def findFixedPoint(arr):     # Get the length of the array     n = len (arr)     # Loop through the array     for i in range (n):         # If the value at the current index is equal to the index itself         if arr[i] = = i:             # Return the index             return i     # If no magic index is found, return -1     return - 1 Â
Â
# Create an array arr = [ - 10 , - 5 , 2 , 2 , 2 , 3 , 4 , 7 , 9 , 12 , 13 ] # Call the findFixedPoint function to find the magic index fixedPoint = findFixedPoint(arr) # If no magic index is found, print "No Magic Index" if fixedPoint = = - 1 : Â Â Â Â print ( "No Magic Index" ) # If a magic index is found, print the index else : Â Â Â Â print (f "Magic Index is : {fixedPoint}" ) |
C#
using System; using System.Collections.Generic; Â
class Program { Â Â Â Â static int FindFixedPoint(List< int > arr) Â Â Â Â { Â Â Â Â Â Â Â Â int n = arr.Count; Â Â Â Â Â Â Â Â for ( int i = 0; i < n; i++) { Â Â Â Â Â Â Â Â Â Â Â Â if (arr[i] == i) { Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â return i; Â Â Â Â Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â return -1; Â Â Â Â } Â
    static void Main( string [] args)     {         List< int > arr = new List< int >{ -10, -5, 2, 2, 2, 3,                                        4,  7, 9, 12, 13 };         int fixedPoint = FindFixedPoint(arr);         if (fixedPoint == -1) {             Console.WriteLine( "No Magic Index" );         }         else {             Console.WriteLine( "Magic Index is: "                               + fixedPoint);         }     } } |
PHP
<?php Â
function findFixedPoint( $arr ) { Â Â Â Â $n = count ( $arr ); Â Â Â Â for ( $i = 0; $i < $n ; $i ++) { Â Â Â Â Â Â Â Â if ( $arr [ $i ] == $i ) { Â Â Â Â Â Â Â Â Â Â Â Â return $i ; Â Â Â Â Â Â Â Â } Â Â Â Â } Â Â Â Â return -1; } Â
$arr = [-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13]; $fixedPoint = findFixedPoint( $arr ); if ( $fixedPoint == -1) { Â Â Â Â echo "No fixed point" ; } else { Â Â Â Â echo "Fixed point is : " . $fixedPoint ; } Â
?> |
Javascript
// Define a function to find the magic index in an array function findFixedPoint(arr) { Â
    // Get the length of the array     let n = arr.length;          // Loop through the array     for (let i = 0; i < n; i++) {              // If the value at the current index is equal to     // the index itself         if (arr[i] == i) {                      // Return the index             return i;         }     }          // If no magic index is found, return -1     return -1; } Â
let arr = [-10, -5, 2, 2, 2, 3, 4, 7,     9, 12, 13];          // Call the findFixedPoint function to find the     // magic index let fixedPolet = findFixedPoint(arr); Â
// If no magic index is found, print "No Magic     // Index" if (fixedPolet == -1) {     console.log( "No Magic Index" ); } else {     console.log( "Magic Index is : " + fixedPolet); } Â
// This code is contributed by akashish__ |
Magic Index is : 2
Time Complexity: O(N)
Auxiliary Space: O(1)
Approach 3: Using Hashing
- Create a set of the input array.
- Loop through the array and check if the current element is present in the set and also equal to its index. If yes, return the index.
- If no fixed point is found, return -1.
Here is the implementation of above approach:
C++
#include <iostream> #include <unordered_set> #include <vector> Â
int findFixedPoint(std::vector< int >& arr) { Â Â Â Â std::unordered_set< int > s; Â Â Â Â for ( int i = 0; i < arr.size(); i++) { Â Â Â Â Â Â Â Â if (s.find(arr[i]) != s.end() || arr[i] == i) { Â Â Â Â Â Â Â Â Â Â Â Â return i; Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â s.insert(arr[i]); Â Â Â Â } Â Â Â Â return -1; } Â
int main() { Â Â Â Â std::vector< int > arr = {-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13}; Â Â Â Â int fixedPoint = findFixedPoint(arr); Â Â Â Â if (fixedPoint == -1) { Â Â Â Â Â Â Â Â std::cout << "No fixed point" << std::endl; Â Â Â Â } else { Â Â Â Â Â Â Â Â std::cout << "Fixed point is : " << fixedPoint << std::endl; Â Â Â Â } Â Â Â Â return 0; } |
Java
import java.util.HashSet; Â
public class FixedPoint { Â Â Â Â public static int findFixedPoint( int [] arr) { Â Â Â Â Â Â Â Â HashSet<Integer> set = new HashSet<>(); Â Â Â Â Â Â Â Â for ( int i = 0 ; i < arr.length; i++) { Â Â Â Â Â Â Â Â Â Â Â Â if (set.contains(arr[i]) || arr[i] == i) { Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â return i; Â Â Â Â Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â Â Â Â Â set.add(arr[i]); Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â return - 1 ; Â Â Â Â } Â
    public static void main(String[] args) {         int [] arr = {- 10 , - 5 , 2 , 2 , 2 , 3 , 4 , 7 , 9 , 12 , 13 };         int fixedPoint = findFixedPoint(arr);         if (fixedPoint == - 1 ) {             System.out.println( "No fixed point" );         } else {             System.out.println( "Fixed point is : " + fixedPoint);         }     } } |
Python3
def findFixedPoint(arr):     s = set (arr)     for i in range ( len (arr)):         if arr[i] in s and arr[i] = = i:             return i     return - 1 Â
# Create an array arr = [ - 10 , - 5 , 2 , 2 , 2 , 3 , 4 , 7 , 9 , 12 , 13 ] # Call the findFixedPoint function to find the fixed point fixedPoint = findFixedPoint(arr) # If no fixed point is found, print "No fixed point" if fixedPoint = = - 1 : Â Â Â Â print ( "No fixed point" ) # If a fixed point is found, print the index else : Â Â Â Â print (f "Fixed point is : {fixedPoint}" ) |
C#
using System; using System.Collections.Generic; Â
class Program { Â Â Â Â static int FindFixedPoint( int [] arr) Â Â Â Â { Â Â Â Â Â Â Â Â HashSet< int > set = new HashSet< int >(); Â Â Â Â Â Â Â Â for ( int i = 0; i < arr.Length; i++) Â Â Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â Â Â Â if ( set .Contains(arr[i]) || arr[i] == i) Â Â Â Â Â Â Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â return i; Â Â Â Â Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â Â Â Â Â set .Add(arr[i]); Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â return -1; Â Â Â Â } Â
    static void Main( string [] args)     {         int [] arr = {-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13};         int fixedPoint = FindFixedPoint(arr);         if (fixedPoint == -1)         {             Console.WriteLine( "No fixed point" );         }         else         {             Console.WriteLine( "Fixed point is : " + fixedPoint);         }     } } |
PHP
<?php     function findFixedPoint( $arr ) {     $set = array ();     for ( $i = 0; $i < count ( $arr ); $i ++)     {         if (in_array( $arr [ $i ], $set ) || $arr [ $i ] == $i )         {             return $i ;         }         $set [] = $arr [ $i ];     }     return -1; } Â
$arr = array (-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13); $fixedPoint = findFixedPoint( $arr ); if ( $fixedPoint == -1) { Â Â Â Â echo "No fixed point" ; } else { Â Â Â Â echo "Fixed point is : " . $fixedPoint ; } Â
?> |
Javascript
function findFixedPoint(arr) { Â Â Â Â let set = new Set(); Â Â Â Â for (let i = 0; i < arr.length; i++) Â Â Â Â { Â Â Â Â Â Â Â Â if (set.has(arr[i]) && arr[i] == i) Â Â Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â Â Â Â return i; Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â set.add(arr[i]); Â Â Â Â } Â Â Â Â return -1; } Â
let arr = [-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13]; let fixedPoint = findFixedPoint(arr); if (fixedPoint == -1) { Â Â Â Â console.log( "No fixed point" ); } else { Â Â Â Â console.log( "Fixed point is : " + fixedPoint); } |
Fixed point is : 2
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!