What is the main advantage of using a sorted array to count occurrences of an element?
A sorted array allows us to use binary search to find the first and last positions of the element efficiently, reducing the time complexity from linear to logarithmic.
Click to reveal answer
beginner
Explain how binary search helps in counting occurrences of an element in a sorted array.
Binary search finds the first and last index of the element quickly. The count is the difference between these two indices plus one.
Click to reveal answer
intermediate
What is the time complexity of counting occurrences of an element in a sorted array using binary search?
O(log n), where n is the number of elements in the array, because binary search is used twice.
Click to reveal answer
beginner
If the element is not present in the sorted array, what should the count be?
The count should be 0 because the element does not appear in the array.
Click to reveal answer
intermediate
Describe the steps to find the first occurrence of an element using binary search.
1. Set start and end pointers. 2. Find mid index. 3. If mid element equals target, move end to mid - 1 to find earlier occurrence. 4. If mid element is less than target, move start to mid + 1. 5. Repeat until start > end. 6. The first occurrence is at start if element matches.
Click to reveal answer
What is the first step to count occurrences of an element in a sorted array?
ATraverse the entire array linearly
BFind the first and last positions of the element using binary search
CSort the array first
DUse a hash map to count elements
✗ Incorrect
Using binary search to find the first and last positions is efficient and leverages the sorted property.
If the first occurrence of an element is at index 3 and the last occurrence is at index 7, what is the count of that element?
A5
B7
C3
D4
✗ Incorrect
Count = last index - first index + 1 = 7 - 3 + 1 = 5.
What is the time complexity of counting occurrences using binary search in a sorted array of size n?
AO(n)
BO(n log n)
CO(1)
DO(log n)
✗ Incorrect
Binary search runs in O(log n), and we do it twice, so overall O(log n).
What should be returned if the element is not found in the sorted array?
A0
B-1
Cnull
D1
✗ Incorrect
Count of occurrences is zero if the element is not present.
Which of these is NOT a step in finding the first occurrence of an element using binary search?
AMove end pointer to mid - 1 if mid element equals target
BMove end pointer to mid - 1 if mid element is greater than target
CMove end pointer to mid + 1 if mid element equals target
DMove start pointer to mid + 1 if mid element is less than target
✗ Incorrect
If mid element equals target, we move end to mid - 1 to find earlier occurrence, not mid + 1.
Describe how to count the occurrences of an element in a sorted array using binary search.
Think about how binary search can find boundaries efficiently.
You got /4 concepts.
Explain why counting occurrences in a sorted array is faster with binary search than linear search.
Compare how many elements each method checks.
You got /4 concepts.
Practice
(1/5)
1. What is the main advantage of using a binary search to count occurrences of an element in a sorted array?
easy
A. It sorts the array automatically.
B. It reduces the search time from linear to logarithmic.
C. It counts all elements without searching.
D. It works only on unsorted arrays.
Solution
Step 1: Understand binary search efficiency
Binary search divides the search space in half each time, making it faster than checking every element.
Step 2: Compare linear vs binary search
Linear search checks each element one by one (O(n)), binary search works in O(log n) time.
Final Answer:
It reduces the search time from linear to logarithmic. -> Option B
Quick Check:
Binary search = faster search [OK]
Hint: Binary search halves search space each step [OK]
Common Mistakes:
Thinking binary search sorts the array
Assuming binary search works on unsorted arrays
Confusing counting with searching
2. Which of the following is the correct syntax to find the middle index in a binary search on array arr between indices low and high in JavaScript?
easy
A. const mid = low + high;
B. const mid = (low + high) / 2;
C. const mid = Math.ceil((low + high) / 2);
D. const mid = Math.floor((low + high) / 2);
Solution
Step 1: Calculate middle index correctly
We use Math.floor to get the integer index because array indices must be whole numbers.
Step 2: Avoid floating point and wrong calculations
Using just division or Math.ceil can cause errors or out-of-bound indices.
Hint: Use Math.floor to get integer middle index [OK]
Common Mistakes:
Not using Math.floor causing float index
Using Math.ceil which may skip elements
Adding indices without division
3. What will be the output of the following JavaScript code?
function countOccurrences(arr, x) {
let low = 0, high = arr.length - 1;
let count = 0;
while (low <= high) {
let mid = Math.floor((low + high) / 2);
if (arr[mid] === x) {
count++;
let left = mid - 1;
while (left >= 0 && arr[left] === x) {
count++;
left--;
}
let right = mid + 1;
while (right < arr.length && arr[right] === x) {
count++;
right++;
}
break;
} else if (arr[mid] < x) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return count;
}
console.log(countOccurrences([1,2,2,2,3,4,5], 2));
medium
A. 1
B. 2
C. 3
D. 0
Solution
Step 1: Find one occurrence of 2 using binary search
The binary search finds 2 at index 2 (middle of array).
Step 2: Count all adjacent 2s on left and right
Left side: indices 1 and 0 checked; only index 1 has 2. Right side: index 3 has 2. Total count = 3.
Final Answer:
3 -> Option C
Quick Check:
Count adjacent 2s = 3 [OK]
Hint: Count neighbors after binary search hit [OK]
Common Mistakes:
Counting only the found element once
Not checking neighbors on both sides
Incorrect loop conditions causing infinite loops
4. The following code is intended to count occurrences of x in a sorted array arr. What is the bug?
function countOccurrences(arr, x) {
let low = 0, high = arr.length - 1;
let count = 0;
while (low <= high) {
let mid = Math.floor((low + high) / 2);
if (arr[mid] === x) {
count++;
let left = mid - 1;
while (arr[left] === x) {
count++;
left--;
}
let right = mid + 1;
while (arr[right] === x) {
count++;
right++;
}
break;
} else if (arr[mid] < x) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return count;
}
medium
A. The while loops do not check array bounds before accessing elements.
B. The binary search condition is incorrect.
C. The count variable is not initialized.
D. The function does not return any value.
Solution
Step 1: Analyze while loops for boundary checks
The loops check arr[left] === x and arr[right] === x without verifying if left or right are valid indices.
Step 2: Identify risk of out-of-bounds access
If left becomes -1 or right exceeds array length, accessing arr[left] or arr[right] causes errors.
Final Answer:
The while loops do not check array bounds before accessing elements. -> Option A
Quick Check:
Always check array bounds before access [OK]
Hint: Check array bounds before accessing elements [OK]
Common Mistakes:
Ignoring array index limits in loops
Assuming array access is always safe
Not breaking loop on invalid index
5. Given a sorted array arr = [1,2,2,2,3,3,4,5,5,5,5,6], which approach is the most efficient to count occurrences of 5 without scanning the entire array?
hard
A. Use binary search to find first and last positions of 5, then calculate count.
B. Use a for loop to count all 5s by scanning the whole array.
C. Sort the array again and count 5s.
D. Use a hash map to store counts of all elements.
Solution
Step 1: Understand the problem constraints
The array is sorted, so all 5s are grouped together.
Step 2: Use binary search to find boundaries
Find the first index of 5 and last index of 5 using binary search, then count = last - first + 1.
Step 3: Compare efficiency
This method is O(log n), faster than scanning entire array (O(n)) or sorting again (O(n log n)).
Final Answer:
Use binary search to find first and last positions of 5, then calculate count. -> Option A
Quick Check:
Binary search boundaries = efficient count [OK]
Hint: Find first and last index with binary search [OK]
Common Mistakes:
Scanning entire array unnecessarily
Sorting already sorted array again
Using extra space with hash map when not needed
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.