Created
February 4, 2019 07:09
-
-
Save Smakar20/8d517b11eba66651b2ee968b8e48a59a to your computer and use it in GitHub Desktop.
countOccurance.js created by smakar20 - https://repl.it/@smakar20/countOccurancejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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