4

I have a very big sorted array. How can I count or print all the unique elements of an array??

Suppose my array is [2,3,3,3,4,6,6,7] then output should be 2,3,4,6,7

I know to do it in a n(complexity) time. But interviewer asked me to do this in log n time?? Is it possible?

2
  • 4
    Since printing elements is O(n) complexity it shouldn't be unless you have only a predefined number of different elements (suppose you have integer numbers 1 to 10 in the array). Commented Jun 19, 2014 at 8:32
  • Interviewer is not asking to do task with (log n) number of operations. He is asking the complexity to be (log n) it means number of operations are proportional to (log n). e.g. for o(n) algo if for 100 elements it takes 100,000 operations then for 200 elements it will take 200,000 operations. where as for o(log n) algo if for 100 elements it takes 100,000 operations then for 200 elements it will take 100,150 etc. (Ignore actual numbers. They are just indicative) Commented Jun 21, 2014 at 11:13

2 Answers 2

7

Here is an algorithm which requires O(logn*k) where k is unique elements:-

set uniQ
int ind = 0;

do {

 uniQ.add(arr[i]);
 ind = BinSearchGreater(arr,arr[ind],ind+1);
 if(ind >= arr.length)
   break;

} while(true);


BinSearchGreater(arr,key,start_ind) : returns index of first element greater than key in subarray starting at start_ind 

Time complexity :- Note this algorithm is only good when no of unique elements are small. This is asymptotically O(n*logn) if all are unique so worse than linear.

Sign up to request clarification or add additional context in comments.

1 Comment

My interviewer was very pleased with this solution when I was asked the same question once.
0

I would like to know how he (the interviewer) counts every unique element in the array [1,2,3,4,5] without picking at least every element. In this case you have to pick every element to count every element and this will be done in O(n). In my opinion impossible to get a complexity of O(log n), if there are no other requirements to the given array.

9 Comments

the array is sorted so you don't really need to look at every element.
You have to at least read that whole array so lower bound is O(n)
@perreal you have to look at every element, for example, this case (2,5,7,100) how can you tell?
I think it can be done in M log N where M is size of the result. You can achieve this by running multiple binary searches.
@PhamTrung, that is a list of all uniq elements so even printing is O(n). What if you have log(n) unique elements?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.