Microsoft Microsoft Interview Question
Software Engineer in TestsTeam: Office
Country: United States
Interview Type: In-Person
There is a minor problem here: The question doesn't say whether it is incremental or not.
@sw, the only way there can be any duplicates without violating the sorted order property is two same numbers being consecutive which is checked by the <= operator. Otherwise duplicates would violate the sorted order property.
isnt this an infinite loop, or am i mistaken?
the continue makes the next iteration start and t is never incremented
Following condition could be placed before the loop too : if (a[0] <= 0)
instead of if(a[t] <= 0) inside the loop
if first element is greater than zero, all other elements in the set would be greater than zero as set is expected to be incremental, else it is caught in the condition :
if (a[t] <= a[t - 1])
I think the problem can be solved using a bit vector.
public static boolean isUnique(int[] a){
int prev = 0;
int res;
for(int i=0; i<a.length;i++) {
res = prev ^ (1<<a[i]);
if(res<prev) return false;
prev=res;
}
return true;
}
1. sort direction is not an issue, cause if descending, just traverse the array from tail.
2. only check <= is fine, it will cover the duplicate case.
here is the c# code
public static bool IsSet(int[] array) {
if(array == null || array.Length == 0) return false;
if(array[0] <= 0) return false; // if ascending, only need to check once
for(int i=0; i<array.Length-1; i++) {
if(array[i] >= array[i+1]) return false;
}
return true;
}
I think this problem can be solved by Balanced binary search tree.
Case 1:
when we scan the array simple check it is positive or not.
Case 2:
When you create the BST inorder traversal will automatically gives you element in sorted order.
Case 3:
For searching complexity will be log(n) which also for inserting the element.
- speedmancs January 27, 2013