Practice
Solution
Step 1: Understand problem constraints
The array is sorted and every element except one appears twice consecutively.Step 2: Identify algorithm that exploits sorted pairs
Modified binary search using index parity halves the search space by comparing pairs, achieving O(log n).Final Answer:
Option A -> Option AQuick Check:
Binary search with parity is known optimal for this problem [OK]
- Thinking linear scan is optimal
- Using DP unnecessarily
- Applying greedy without global insight
def findPeakElement(nums):
def binarySearch(low, high):
if low == high:
return low
mid = (low + high) // 2
if nums[mid] < nums[mid]: # Line X
return binarySearch(mid + 1, high)
else:
return binarySearch(low, mid)
return binarySearch(0, len(nums) - 1)
Solution
Step 1: Identify suspicious comparison
Line 5 compares nums[mid] with itself, which is always false, causing wrong recursion path.Step 2: Understand impact
This bug causes infinite recursion or incorrect peak detection because the condition never triggers correctly.Final Answer:
Option A -> Option AQuick Check:
Comparison must be nums[mid] < nums[mid + 1] [OK]
- Comparing mid with mid instead of mid+1
- Off-by-one causing infinite recursion
- Returning wrong index after recursion
Solution
Step 1: Identify outer binary search complexity
Binary search on value range runs in O(log(maxVal - minVal)) iterations.Step 2: CountLessEqual calls cost
Each countLessEqual uses bisect on both arrays, each O(log m) and O(log n), total O(log m + log n).Final Answer:
Option D -> Option DQuick Check:
Nested binary searches multiply complexities [OK]
- Confusing with merge O(m+n)
- Assuming O(log(m+n)) without value range
- Ignoring bisect cost inside loop
Solution
Step 1: Identify mid calculation issue
Using '/' in Python 3 returns float, which cannot index arrays, causing errors or infinite loops.Step 2: Confirm other lines are correct
Parity checks and updates are correct; no out-of-range access due to loop conditions.Final Answer:
Option D -> Option DQuick Check:
mid must be integer index; float causes failure [OK]
- Using '/' instead of '//' in Python 3
- Confusing parity logic
- Incorrect boundary updates
Solution
Step 1: Understand problem change
The single element may appear multiple times, breaking the strict pair pattern.Step 2: Analyze binary search adaptation
Parity-based halving fails; instead, compare mid with neighbors and count duplicates to decide which half to search.Step 3: Confirm other options
Linear scan is inefficient; hash map uses extra space and is unnecessary if modified binary search works.Final Answer:
Option A -> Option AQuick Check:
Counting duplicates around mid guides correct binary search [OK]
- Assuming parity logic still works
- Switching to linear scan prematurely
- Using extra space unnecessarily
