5/12/12

Find a Fixed Point in a given array | GeeksforGeeks

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:
Ipt ar]={1,-,0 3 7 nu: r[ -0 5 , , } Otu:3 / ar3 = 3 upt / r[] = Ipt ar]={,2 5 8 1} nu: r[ 0 , , , 7 Otu:0 / ar0 = 0 upt / r[] =
www.geeksforgeeks.org/archives/15946 1/19

n) rnf"ie on s d.10.3 4 7 9 nu: r[ -0 5 . eun 1 } / Die pormt cekaoefntos* * rvr rga o hc bv ucin / itmi( n an) { itar1]={1. itbnrSac(n ar] itlw ithg) n iayerhit r[.org/archives/15946 2/19 .3. +) { i(r[]= i fari = ) rtr i eun .0 3 1. itlnaSac(n ar] itn n iererhit r[. Else the Fixed Point(s) lies on left side. If index is greater. n iefar/iefar0) pit(FxdPiti %" lnaSac(r. If it is. Thanks to pm for suggesting this solution. } Time Complexity: O(n) Method 2 (Binary Search) First check whether middle element is Fixed Point or not. 0 1 0 0 0} itn=szo(r)szo(r[]. . n ) { iti n .5. Return the first such index found. n r[0 -0 1 ./ n i lw ih/. n ih { i(ih> lw fhg = o) { itmd=(o +hg)2 /lw+(ih-lw/.geeksforgeeks. n o. ./ N FxdPit upt 1 / o ie on Asked by rajk Method 1 (Linear Search) Linearly search for an index i such that arr[i] == i.-. .-. *o hg o)2* www. iererhar ). otherwise check whether index of middle element is greater than value at the index. } / I n fxdpitpeette rtr . } Otu:. gthr) eca(.5/12/12 Find a Fixed Point in a given array | GeeksforGeeks Ipt ar]={1.* * f o ie on rsn hn eun 1 / rtr -. . rtr 0 eun . fri=0 i<n i+ o( . then Fixed Point(s) lies on the right side of the middle point (obviously only if there is a Fixed Point).1. then return it.

n r[0 -0 1 .lw (i -). eun iayerhar o.geeksforgeeks. i(i >armd) fmd r[i] rtr bnrSac(r.0 3 1. 4. -). n iefar/iefar0) pit(FxdPiti %" bnrSac(r. es le rtr bnrSac(r.(i +1. 2. } Algorithmic Paradigm: Divide & Conquer Time Complexity: O(Logn) Please write comments if you find anything incorrect.hg) eun iayerhar md ) ih. md 1) } / Rtr . 5. 0 1 0 0 0} itn=szo(r)szo(r[].com/readynow 25 comments so far 1.5.1. 3. Search an element in a sorted and pivoted array Find whether an array is subset of another array | Added Method 3 Count the number of occurrences in a sorted array Check for Majority Element in a sorted array Floor and Ceiling in a sorted array Microsoft® Private Cloud Microsoft® Private Cloud: Built for the Future.org/archives/15946 3/19 . gthr) eca(. Send 5 people You may also like following posts 1. Anon says: www.3. or you want to share more information about the topic discussed above. rtr 0 eun .10. eun 1 / Die pormt cekaoefntos* * rvr rga o hc bv ucin / itmi( n an) { itar1]={1.i teei n FxdPit* * eun 1 f hr s o ie on / rtr -. iayerhar . Ready Now.0 n1) rnf"ie on s d.5/12/12 Find a Fixed Point in a given array | GeeksforGeeks } i(i = armd) fmd = r[i] rtr md eun i.-. . Learn More! Microsoft.

PsychoCoder says: March 10. } itln=szo(r)szo(n) n e iefar/iefit. 2012 at 8:17 PM #nld<ti. 2012 at 6:40 PM The binary search method will not work in case of duplicate elements in the array. +) { i(r[]= i fari = ) { fa =1 lg . u) gth) ec(. md 1) So.lw (i -). because we can't eliminate one part of the array in each iteration. n r[ -0 5 . . Avi says: April 12.geeksforgeeks. } } pit(% \" nm. if my input is www.org/archives/15946 4/19 . n u 1 friti=0 iln i+ o(n . es le rtr bnrSac(r.5/12/12 Find a Fixed Point in a given array | GeeksforGeeks April 21. . nm=ari. eun iayerhar o.> icuesdoh #nld<oi. u r[] bek ra. rnf"d n. <e. sai itfa. ttc n lg itnm=-.3 4 7 9. } Reply 3.-. Reply 2.hg) eun iayerhar md ) ih. 2012 at 1:14 PM In the function this portion is fixed irrespective of the given data.> icuecnoh itmi( n an) { itar]={1. i(i >armd) fmd r[i] rtr bnrSac(r.(i +1.

4.5.5/12/12 Find a Fixed Point in a given array | GeeksforGeeks itar1]={1.0 6 1. int a3[] = {-10. 11. . int a4[] = {-10. 50.10 9. 7.geeksforgeeks.org/archives/15946 5/19 . } } return -1. cout << getFixedPoint(a1. 6) << endl. 30. int getFixedPoint(int a[]. 5) << endl. if (a[mid] == mid) { return mid. n r[0 -0 1 . } else if (a[mid] < mid) { start = mid + 1.1.1. 0 1 0 0 0. while (start <= end) { mid = (start + end) >> 1. -5. -5. 100}. 3. Reply Yogesh Batra says: April 8. 2. 10. 5. cout << getFixedPoint(a3. } else { end = mid .3. 0. 17}. 9}.1. 9) << endl. 3.h> using namespace std. mid = 0. Reply 4. 5) << endl. 3. } then 5(mid) < 11 (arr[mid]) so it will neglect right hand side the value '9' which is placed at arr[9]. 2012 at 4:12 PM This is clearly given that sequence is in increasing order. www. int n) { int start = 0. kartikaditya says: February 20. 2012 at 11:22 AM #include <iostream> #include <stdio. 2. end = n . 7}. } int main() { int a1[] = {-10. int a2[] = {0. 1. cout << getFixedPoint(a4. find some other counter example for binary look up method.-. cout << getFixedPoint(a2. 8.

Replace the if condition of while loop by : i([]=) fam>m Reply 6. wiel=) hl(<h { m(+)2 =lh/. 2012 at 3:25 PM An optimized algorithm for the case when elements can be repeated in the array : itfxdp(n *. } Reply 5. es le lm1 =+. 2012 at 6:55 AM pbi casFxdonIAry{ ulc ls iePitnra pbi sai vi mi(tig]ag { ulc ttc od anSrn[ r) www.=-.geeksforgeeks. eun 1 } The algo will return 1st element that is a fixed pt. Nages says: February 10.. i([]=) fam>0 hm1 =-. }/fnigte1teeeti wl b al)>0 / idn h s lmn(t il e [] = friliniai) o(=. } rtr -.n n n ie_tit ait ) { itl0hn1mi n =.<..5/12/12 Find a Fixed Point in a given array | GeeksforGeeks return 0. vijay_kansal says: February 15. Reply vijay_kansal says: February 19.org/archives/15946 6/19 . 2012 at 10:35 AM An error correction.=[] { i([]=) fai=i rtr i eun .

{ o it . 7 .egh) i ( = ari) f i = r[] rtr i eun . } } rtr ps eun o.org/archives/15946 7/19 . Sse. 5 . 5 . It would be good if someone can check this code for correctness. . .3 4 7 9} r e n[ 1.geeksforgeeks. Sse.u. } Reply 7. r[] es le +i +. .middle.end=length-1.rnl(iePitar) ytmotpitnfxdon(r).5/12/12 Find a Fixed Point in a given array | GeeksforGeeks itar]=nwit]{-0 -. pbi sai itfxdon(n[ ar { ulc ttc n iePitit] r) itps=-. . while(start<=end) { middle=(start+end)/2. .int length) { if(length==0){ return -1. the following code can find the first Fixed Point.rnl(iePitar) ytmotpitnfxdon(r). . r. Karthick says: December 27.0 3 7} n r[ e n[ 1.u.u. . 2011 at 6:19 PM I think. } Sse.rnl(iePitar) ytmotpitnfxdon(r). . ar=nwit]{0 2 5 8 1 } r e n[ . if(a[middle]==middle) { www. es i ( <ari) le f i r[] i=ari. } int start=0. int findFirstFixedPoint(int a[]. ar=nwit]{-0 -. n o 1 fr(n i=0 i<arlnt.

} Reply Karthick says: December 27. wiesat=n) hl(tr<ed { mdl=sated/.lg-. } else if(a[middle]<middle){ start=middle+1.} flnt=0{ eun 1 itsat0edlnt-. kaka09 says: December 14. i0 =. } } return -1. 2011 at 6:25 PM Sorry for posting without the sourcecode tags itfnFrtiePititlnt) n idisFxdon(n egh { i(egh=) rtr -.ai) cn(%"&[].+) saf"d.5/12/12 Find a Fixed Point in a given array | GeeksforGeeks if(middle==start || a[middle-1]!=middle-1){ return middle. } else{ end=middle-1.o. www.ide n tr=.<.n.org/archives/15946 8/19 . n [] fri0ini+ o(=.} le famdl]mdl) tr=ide1 es{edmdl-.n=egh1mdl. } end=middle-1.> icuesdoh itmi n an { itnijfa=1ps n . saf"d.) cn(%"&)( itan. ide(tr+n)2 i([ide=mdl) famdl]=ide { i(ide=tr | amdl-]=ide1{rtr fmdl=sat | [ide1!mdl-) eun edmdl-. 2011 at 7:19 PM #nld<ti.geeksforgeeks.. eun 1 } Reply 8. n=ide1 } es i([ide<ide{satmdl+..} le n=ide1 } rtr -.

} } i(lg=) ffa!0 pit(nme ntfud!) rnf"ubr o on!".n.<.> icuesdoh itmi( n an) { itnijfa=1ps n . rnf"ubr on t ne dn.ai) cn(%"&[].org/archives/15946 9/19 .. lg0 psj o=. 2011 at 7:19 PM #nld<ti. punit says: www. saf"d. n [] fri0ini+ o(=.5/12/12 Find a Fixed Point in a given array | GeeksforGeeks } wieai+<) hl([+]0 frjijnj+ o(=.+) saf"d. wieai+<) hl([+]0 frjijnj+ o(=. lg0 psj o=. cn(%"&) itan. bek ra. o) Reply 9.lg-. i0 =.+) { i(=aj) fj=[] { fa=.o.+) { i(=aj) fj=[] { fa=..geeksforgeeks.<. es le pit(nme fuda idx%\" ps. } } i(lg=) ffa!0 pit(nme ntfud!) rnf"ubr o on!". rnf"ubr on t ne dn. es le pit(nme fuda idx%\" ps.<. bek ra. kaka09 says: December 14. o) } Reply 10.

4] just tweak binary search as followsint bs(vector v. m-1). 5.at(m+1))) { return bs(v. so a[2]>2 and here a[2]==a[3]==5 so l=3. 2. 5. Reply yogendra says: April 9. l. 5. 5. if(v[m] == m) return m. 2011 at 1:09 PM for handling equal values like [-1. www. 7] in first Itr l=0. I don't think there is any problem with the above code. 2012 at 9:31 PM @Yogesh I checked the above code is failing in case of [0. 0. 6. 4. 2012 at 4:22 PM It's working. if(l > r) return -1. if((v[m] > m) && (v[m] != v. 7] / Pseyu cd hr (o mydlt teelnsi ntwii * at or oe ee Yu a eee hs ie f o rt Reply Yogesh Batra says: April 8. int r) { int m = (l+r)/2. 2011 at 2:56 PM I think it fails for this test case:[0.org/archives/15946 10/19 . 4. } Reply AG says: December 29.5/12/12 Find a Fixed Point in a given array | GeeksforGeeks December 3. } else return bs(v. 4. m+1. r).geeksforgeeks. 6. 2. 5. int l.r=5 => m=2. 4.

} cout<<"found at index = "<<Index<<endl.5/12/12 Find a Fixed Point in a given array | GeeksforGeeks in second Itr l=3. if(v[m] == m) return m. static int flag = true.r=5 =>m=4. m+1. 2011 at 1:00 PM /* Paste your code here (You may delete these lines if not writing code) */ [#include using namespace std. } else return bs(v.geeksforgeeks. m-1). if(l > r) return -1. } void Fp(vector v. int r) { int index. Index = 0. index = r. punit says: December 3. l. return. int l. l. } www. r). int next iter.org/archives/15946 11/19 . if(index == -1) { if(flag == false) { cout<<"not found. if(v[m] > m) { return bs(v. Reply 11. int r) { int m = (l+r)/2.\n". break. index-1). while(1) { index = bs(v. s0 a[4]>6 hence it will return -1. #include int bs(vector v. int l.

}] Reply 12. www. v. 4. v. 0. 2011 at 8:49 PM I don't think binary search can be applied in case of non-distict case. 2011 at 12:11 PM The problem would be more interesting if we ask for the first Fixed Point instead of a Fixed Point.push_back(5). 8. 2011 at 3:18 PM The non-distinct case would be interesting. return 0. 4. 4. 4. 5. 4. 5}. Daniel says: December 1. We go to middle index 3 and see value is greater then index.5/12/12 Find a Fixed Point in a given array | GeeksforGeeks Index = index. The method 2 can also be tweaked to find the first FP.geeksforgeeks. Fp(v. 5. v. 4.push_back(2). v. 10} or {-1. } } int main() { vector v. 4. {-1. 0. 4.push_back(-1). 4}. We can't have a logic to look for left side or right side as array could be {-1.push_back(0). Let me know your thoughts. Reply kartik says: December 1. 2. The method 1 anyways finds the first FP.size()). v. krishna says: December 1. Reply kartik says: December 1. 6.org/archives/15946 12/19 . 2011 at 12:20 PM @Krishna: Thanks for suggesting a more advanced version of the problem. 4. Reply 13. For example. flag = true.

n . Let me know if there are any corner cases. } i(Al = l)/Cre cs :) f [] = / onr ae tae =l rcd . eun rcd Reply Jing says: December 2. 2011 at 4:22 PM @krishna. 2011 at 4:23 PM Driver code. Binary search is such a powerful technique.org/archives/15946 13/19 . ittae =-. 0.geeksforgeeks. n rcd 1 wie ( -l >1) hl( r ) { md=l+( -l/. some times. 2011 at 11:11 AM For A=[-1. Solution to your question is given below. itbnrSac(n A] itl itr n iayerhit [. / CC+sateog t cnue / /+ mr nuh o ofs (i < Amd ?r:l =md md = [i] ) i. it seems to return -1 instead of 2.5/12/12 Find a Fixed Point in a given array | GeeksforGeeks Reply Venki says: December 1. doesn't it? / Pseyu cd hr (o mydlt teelnsi nt * at or oe ee Yu a eee hs ie f o Reply Venki says: December 1. 2]. n ) { itmd n i. we miss to note its power. } rtr tae. itmi( n an) { www. i r )2 i(Amd = md) f [i] = i tae =md rcd i. Good question.

geeksforgeeks. n rcd 1 wie ( -l >1) hl( r ) { md=l+( -l/. i(Ar = r)tae =r f [] = rcd . . ittae =-.3.org/archives/15946 14/19 . n rcd 1 wie ( -l >1) hl( r ) { md=l+( -l/. thanks for pointing the error. iayerhar . i r )2 i(Amd = md)tae =md f [i] = i rcd i. n ) { itmd n i. www. 2011 at 11:41 AM @Jing.5. } (i < Amd ?r:l =md md = [i] ) i. n ) { itmd n i. i(Al = l)tae =l f [] = rcd . eun rcd itbnrSacRgtitA] itl itr n iayerhih(n [.10. Reply Venki says: December 2. #nld <ti. i r )2 i(Amd = md)tae =md f [i] = i rcd i. 0 1 0 0 0} itn=szo(r)szo(r[]. } rtr tae. -).0 n1) rnf"ie on s d. n . n iefar/iefar0) pit(FxdPiti %" bnrSac(r. .> icue sdoh itbnrSacLf(n A] itl itr n iayerhetit [. n r[ -0 . ittae =-. } rtr 0 eun .5/12/12 Find a Fixed Point in a given array | GeeksforGeeks itar]={1. n . Given below is updated one.1 2 3 1.1.

itn=szo(r)szo(r[]. iayerhih(r. n iefar/iefar0) pit(FxdPiti %\" bnrSacLf(r. i(Ar = r)tae =r f [] = rcd . -) pit(FxdPiti %\" bnrSacRgtar 0 n1 rnf"ie on s dn. -) } rtr 0 eun . Reply Comment Name (Required) Website URI code between sourcecode tags) Email (Required) Your Comment (Writing code? please paste your [oreoelnug=C] succd agae"" / Pseyu cd hr (o mydlt teelns * at or oe ee Yu a eee hs ie i ntwiigcd)* f o rtn oe / [succd] /oreoe Have Your Say Search www. . .org/archives/15946 15/19 . eun rcd itmi( n an) { itar]={0 1 2} n r[ . iayerhetar . } rtr tae.geeksforgeeks. i(Al = l)tae =l f [] = rcd .0 n1) rnf"ie on s dn.5/12/12 Find a Fixed Point in a given array | GeeksforGeeks } (i > Amd ?l:r =md md = [i] ) i. .

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks Popular Tags GATE Java Dynamic Programming Backtracking Pattern Searching Divide & Conquer Graph Operating Systems Recursion Popular Posts All permutations of a given string Memory Layout of C Programs Understanding “extern” keyword in C Median of two sorted arrays Tree traversal without recursion and without stack! Structure Member Alignment. Check if a binary tree is BST or not Sorted Linked List to Balanced BST www.org/archives/15946 16/19 . Padding and Data Packing Intersection point of two Linked Lists Lowest Common Ancestor in a BST.geeksforgeeks.

5/12/12 Find a Fixed Point in a given array | GeeksforGeeks 250 Subscribe Forum Latest Discussion LIS in nlogn time Last Post By: kartik Inside: Interview Questions tree to file Last Post By: Dheeraj Inside: Interview Questions www.geeksforgeeks.org/archives/15946 17/19 .

org/archives/15946 18/19 .5/12/12 Find a Fixed Point in a given array | GeeksforGeeks Count internal nodes in a binary tree Last Post By: kartik Inside: Interview Questions Ancestor of two given leaf nodes Last 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 question Last Post By: ranganath111 Inside: Interview Questions Testing of factorial of a number Last Post By: rukawa Inside: Interview Questions numeric puzzle Last Post By: asm Inside: Algorithms Forum Categories Interview Questions C/C++ Programming Questions Algorithms Trees specific questions Linked List specific questions Multiple Choice Questions Object oriented queries GPuzzles www.geeksforgeeks.

org/archives/15946 19/19 . Padding and Data Packing avi on Structure Member Alignment. Some rights reserved Powered by WordPress & MooTools.geeksforgeeks. customized by geeksforgeeks team www. Padding and Data Packing @geeksforgeeks.5/12/12 Find a Fixed Point in a given array | GeeksforGeeks Operating Systems Miscellaneous Java specific Questions Perl specific Questions Recent Comments Venki on Structure Member Alignment. Padding and Data Packing rahul 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 atul on A Program to check if strings are rotations of each other or not Venki on Structure Member Alignment.