0
0
DSA Javascriptprogramming~10 mins

Count Occurrences of Element in Sorted Array in DSA Javascript - Execution Trace

Choose your learning style9 modes available
Concept Flow - Count Occurrences of Element in Sorted Array
Start
Input: sorted array, target element
Find first occurrence index using binary search
Find last occurrence index using binary search
Calculate count = last - first + 1
Return count
End
We use two binary searches to find the first and last positions of the target element, then calculate how many times it appears.
Execution Sample
DSA Javascript
function countOccurrences(arr, target) {
  const first = findFirst(arr, target);
  if (first === -1) return 0;
  const last = findLast(arr, target);
  return last - first + 1;
}
This code finds the first and last positions of the target in the sorted array and returns the count of occurrences.
Execution Table
StepOperationArray StatePointer ChangesVisual State
1Start countOccurrences(arr, 2)[1,2,2,2,3,4,5]first = undefined, last = undefinedArray unchanged
2Call findFirst(arr, 2)[1,2,2,2,3,4,5]low=0, high=6, mid=3Check arr[3]=2 matches target
3findFirst: arr[3]=2 matches targetSamehigh=2 (move left)Searching left half
4findFirst: low=0, high=2, mid=1Samearr[1]=2 matches targethigh=0 (move left)
5findFirst: low=0, high=0, mid=0Samearr[0]=1 < targetlow=1 (move right)
6findFirst: low=1, high=0 (low>high)SameReturn first=1First occurrence at index 1
7Call findLast(arr, 2)[1,2,2,2,3,4,5]low=0, high=6, mid=3Check arr[3]=2 matches target
8findLast: arr[3]=2 matches targetSamelow=4 (move right)Searching right half
9findLast: low=4, high=6, mid=5Samearr[5]=4 > targethigh=4 (move left)
10findLast: low=4, high=4, mid=4Samearr[4]=3 > targethigh=3 (move left)
11findLast: low=4, high=3 (low>high)SameReturn last=3Last occurrence at index 3
12Calculate count = last - first + 1Samecount = 3 - 1 + 1 = 3Count of 2 is 3
13Return count=3SameFunction endsFinal result: 3 occurrences
💡 Binary searches end when low > high; count calculated from first and last indices.
Variable Tracker
VariableStartAfter Step 2After Step 6After Step 7After Step 11After Step 12Final
firstundefinedundefined11111
lastundefinedundefinedundefinedundefined333
lowundefined010444
highundefined606333
midundefined303444
countundefinedundefinedundefinedundefinedundefined33
Key Moments - 3 Insights
Why do we need two binary searches instead of one?
One binary search finds the first occurrence (step 6), the other finds the last occurrence (step 11). This ensures we count all occurrences between these indices.
What happens if the target is not found?
If findFirst returns -1 (not found), countOccurrences returns 0 immediately (step 2), skipping findLast.
Why does findFirst move 'high' when arr[mid] equals target?
To find the first occurrence, we continue searching left (lower indices) by moving 'high' left (step 3 and 4) even if we find the target.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'first' after step 6?
A1
B0
C-1
D3
💡 Hint
Check the 'Pointer Changes' column at step 6 where findFirst returns the first occurrence index.
At which step does the condition low > high become true for findLast?
AStep 9
BStep 10
CStep 11
DStep 12
💡 Hint
Look at the 'Pointer Changes' column for findLast where low=4 and high=3 indicating low > high.
If the target was not in the array, what would be the output of countOccurrences?
ALength of the array
B0
C-1
D1
💡 Hint
Refer to step 2 where if findFirst returns -1, countOccurrences returns 0 immediately.
Concept Snapshot
Count Occurrences in Sorted Array:
- Use binary search twice: findFirst and findLast occurrence
- findFirst moves left when target found
- findLast moves right when target found
- Count = last - first + 1
- If not found, count = 0
Full Transcript
To count how many times an element appears in a sorted array, we use two binary searches. First, find the first position where the element appears. Then, find the last position. The count is the difference plus one. If the element is not found, return zero. This method is efficient because it uses binary search, which runs fast on sorted arrays.