What if you could count items in a huge sorted list in just a few quick steps instead of checking one by one?
Why Count Occurrences of Element in Sorted Array in DSA Go?
Imagine you have a long list of sorted numbers, like a phone book sorted by last name. You want to find out how many times a particular name appears. Doing this by checking each entry one by one would take a lot of time.
Manually scanning through the entire list to count occurrences is slow and tiring. It's easy to lose track or make mistakes, especially if the list is very long. This wastes time and can cause errors.
Using a smart method that takes advantage of the list being sorted, we can quickly find where the element starts and ends. This way, we count occurrences fast without checking every item.
count := 0 for i := 0; i < len(arr); i++ { if arr[i] == target { count++ } }
start := findFirst(arr, target)
end := findLast(arr, target)
count := end - start + 1This lets you count how many times an item appears in a sorted list quickly and accurately, even if the list is huge.
In a library system, quickly finding how many copies of a book are available by searching a sorted list of book IDs helps manage inventory efficiently.
Manual counting is slow and error-prone for large sorted lists.
Using the sorted order lets us find occurrences quickly with special search methods.
This approach saves time and reduces mistakes in counting.
Practice
Solution
Step 1: Understand binary search efficiency
Binary search divides the search space in half each time, making it faster than linear search.Step 2: Apply to counting occurrences
By finding the first and last positions of the element, we can count occurrences efficiently.Final Answer:
It reduces the search time to logarithmic complexity. -> Option CQuick Check:
Binary search = O(log n) time [OK]
- Thinking binary search sorts the array
- Using linear search for counting in sorted array
- Assuming binary search works on unsorted arrays
Solution
Step 1: Check function signature syntax
In Go, slices are declared as []int, and return type int is correct for count.Step 2: Validate return statement matches return type
Returning 0 as int matches the return type int.Final Answer:
func countOccurrences(arr []int, target int) int { return 0 } -> Option AQuick Check:
Correct Go function syntax [OK]
- Using array syntax int[] instead of []int
- Mismatching return type and return value
- Omitting return type in function signature
func countOccurrences(arr []int, target int) int {
left := 0
right := len(arr) - 1
first := -1
for left <= right {
mid := (left + right) / 2
if arr[mid] == target {
first = mid
right = mid - 1
} else if arr[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
if first == -1 {
return 0
}
left = 0
right = len(arr) - 1
last := -1
for left <= right {
mid := (left + right) / 2
if arr[mid] == target {
last = mid
left = mid + 1
} else if arr[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
return last - first + 1
}
func main() {
arr := []int{1, 2, 2, 2, 3, 4, 5}
count := countOccurrences(arr, 2)
fmt.Println(count)
}Solution
Step 1: Find first occurrence of 2
Binary search finds first index of 2 at position 1.Step 2: Find last occurrence of 2
Binary search finds last index of 2 at position 3.Step 3: Calculate count
Count = last - first + 1 = 3 - 1 + 1 = 3.Final Answer:
3 -> Option BQuick Check:
Occurrences of 2 = 3 [OK]
- Returning index instead of count
- Not updating left/right correctly in binary search
- Confusing first and last occurrence indices
func countOccurrences(arr []int, target int) int {
left, right := 0, len(arr)-1
count := 0
for left <= right {
mid := (left + right) / 2
if arr[mid] == target {
count++
break
} else if arr[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
return count
}Solution
Step 1: Analyze loop behavior
The loop breaks after finding one occurrence, so count increments only once.Step 2: Understand counting logic
Counting all occurrences requires searching for first and last positions, not just one match.Final Answer:
It counts only one occurrence, not all. -> Option AQuick Check:
Loop breaks early, count = 1 [OK]
- Using break instead of continuing search
- Not searching for first and last indices
- Assuming one match equals total count
Solution
Step 1: Consider efficiency for multiple targets
Binary search per target is O(k log n) for k targets, which can be costly.Step 2: Use hash map after one scan
A single linear scan builds a map of counts for all elements in O(n), allowing O(1) lookup per target.Step 3: Compare approaches
Hash map approach is more efficient for multiple queries than repeated binary searches.Final Answer:
Use a hash map to store counts after one full scan. -> Option DQuick Check:
Hash map = efficient multiple counts [OK]
- Repeating binary search for each target
- Sorting array multiple times unnecessarily
- Ignoring hash map for frequency counting
Ready to prove it?
Pass the test and this pattern moves unknown
