Bird
Raised Fist0
Interview Prepmodified-binary-searcheasyAmazonGoogle

Count Occurrences in Sorted Array

Choose your preparation mode4 modes available
</>
IDE
def count_occurrences(nums: list[int], target: int) -> int:public int countOccurrences(int[] nums, int target)int countOccurrences(const vector<int>& nums, int target)function countOccurrences(nums, target)
def count_occurrences(nums, target):
    # Write your solution here
    pass
class Solution {
    public int countOccurrences(int[] nums, int target) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int countOccurrences(const vector<int>& nums, int target) {
    // Write your solution here
    return 0;
}
function countOccurrences(nums, target) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: 0Binary search only finds one occurrence or fails to find target when present.✅ Implement two binary searches to find leftmost and rightmost indices of target.
Wrong: n (array length)Returning array length without checking if all elements equal target.✅ Verify target presence by binary search before returning count.
Wrong: Incorrect count off by oneOff-by-one error in count calculation (missing +1).✅ Count = right boundary - left boundary + 1.
Wrong: Non-zero count for target not in arrayNot checking if target is actually present between boundaries.✅ Check if nums[left] == target before returning count; else return 0.
Wrong: Timeout (TLE)Using linear scan instead of binary search on large inputs.✅ Use binary search to find leftmost and rightmost indices for O(log n) complexity.
✓
Test Cases
t1_01basic
Input{"nums":[1,2,2,2,3,4,5],"target":2}
Expected3

The number 2 appears at indices 1, 2, and 3, so the count is 3.

t1_02basic
Input{"nums":[1,1,2,2,2,2,3,3,4],"target":3}
Expected2

The number 3 appears twice at indices 6 and 7.

t2_01edge
Input{"nums":[],"target":5}
Expected0

Empty array contains no elements, so count is 0.

t2_02edge
Input{"nums":[10],"target":10}
Expected1

Single element array where target equals the element, count is 1.

t2_03edge
Input{"nums":[2,2,2,2,2],"target":2}
Expected5

All elements are the target, so count equals array length 5.

t2_04edge
Input{"nums":[1,2,3,4,5],"target":3}
Expected1

Target appears exactly once in the middle of the array.

t3_01corner
Input{"nums":[1,2,3,4,5],"target":6}
Expected0

Target 6 is larger than all elements, so count is 0.

t3_02corner
Input{"nums":[1,2,3,4,5],"target":0}
Expected0

Target 0 is smaller than all elements, so count is 0.

t3_03corner
Input{"nums":[1,2,2,2,3,4,5],"target":2}
Expected3

Test to catch off-by-one errors in boundary calculations for target 2.

t4_01performance
Input{"nums":[0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9],"target":5}
⏱ Performance - must finish in 2000ms

Large input with n=100, O(log n) binary search must complete within 2 seconds.

Practice

(1/5)
1. You are given a sorted array and need to efficiently find the index of a target value or determine it is not present. Which algorithmic approach guarantees the fastest search in O(log n) time by repeatedly dividing the search interval in half?
easy
A. Linear search by scanning each element until the target is found
B. Greedy algorithm selecting the closest element at each step
C. Binary search by repeatedly halving the search range based on comparisons
D. Dynamic programming to build a table of subproblems for target lookup

Solution

  1. Step 1: Understand problem constraints

    The array is sorted, enabling divide-and-conquer strategies.
  2. Step 2: Identify algorithm matching O(log n) search

    Binary search halves the search space each step, guaranteeing O(log n) time, unlike linear or greedy approaches.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Binary search is the classic O(log n) search on sorted arrays [OK]
Hint: Sorted array + fast search -> binary search [OK]
Common Mistakes:
  • Confusing greedy or DP with binary search
  • Assuming linear scan is optimal
  • Thinking DP applies to simple search
2. You are given a sorted array and a target value. You need to find the starting and ending indices of the target value in the array. Which algorithmic approach guarantees an optimal solution with logarithmic time complexity?
easy
A. Linear scan from start to end to find first and last occurrences
B. Greedy approach to jump to target positions based on value comparisons
C. Modified binary search to find leftmost and rightmost positions separately
D. Dynamic programming to store intermediate results for each index

Solution

  1. Step 1: Understand problem constraints

    The array is sorted, so binary search can be used to find target positions efficiently.
  2. Step 2: Identify suitable algorithm

    Modified binary search can find leftmost and rightmost indices in O(log n) time, which is optimal compared to linear scan or greedy methods.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Binary search exploits sorted property for O(log n) search [OK]
Hint: Sorted array + position search -> modified binary search [OK]
Common Mistakes:
  • Thinking linear scan is optimal
  • Confusing greedy with binary search
  • Using DP unnecessarily
3. What is the time complexity of the recursive modified binary search algorithm for finding a peak element in an array of size n, and why might some candidates mistakenly think it is worse?
medium
A. O(n) because each recursive call processes a subarray of size n-1
B. O(log n) because each recursive call halves the search space
C. O(n log n) because recursion adds a log n factor to linear scanning
D. O(log n) time but O(n) space due to recursion stack

Solution

  1. Step 1: Analyze recursive calls

    Each call halves the search space, so number of calls is O(log n).
  2. Step 2: Confirm work per call

    Each call does O(1) work (simple comparisons), so total time is O(log n).
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Halving search space leads to logarithmic time [OK]
Hint: Halving input size -> O(log n) time [OK]
Common Mistakes:
  • Confusing recursion stack space with time
  • Assuming linear scan inside recursion
  • Thinking recursion multiplies complexity
4. Examine the following buggy code that attempts to search a target in a 2D matrix using the staircase search approach starting from the top-left corner. Identify the line containing the subtle bug that causes incorrect behavior or infinite loops.
medium
A. Line 9: Incrementing row when element is less than target
B. Line 7: Using '<' instead of '<=' in while condition
C. Line 11: Decrementing col without boundary check
D. Line 3: Starting at top-left corner instead of top-right

Solution

  1. Step 1: Analyze starting point

    Starting at top-left corner breaks the staircase search logic because we cannot eliminate rows or columns correctly.
  2. Step 2: Check pointer movements

    Moving row down when current < target and col left when current > target only works if starting at top-right corner.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Starting at top-left causes infinite loops or wrong results [OK]
Hint: Staircase search must start at top-right corner [OK]
Common Mistakes:
  • Starting at top-left or bottom-left corner
  • Not checking empty matrix
  • Moving pointers in wrong directions
5. Consider the following buggy code snippet for finding the pivot in a rotated sorted array. Which line contains the subtle bug that can cause incorrect pivot detection?
medium
A. if nums[mid] > nums[high]: -- comparison logic is correct
B. mid = (low + high) / 2 -- mid should be integer index, not float
C. low = mid + 1 -- updating low is correct when nums[mid] > nums[high]
D. return low -- returning low as pivot is correct

Solution

  1. Step 1: Identify mid calculation issue

    mid is computed using division '/', which returns float in Python 3, causing invalid indexing.
  2. Step 2: Impact of float mid

    Using float as index causes runtime error or incorrect behavior; integer division '//' is required.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Changing '/' to '//' fixes the bug [OK]
Hint: mid must be integer index [OK]
Common Mistakes:
  • Using '/' instead of '//' in Python
  • Misplaced comparison operators
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard