Skip to content

Instantly share code, notes, and snippets.

@jack-wong-build
Created February 13, 2014 11:04
Show Gist options
  • Save jack-wong-build/8973264 to your computer and use it in GitHub Desktop.
Save jack-wong-build/8973264 to your computer and use it in GitHub Desktop.
Given a sorted array arr[] and a number x, write a function that counts the occurrences of x in arr[]. Expected time complexity is O(Logn).
//1,2,3,4,4,4,4,4,5,6,7
function findFrequency(array, target){
var first, last;
var result = -1;
first = findFirst(array, target, 0, array.length-1);
if (first !== -1){
last = findLast(array, target, 0, array.length-1);
result = last - first + 1;
}
return result;
}
function findFirst(array, target, startIndex, lastIndex){
// base case
if (startIndex ===lastIndex){
if (target === array[startIndex]){
return startIndex;
} else{
return -1;
}
}
var mediumIndex = startIndex + Math.floor( (lastIndex - startIndex ) / 2 );
if (target <= array[mediumIndex]){
return findFirst(array, target, startIndex, mediumIndex);
} else {
return findFirst(array, target, mediumIndex + 1, lastIndex);
}
}
function findLast(array, target, startIndex, lastIndex){
// base case
if (startIndex ===lastIndex){
if (target === array[startIndex]){
return startIndex;
} else{
return -1;
}
}
var mediumIndex = startIndex + Math.floor( (lastIndex - startIndex ) / 2 );
if (target >= array[mediumIndex + 1]){
return findLast(array, target, mediumIndex + 1, lastIndex);
} else {
return findLast(array, target, startIndex, mediumIndex);
}
}
console.log( findFrequency([1,2,3,4,4,4,4,5,5,6,7], 5) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment