Skip to content

Instantly share code, notes, and snippets.

@jasonwaters
Created June 13, 2019 23:25
Show Gist options
  • Save jasonwaters/1c0cf3b4273a491e9cdb052b3b5af5a6 to your computer and use it in GitHub Desktop.
Save jasonwaters/1c0cf3b4273a491e9cdb052b3b5af5a6 to your computer and use it in GitHub Desktop.
Count the number of repeat integers in a sorted array.
function first(arr, target, left, right, found=-1) {
const mid = Math.floor((left+right)/2);
found = arr[mid] === target ? mid : found;
if(right > left) {
if(arr[mid] >= target) {
return first(arr, target, left, mid-1, found);
}else if(arr[mid] < target) {
return first(arr, target, mid+1, right, found);
}
}
return found;
}
function last(arr, target, left, right, found=-1) {
const mid = Math.floor((left+right)/2);
found = arr[mid] === target ? mid : found;
if(right > left) {
if(arr[mid] > target) {
return last(arr, target, left, mid-1, found);
}else if(arr[mid] <= target) {
return last(arr, target, mid+1, right, found);
}
}
return found;
}
function countDupes(arr, target) {
const left = first(arr, target, 0, arr.length);
const right = last(arr, target, left, arr.length);
const count = left >= 0 ? right-(left-1) : 0;
return count;
}
const arr = [1,2,3,3,3,3,4,5,6,7,7,7,7,9,9];
// const arr = [1,2,2,2,3];
new Set(arr).forEach((value) => {
const dupes = countDupes(arr, value);
console.log(`value: ${value}, dupes: ${dupes}`)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment