19
5/12/12 Find a Fixed Point in a given array | GeeksforGeeks 1/19 www.geeksforgeeks.org/archives/15946 GeeksforGeeks A computer science portal for geeks Home Q&A Interview Corner Ask a question Feedback Contribute About us Subscribe Arrays Articles Bit Magic C/C++ Puzzles GFacts Linked Lists MCQ Misc Output Strings Trees Find a Fixed Point in a given array December 1, 2011 Given an array of n 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 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 array can be negative. Examples: Input: arr[] = {-10, -5, 0, 3, 7} Output: 3 // arr[3] == 3 Input: arr[] = {0, 2, 5, 8, 17} Output: 0 // arr[0] == 0

Find a Fixed Point in a Given Array _ GeeksforGeeks

Embed Size (px)

Citation preview

Page 1: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

1/19www.geeksforgeeks.org/archives/15946

GeeksforGeeks

A computer science portal for geeks

HomeQ&AInterview CornerAsk a question

FeedbackContributeAbout us

SubscribeArraysArticlesBit MagicC/C++ PuzzlesGFactsLinked ListsMCQMiscOutputStringsTrees

Find a Fixed Point in a given array

December 1, 2011

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

Examples:

Input: arr[] = {-10, -5, 0, 3, 7} Output: 3 // arr[3] == 3

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

Page 2: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

2/19www.geeksforgeeks.org/archives/15946

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

Asked by rajk

Method 1 (Linear Search) Linearly search for an index i such that arr[i] == i. Return the first such index found. Thanksto pm for suggesting this solution.

Time Complexity: O(n)

Method 2 (Binary Search)First check whether middle element is Fixed Point or not. If it is, then return it; otherwisecheck whether index of middle element is greater than value at the index. If index is greater,then Fixed Point(s) lies on the right side of the middle point (obviously only if there is a FixedPoint). Else the Fixed Point(s) lies on left side.

int linearSearch(int arr[], int n){ int i; for(i = 0; i < n; i++) { if(arr[i] == i) return i; } /* If no fixed point present then return -1 */ return -1;} /* Driver program to check above functions */int main(){ int arr[10] = {-10, -1, 0, 3, 10, 11, 30, 50, 100}; int n = sizeof(arr)/sizeof(arr[0]); printf("Fixed Point is %d", linearSearch(arr, n)); getchar(); return 0;}

int binarySearch(int arr[], int low, int high){ if(high >= low) { int mid = (low + high)/2; /*low + (high - low)/2;*/

Page 3: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

3/19www.geeksforgeeks.org/archives/15946

Algorithmic Paradigm: Divide & ConquerTime Complexity: O(Logn)

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

You may also like following posts

1. Search an element in a sorted and pivoted array2. Find whether an array is subset of another array | Added Method 33. Count the number of occurrences in a sorted array4. Check for Majority Element in a sorted array5. Floor and Ceiling in a sorted array

25 comments so far

1. Anon says:

if(mid == arr[mid]) return mid; if(mid > arr[mid]) return binarySearch(arr, (mid + 1), high); else return binarySearch(arr, low, (mid -1)); } /* Return -1 if there is no Fixed Point */ return -1;} /* Driver program to check above functions */int main(){ int arr[10] = {-10, -1, 0, 3, 10, 11, 30, 50, 100}; int n = sizeof(arr)/sizeof(arr[0]); printf("Fixed Point is %d", binarySearch(arr, 0, n-1)); getchar(); return 0;}

Send 5people

Microsoft® Private CloudMicrosoft® Private Cloud: Built for the Future. Ready Now. Learn More!

Microsoft.com/readynow

Page 4: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

4/19www.geeksforgeeks.org/archives/15946

April 21, 2012 at 6:40 PM

The binary search method will not work in case of duplicate elements in the array,because we can't eliminate one part of the array in each iteration.

Reply2. Avi says:

April 12, 2012 at 8:17 PM

Reply3. PsychoCoder says:

March 10, 2012 at 1:14 PM

In the function this portion is fixed irrespective of the given data.

So, if my input is

#include<stdio.h>#include<conio.h>int main(){ int arr[] = {-10, -5, 3, 4, 7, 9}; int len = sizeof(arr)/sizeof(int); static int flag; int num = -1; for(int i = 0; i<len; i++) { if(arr[i] == i) { flag = 1; num = arr[i]; break; } } printf("%d \n", num); getch(); }

if(mid > arr[mid]) return binarySearch(arr, (mid + 1), high);else return binarySearch(arr, low, (mid -1));

Page 5: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

5/19www.geeksforgeeks.org/archives/15946

then 5(mid) < 11 (arr[mid]) so it will neglect right hand side the value '9' which isplaced at arr[9].

ReplyYogesh Batra says:April 8, 2012 at 4:12 PM

This is clearly given that sequence is in increasing order, find some other counterexample for binary look up method.

Reply4. kartikaditya says:

February 20, 2012 at 11:22 AM

#include <iostream>#include <stdio.h>

using namespace std;

int getFixedPoint(int a[], int n) {int start = 0, end = n - 1, mid = 0;while (start <= end) {mid = (start + end) >> 1;if (a[mid] == mid) {return mid;} else if (a[mid] < mid) {start = mid + 1;} else {end = mid - 1;}}return -1;}

int main() {int a1[] = {-10, -5, 0, 3, 7};cout << getFixedPoint(a1, 5) << endl;int a2[] = {0, 2, 5, 8, 17};cout << getFixedPoint(a2, 5) << endl;int a3[] = {-10, -5, 3, 4, 7, 9};cout << getFixedPoint(a3, 6) << endl;int a4[] = {-10, 1, 2, 3, 10, 11, 30, 50, 100};cout << getFixedPoint(a4, 9) << endl;

int arr[10] = {-10, -1, 0, 6, 10, 11, 30, 50, 100, 9};

Page 6: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

6/19www.geeksforgeeks.org/archives/15946

return 0;}

Reply5. vijay_kansal says:

February 15, 2012 at 3:25 PM

An optimized algorithm for the case when elements can be repeated in the array :

The algo will return 1st element that is a fixed pt.

Replyvijay_kansal says:February 19, 2012 at 10:35 AM

An error correction,Replace the if condition of while loop by :

Reply6. Nages says:

February 10, 2012 at 6:55 AM

int fixed_pt(int *a,int n){ int l=0,h=n-1,m,i; while(l<=h) { m=(l+h)/2; if(a[m]>=0) h=m-1; else l=m+1; }// finding the 1st element(it will be a[l]) >=0 for(i=l;i<n;i=a[i]) { if(a[i]==i) return i; } return -1;}

if(a[m]>=m)

public class FixedPointInArray { public static void main(String[] arg) {

Page 7: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

7/19www.geeksforgeeks.org/archives/15946

Reply7. Karthick says:

December 27, 2011 at 6:19 PM

I think, the following code can find the first Fixed Point.It would be good if someone can check this code for correctness.

int findFirstFixedPoint(int a[],int length){if(length==0){ return -1; }int start=0,end=length-1,middle;while(start<=end){middle=(start+end)/2;if(a[middle]==middle){

int arr[] = new int[] { -10, -5, 0, 3, 7 }; System.out.println(fixedPoint(arr)); arr = new int[] { 0, 2, 5, 8, 17 }; System.out.println(fixedPoint(arr)); arr = new int[] { -10, -5, 3, 4, 7, 9 }; System.out.println(fixedPoint(arr)); } public static int fixedPoint(int[] arr) { int pos = -1; for (int i = 0; i < arr.length;) { if (i == arr[i]) return i; else if (i < arr[i]) i = arr[i]; else ++i; } return pos; }}

Page 8: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

8/19www.geeksforgeeks.org/archives/15946

if(middle==start || a[middle-1]!=middle-1){ return middle; }end=middle-1;}else if(a[middle]<middle){ start=middle+1; }else{ end=middle-1; }}return -1;}

ReplyKarthick says:December 27, 2011 at 6:25 PM

Sorry for posting without the sourcecode tags

Reply8. kaka09 says:

December 14, 2011 at 7:19 PM

int findFirstFixedPoint(int length){ if(length==0){ return -1; } int start=0,end=length-1,middle; while(start<=end) { middle=(start+end)/2; if(a[middle]==middle) { if(middle==start || a[middle-1]!=middle-1){ return end=middle-1; } else if(a[middle]<middle){ start=middle+1; } else{ end=middle-1; } } return -1;}

#include<stdio.h>int main{ int n,i,j,flag=-1,pos; scanf("%d",&n);() int a[n]; for(i=0;i<n;i++) scanf("%d",&a[i]); i=0;

Page 9: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

9/19www.geeksforgeeks.org/archives/15946

Reply9. kaka09 says:

December 14, 2011 at 7:19 PM

Reply10. punit says:

while(a[i++]<0) for(j=i;j<n;j++) { if(j==a[j]) { flag=0; pos=j; break; } } if(flag!=0) printf("number not found!!"); else printf("number found at index %d\n", pos);}

#include<stdio.h>int main(){ int n,i,j,flag=-1,pos; scanf("%d",&n); int a[n]; for(i=0;i<n;i++) scanf("%d",&a[i]); i=0; while(a[i++]<0) for(j=i;j<n;j++) { if(j==a[j]) { flag=0; pos=j; break; } } if(flag!=0) printf("number not found!!"); else printf("number found at index %d\n", pos);}

Page 10: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

10/19www.geeksforgeeks.org/archives/15946

December 3, 2011 at 1:09 PM

for handling equal values like [-1, 0, 4, 4, 4, 4, 4] just tweak binary search as follows-int bs(vector v, int l, int r){int m = (l+r)/2;if(l > r)return -1;if(v[m] == m)return m;if((v[m] > m) && (v[m] != v.at(m+1))){return bs(v, l, m-1);}elsereturn bs(v, m+1, r);}

ReplyAG says:December 29, 2011 at 2:56 PM

I think it fails for this test case:-

[0, 2, 5, 5, 5, 6, 7]

ReplyYogesh Batra says:April 8, 2012 at 4:22 PM

It's working, I don't think there is any problem with the above code.

Replyyogendra says:April 9, 2012 at 9:31 PM

@YogeshI checked the above code is failing in case of [0, 2, 5, 5, 6, 7]in first Itrl=0,r=5 => m=2;so a[2]>2 and here a[2]==a[3]==5so l=3;

/* Paste your code here (You may delete these lines if not writing code) */

Page 11: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

11/19www.geeksforgeeks.org/archives/15946

in second Itr l=3,r=5 =>m=4;s0 a[4]>6 hence it will return -1; int next iter.

Reply11. punit says:

December 3, 2011 at 1:00 PM

/* Paste your code here (You may delete these lines if not writing code) */[#includeusing namespace std;#includeint bs(vector v, int l, int r){int m = (l+r)/2;if(l > r)return -1;if(v[m] == m)return m;if(v[m] > m){return bs(v, l, m-1);}elsereturn bs(v, m+1, r);}void Fp(vector v, int l, int r){int index;static int flag = true, Index = 0;index = r;while(1){index = bs(v, l, index-1);

if(index == -1){if(flag == false){cout<<"not found.\n";return;}cout<<"found at index = "<<Index<<endl;break;}

Page 12: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

12/19www.geeksforgeeks.org/archives/15946

Index = index;flag = true;}}int main(){vector v;v.push_back(-1);v.push_back(0);v.push_back(2);v.push_back(5);Fp(v, 0, v.size());return 0;}]

Reply12. Daniel says:

December 1, 2011 at 3:18 PM

The non-distinct case would be interesting.

Replykartik says:December 1, 2011 at 8:49 PM

I don't think binary search can be applied in case of non-distict case. Forexample, {-1, 4, 4, 4, 4, 4, 4}. We go to middle index 3 and see value is greaterthen index. We can't have a logic to look for left side or right side as array couldbe {-1, 0, 2, 4, 6, 8, 10} or {-1, 4, 4, 4, 5, 5, 5}. Let me know your thoughts.

Reply13. krishna says:

December 1, 2011 at 12:11 PM

The problem would be more interesting if we ask for the first Fixed Point instead of aFixed Point.

Replykartik says:December 1, 2011 at 12:20 PM

@Krishna: Thanks for suggesting a more advanced version of the problem. Themethod 1 anyways finds the first FP. The method 2 can also be tweaked to findthe first FP.

Page 13: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

13/19www.geeksforgeeks.org/archives/15946

ReplyVenki says:December 1, 2011 at 4:22 PM

@krishna, Good question. Binary search is such a powerful technique, sometimes, we miss to note its power. Solution to your question is given below. Letme know if there are any corner cases.

ReplyJing says:December 2, 2011 at 11:11 AM

For A=[-1, 0, 2], it seems to return -1 instead of 2, doesn't it?

ReplyVenki says:December 1, 2011 at 4:23 PM

Driver code.

