Skip to content

Instantly share code, notes, and snippets.

@Smakar20
Created February 4, 2019 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Smakar20/8d517b11eba66651b2ee968b8e48a59a to your computer and use it in GitHub Desktop.
Save Smakar20/8d517b11eba66651b2ee968b8e48a59a to your computer and use it in GitHub Desktop.
countOccurance.js created by smakar20 - https://repl.it/@smakar20/countOccurancejs
/* Count occurrences of a given number in a sorted array which has duplicates
[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 8, 8, 12, 12, 12]
Given the number 2, we should return 5, since it appeared 5 times in the given array.
Complexity required - O(log(n))
*/
function findElement(arr, num){
var startIdx = countOccurances(arr, 0, arr.length, num, true);
var lstIdx = countOccurances(arr, 0, arr.length, num, false) - 1;
console.log(`${startIdx} and ${lstIdx}`);
return (lstIdx - startIdx) + 1;
}
function countOccurances(arr, start, end, num, left){
while (start < end){
var mid = parseInt((start + end)/2);
if (arr[mid] > num || (left && arr[mid] === num)){
end = mid;
}
else {
start = mid + 1;
}
}
return start;
}
findElement([1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 8, 8, 12, 12, 12], 2) // 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment