Bird
Raised Fist0
Interview Prepmodified-binary-searcheasyAmazonGoogle

Count Occurrences in Sorted Array

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize first binary search for target

Set initial search boundaries lo=0 and hi=7 (length of array) to find left insertion point of target=2.

💡 Starting with the full array ensures we consider all possible positions for the target.
Line:left = bisect.bisect_left(nums, target)
💡 The search space covers the entire array initially.
📊
Count Occurrences in Sorted Array - Watch the Algorithm Execute, Step by Step
Watching each binary search step reveals how the search space shrinks and how the algorithm pinpoints the exact boundaries of the target values efficiently.
Step 1/11
·Active fill★Answer cell
Target: 2
lo
1
0
2
1
2
2
2
3
3
4
4
5
5
6
Next: lo=0 hi=7
Target: 2
lo
1
0
2
1
2
2
mid
2
3
3
4
4
5
5
6
mid[3]=2 - mid_value == target, move hi to mid
Next: lo=0 hi=3
Target: 2
lo
1
0
mid
2
1
2
2
hi
2
3
3
4
4
5
5
6
mid[1]=2 - mid_value == target, move hi to mid
Next: lo=0 hi=1
Target: 2
lo/mid
1
0
hi
2
1
2
2
2
3
3
4
4
5
5
6
mid[0]=1 - mid_value < target, move lo to mid+1
Next: lo=1 hi=1
Target: 2
1
0
lo/hi
2
1
2
2
2
3
3
4
4
5
5
6
Next: lo=1 hi=1
Target: 3
lo
1
0
2
1
2
2
2
3
3
4
4
5
5
6
Next: lo=0 hi=7
Target: 3
lo
1
0
2
1
2
2
mid
2
3
3
4
4
5
5
6
mid[3]=2 - mid_value < target, move lo to mid+1
Next: lo=4 hi=7
Target: 3
1
0
2
1
2
2
2
3
lo
3
4
mid
4
5
5
6
mid[5]=4 - mid_value > target, move hi to mid
Next: lo=4 hi=5
Target: 3
1
0
2
1
2
2
2
3
lo/mid
3
4
hi
4
5
5
6
mid[4]=3 - mid_value == target, move hi to mid
Next: lo=4 hi=4
Target: 3
1
0
2
1
2
2
2
3
lo/hi
3
4
4
5
5
6
Next: lo=4 hi=4
Target: 2
1
0
2
1
2
2
2
3
3
4
4
5
5
6

Key Takeaways

✓ Binary search can be used twice to find the exact boundaries of a target value in a sorted array.

This insight is hard to see from code alone because the two searches look similar but serve different boundary-finding purposes.

✓ The difference between the left insertion points of target and target+1 gives the count of target occurrences efficiently.

Understanding this arithmetic relationship is easier when visualizing the insertion points rather than scanning the array.

✓ Each binary search step eliminates half the search space by comparing mid_value with the target, honing in on the left boundary.

Seeing how lo and hi move step-by-step clarifies why binary search is O(log n) and how it finds boundaries precisely.

Practice

(1/5)
1. 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
2. Consider the following code snippet implementing the optimal binary search to find the single element in a sorted array where every other element appears twice. What is the returned value when the input is [1,1,2,3,3]?
easy
A. 3
B. 1
C. 2
D. Error due to index out of range

Solution

  1. Step 1: Trace first iteration with low=0, high=4

    mid = 2 (even), nums[2]=2, nums[3]=3 not equal, so high = mid = 2
  2. Step 2: Trace second iteration with low=0, high=2

    mid = 1 (odd), nums[1]=1, nums[0]=1 equal, so low = mid + 1 = 2
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Loop ends with low=2, nums[2]=2 returned [OK]
Hint: Check parity and compare adjacent elements carefully [OK]
Common Mistakes:
  • Off-by-one errors in mid calculation
  • Confusing even/odd parity logic
  • Assuming index out of range error
3. What is the time complexity of the optimal approach that uses a single binary search followed by expanding boundaries to find the first and last positions of the target in a sorted array?
medium
A. O(n)
B. O(log n + k), where k is the number of occurrences of the target
C. O(log n * k), where k is the number of occurrences of the target
D. O(log n)

Solution

  1. Step 1: Analyze binary search phase

    Binary search runs in O(log n) to find one occurrence of target.
  2. Step 2: Analyze boundary expansion phase

    Expanding left and right to find all occurrences takes O(k), where k is count of target.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Combined complexity is O(log n + k), not multiplicative [OK]
Hint: Binary search plus linear expansion over occurrences [OK]
Common Mistakes:
  • Assuming O(log n) only
  • Multiplying log n by k incorrectly
  • Ignoring expansion cost
4. Suppose the array is no longer sorted but you still need to find the first and last positions of a target value. Which approach is correct and efficient?
hard
A. Use a linear scan to find first and last occurrences directly
B. Sort the array first, then apply modified binary search to find positions
C. Use the same modified binary search approach since it works on any array
D. Use a hash map to store all indices of each value, then retrieve target positions

Solution

  1. Step 1: Recognize that binary search requires sorted array

    Without sorting, binary search cannot guarantee correct positions.
  2. Step 2: Evaluate alternatives

    Sorting changes indices, so linear scan or hash map are options; linear scan is simplest and O(n).
  3. Step 3: Compare efficiency and correctness

    Linear scan finds first and last positions in one pass without modifying array.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Binary search requires sorted input; linear scan works otherwise [OK]
Hint: Binary search needs sorted array; linear scan works otherwise [OK]
Common Mistakes:
  • Trying binary search on unsorted array
  • Sorting and losing original indices
  • Overcomplicating with hash maps
5. Suppose the matrix rows are sorted but columns are not guaranteed to be sorted. Which of the following approaches correctly finds the target value efficiently?
hard
A. Use the staircase search starting from the top-right corner.
B. Use a brute force nested loop to check every element.
C. Perform binary search on each row independently.
D. Sort each column first, then apply staircase search.

Solution

  1. Step 1: Understand matrix constraints

    Only rows are sorted; columns are unsorted, so staircase search assumptions fail.
  2. Step 2: Evaluate approaches

    Binary search on rows works but columns unsorted means target could be anywhere in columns; brute force guarantees correctness.
  3. Step 3: Consider sorting columns

    Sorting columns is expensive and changes matrix; not practical for search.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Brute force is correct though less efficient; others rely on column sorting [OK]
Hint: Without column sorting, staircase search fails [OK]
Common Mistakes:
  • Assuming staircase search works with only row sorting
  • Thinking sorting columns is cheap
  • Believing binary search on rows suffices
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