Microsoft Interview Question
Software Engineer in TestsTeam: SDET
Country: India
Interview Type: Phone Interview
The question would make more sense if it is sorted and requires better than O(n), for O(n) it's too simple
public static int findIndex(char[] A, char ch){
int low=0;
int high=A.lengh()-1;
while(low<=high)
{
int mid=(high-low)/2 -low;
if(A[mid]==ch){
return mid;}
else if (A[mid]<ch)
{
low=mid+1;
while(A[low]==' '){
low++;
}
}
else
{
high=mid-1;
while(A[high]==' '){
high--;
}
}
}
return -1;
}
Using Binary Search
int chSearch(string& str,char val, int start, int end, bool shift = true)
{
if(start == end)
return -1;
if(str[start]==val)
return start;
if(str[end]==val)
return end;
int mid = (start+end)/2;
if(shift)
{
while (str[mid]== ' ')
{
mid --;
}
}
else
{
while (str[mid]== ' ')
{
mid ++;
}
}
if(str[mid]==val)
return mid;
if(str[mid]<val)
chSearch(str,val,mid,end,false);
else
chSearch(str,val,start,mid);
}
int binarySearch(string &str,char val)
{
int length = str.length();
if(val < str[0] || val > str[length-1])
return -1;
return chSearch(str,val,0,length-1);
}
Linear search, complexity O(N). Is the array sorted, except the spaces? If, yes binary search, and at each step check if you found a space, in which case move one position to the left, or to the right.
- EugenDu May 29, 2013