Count Occurrences of Element in Sorted Array in DSA C - Time & Space Complexity
We want to know how fast we can count how many times a number appears in a sorted list.
The question is: how does the time needed change as the list gets bigger?
Analyze the time complexity of the following code snippet.
int binarySearch(int arr[], int n, int x, int findFirst) {
int low = 0, high = n - 1, result = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == x) {
result = mid;
if (findFirst) high = mid - 1;
else low = mid + 1;
} else if (arr[mid] < x) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return result;
}
int countOccurrences(int arr[], int n, int x) {
int first = binarySearch(arr, n, x, 1);
if (first == -1) return 0;
int last = binarySearch(arr, n, x, 0);
return last - first + 1;
}
This code finds the first and last place of a number in a sorted array using binary search, then counts how many times it appears.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The binary search loop that halves the search space each time.
- How many times: Each binary search runs in about log n steps, and we do it twice.
As the list size grows, the number of steps grows slowly because we split the list in half each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 2 x 4 = 8 steps |
| 100 | About 2 x 7 = 14 steps |
| 1000 | About 2 x 10 = 20 steps |
Pattern observation: Doubling the list size adds only one more step per binary search, so total steps grow very slowly.
Time Complexity: O(log n)
This means the time to count occurrences grows slowly as the list gets bigger, making it very efficient.
[X] Wrong: "Counting occurrences requires checking every element, so it must be O(n)."
[OK] Correct: Because the array is sorted, we can use binary search to jump directly to the first and last positions, avoiding checking every element.
Knowing how to use binary search to count occurrences shows you understand how to use sorting to speed up searching, a skill often valued in problem solving.
"What if the array was not sorted? How would the time complexity change?"
Practice
Solution
Step 1: Understand binary search efficiency
Binary search divides the search space in half each time, reducing time complexity to O(log n).Step 2: Compare with linear search
Linear search checks each element one by one, taking O(n) time, which is slower for large arrays.Final Answer:
It reduces the search time from linear to logarithmic -> Option CQuick Check:
Binary search = faster search [OK]
- Thinking binary search sorts the array
- Confusing memory usage with speed
- Assuming binary search works on unsorted arrays
Solution
Step 1: Check function return type and parameters
The function should return an int (count), take array, size, and target element as parameters.Step 2: Validate parameter types
Array parameter must be int arr[] or int *arr, size as int n, and target as int x.Final Answer:
int countOccurrences(int arr[], int n, int x); -> Option BQuick Check:
Correct function signature = int countOccurrences(int arr[], int n, int x); [OK]
- Using void return type instead of int
- Passing array as int instead of int[]
- Missing array size parameter
int arr[] = {1, 2, 2, 2, 3, 4, 5};
int n = 7;
int x = 2;
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == x) count++;
}
printf("%d", count);Solution
Step 1: Iterate through the array and count matches
Elements equal to 2 are at indices 1, 2, and 3, so count increments 3 times.Step 2: Print the count
The final count is 3, so printf outputs 3.Final Answer:
3 -> Option DQuick Check:
Count of 2 in array = 3 [OK]
- Counting only first occurrence
- Off-by-one errors in loop
- Printing count before loop ends
int countOccurrences(int arr[], int n, int x) {
int count = 0;
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == x) {
count++;
mid++;
} else if (arr[mid] < x) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return count;
}Solution
Step 1: Analyze loop variables and updates
Incrementing mid does not affect low or high, so loop may become infinite or incorrect.Step 2: Understand binary search update rules
To move search window, low or high must be updated, not mid.Final Answer:
Incrementing mid inside the loop does not change low or high -> Option AQuick Check:
mid++ does not move search window [OK]
- Changing mid instead of low/high
- Wrong loop condition causing infinite loop
- Incorrect return type
arr = {1, 2, 2, 2, 3, 3, 4, 5, 5, 5, 5}, write a function that uses binary search to count occurrences of x = 5. What is the count returned?Solution
Step 1: Use binary search to find first occurrence of 5
First 5 is at index 7.Step 2: Use binary search to find last occurrence of 5
Last 5 is at index 10.Step 3: Calculate count as last - first + 1
Count = 10 - 7 + 1 = 4.Final Answer:
4 -> Option AQuick Check:
Count of 5 in array = 4 [OK]
- Counting total elements instead of occurrences
- Off-by-one errors in count calculation
- Using linear search instead of binary search
Ready to prove it?
Pass the test and this pattern moves unknown
