link mingle home | logged in as: guest | login/register| submit link


IndiaDiscuss.com : Social Bookmarkings and News Networking Site for India
interview_questions
Bookmarks
n/2 of n are same
-11
Votes

An array of size n, has n/2 unique elements and n/2 occurences of an element. Find the non-unique element in linear time?

saved under Amazon Interview Questions by interview_questions

 
    
    public int getDuplicatedElement(int [] input){
     int ret = 0;
     if(input.length <= 2) return input[0];// safe way
     if(input[0]==input[1])return input[0];
     for (int i = 1; i <input.length-1 ; i++)  {
        if(input[i]==input[i+1])return input[i];
        if(input[i-1]==input[i+1])return input[i-1];
     }
     return -1;
    }

comment by freebooksandarticles on 2008-06-12 21:52:58
Corrected for n=4 and case {1,2,3,1}
    public int getDuplicatedElement(int [] input){
     int ret = 0;
     if(input.length <= 2) return input[0];// safe way
     if(input.length==4 && input[0]==input[3])return input[0];
     if(input[0]==input[1])return input[0];
     for (int i = 1; i <input.length-1 ; i++)  {
        if(input[i]==input[i+1])return input[i];
        if(input[i-1]==input[i+1])return input[i-1];
     }
     return -1;
    }

comment by freebooksandarticles on 2008-06-13 02:16:19
 



Enter the string above
 
IndiaDiscuss | Published News | Hot
Indian Social News and Links Network
IndiaDiscuss | Published News
Indian Social News and Links Network