int binarySearch(int A[], int l, int r){ int mid; int traced = -1; while( (r - l) > 1 ) { mid = l + (r - l)/2; if( A[mid] == mid ) traced = mid; // C/C++ smart enough to confuse (mid <= A[mid] ? r : l) = mid; } if( A[l] == l )// Corner case : ) traced = l; return traced;}

/* Paste your code here (You may delete these lines if not writing code) */

int main(){

Page 14: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

14/19www.geeksforgeeks.org/archives/15946

ReplyVenki says:December 2, 2011 at 11:41 AM

@Jing, thanks for pointing the error. Given below is updated one.

int arr[] = {-10, 1, 2, 3, 10, 11, 30, 50, 100}; int n = sizeof(arr)/sizeof(arr[0]); printf("Fixed Point is %d", binarySearch(arr, 0, n-1)); return 0;}

#include <stdio.h> int binarySearchLeft(int A[], int l, int r){ int mid; int traced = -1; while( (r - l) > 1 ) { mid = l + (r - l)/2; if( A[mid] == mid ) traced = mid; (mid <= A[mid] ? r : l) = mid; } if( A[r] == r ) traced = r; if( A[l] == l ) traced = l; return traced;} int binarySearchRight(int A[], int l, int r){ int mid; int traced = -1; while( (r - l) > 1 ) { mid = l + (r - l)/2; if( A[mid] == mid ) traced = mid;

Page 15: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

15/19www.geeksforgeeks.org/archives/15946

Reply

Comment

Name (Required) Email (Required)

Website URI Your Comment (Writing code? please paste your

code between sourcecode tags)

[sourcecode language="C"]/* Paste your code here (You may delete these lines if not writing code) */[/sourcecode]

Have Your Say

Search

(mid >= A[mid] ? l : r) = mid; } if( A[l] == l ) traced = l; if( A[r] == r ) traced = r; return traced;} int main(){ int arr[] = { 0, 1, 2 }; int n = sizeof(arr)/sizeof(arr[0]); printf("Fixed Point is %d\n", binarySearchLeft(arr, 0, n-1)); printf("Fixed Point is %d\n", binarySearchRight(arr, 0, n-1)); return 0;}

Page 16: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

16/19www.geeksforgeeks.org/archives/15946

Popular Tags

GATEJavaDynamic ProgrammingBacktrackingPattern SearchingDivide & ConquerGraphOperating SystemsRecursion

Popular Posts

All permutations of a given stringMemory Layout of C ProgramsUnderstanding “extern” keyword in CMedian of two sorted arraysTree traversal without recursion and without stack!Structure Member Alignment, Padding and Data PackingIntersection point of two Linked ListsLowest Common Ancestor in a BST.Check if a binary tree is BST or notSorted Linked List to Balanced BST

Page 17: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

17/19www.geeksforgeeks.org/archives/15946

250 Subscribe

Forum Latest Discussion

LIS in nlogn timeLast Post By: kartik

Inside: Interview Questions

tree to fileLast Post By: Dheeraj

Inside: Interview Questions

Page 18: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

18/19www.geeksforgeeks.org/archives/15946

Count internal nodes in a binary treeLast Post By: kartik

Inside: Interview Questions

Ancestor of two given leaf nodesLast Post By: dead

Inside: Trees specific questions

combine elements of an array, so as to minimize weights.Last Post By: rohanag

Inside: Interview Questions

FB interview questionLast Post By: ranganath111

Inside: Interview Questions

Testing of factorial of a numberLast Post By: rukawa

Inside: Interview Questions

numeric puzzleLast Post By: asm

Inside: Algorithms

Forum Categories

Interview QuestionsC/C++ Programming QuestionsAlgorithmsTrees specific questionsLinked List specific questionsMultiple Choice QuestionsObject oriented queriesGPuzzles

Page 19: Find a Fixed Point in a Given Array _ GeeksforGeeks

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks

19/19www.geeksforgeeks.org/archives/15946

Operating SystemsMiscellaneousJava specific QuestionsPerl specific Questions

Recent Comments

Venki on Structure Member Alignment, Padding and Data Packingavi on Structure Member Alignment, Padding and Data Packingatul on A Program to check if strings are rotations of each other or notVenki on Structure Member Alignment, Padding and Data Packingrahul on Dynamic Programming | Set 13 (Cutting a Rod)Sandeep on Dynamic Programming | Set 3 (Longest Increasing Subsequence)Yueming on Dynamic Programming | Set 3 (Longest Increasing Subsequence)avi on Structure Member Alignment, Padding and Data Packing

@geeksforgeeks, Some rights reservedPowered by WordPress & MooTools, customized by geeksforgeeks team