Single Element in Sorted Array - Watch the Algorithm Execute, Step by Step
Watching each pointer movement and comparison helps you understand how parity and pair matching guide the binary search, which is not obvious from code alone.
Step 1/10
·Active fill★Answer cell
lo
1
0
1
1
2
2
3
3
3
4
4
5
4
6
8
7
hi
8
8
Next: lo=0 hi=8
lo
1
0
1
1
2
2
3
3
mid
3
4
4
5
4
6
8
7
hi
8
8
mid[4]=3 - mid is even
Next: lo=0 hi=8
lo
1
0
1
1
2
2
3
3
mid
3
4
4
5
4
6
8
7
hi
8
8
mid[4]=3 - nums[mid] != nums[mid+1], move high to mid
Next: lo=0 hi=4
lo
1
0
1
1
mid
2
2
3
3
hi
3
4
4
5
4
6
8
7
8
8
mid[2]=2 - mid is even
Next: lo=0 hi=4
lo
1
0
1
1
mid
2
2
3
3
hi
3
4
4
5
4
6
8
7
8
8
mid[2]=2 - nums[mid] != nums[mid+1], move high to mid
Next: lo=0 hi=2
lo
1
0
mid
1
1
hi
2
2
3
3
3
4
4
5
4
6
8
7
8
8
mid[1]=1 - mid is odd
Next: lo=0 hi=2
lo
1
0
mid
1
1
hi
2
2
3
3
3
4
4
5
4
6
8
7
8
8
mid[1]=1 - nums[mid] == nums[mid-1], move low to mid+1
Next: lo=2 hi=2
1
0
1
1
lo/hi
2
2
3
3
3
4
4
5
4
6
8
7
8
8
Next: lo=2 hi=2
1
0
1
1
lo/hi
2
2
3
3
3
4
4
5
4
6
8
7
8
8
Next: lo=2 hi=2
1
0
1
1
lo/hi
2
2
3
3
3
4
4
5
4
6
8
7
8
8
Next: lo=2 hi=2
Key Takeaways
✓ Parity of the mid index determines which adjacent element to compare, enabling efficient halving of the search space.
This parity-based logic is subtle and not obvious from code alone; visualization clarifies why even and odd mid indices are handled differently.
✓ When nums[mid] equals its pair element, the single element lies beyond the pair; otherwise, it lies before or at mid.
Understanding this pattern helps grasp how the algorithm eliminates half the array each iteration.
✓ The algorithm converges when low equals high, pinpointing the unique element without scanning the entire array.
This stopping condition is critical and shows the power of binary search in this problem.
Practice
(1/5)
1. You are given an n x n matrix where each row and each column is sorted in ascending order. You need to find the kth smallest element in the matrix efficiently. Which of the following approaches guarantees the optimal time complexity for this problem?
easy
A. Use a greedy approach by repeatedly picking the smallest element from the matrix without extra data structures.
B. Flatten the matrix into a list, sort it, and return the kth element.
C. Apply dynamic programming to build a table of smallest elements up to k.
D. Use a min-heap to merge the sorted rows, extracting the smallest elements until the kth is found.
Solution
Step 1: Understand problem constraints
The matrix rows and columns are sorted, so each row is sorted and each column is sorted independently.
Step 2: Identify the optimal approach
Using a min-heap to merge sorted rows efficiently extracts the smallest elements in ascending order, achieving O(k log n) time, better than flattening and sorting.
2. The following code attempts to find the median of two sorted arrays using binary search on the smaller array. Identify the line containing the subtle bug that can cause incorrect median calculation for even total length arrays.
medium
A. Line: if (m + n) % 2 == 0: return (max(maxLeftX, maxLeftY) + min(minRightX, minRightY)) / 2
B. Line: if len(nums1) > len(nums2): nums1, nums2 = nums2, nums1
C. Line: partitionY = (m + n) // 2 - partitionX
D. Line: while low <= high:
Solution
Step 1: Understand partition calculation
partitionY must be total left half minus partitionX to split arrays correctly.
Step 2: Identify off-by-one bug
Using (m + n) // 2 instead of (m + n + 1) // 2 causes incorrect partition when total length is odd, leading to wrong median.
Final Answer:
Option C -> Option C
Quick Check:
Partition calculation off-by-one breaks median correctness [OK]
Hint: Partition indices must sum to half total length exactly, using (m+n+1)//2 for correct odd/even handling [OK]
Common Mistakes:
Swapping arrays incorrectly
Wrong median formula for even length
Loop boundary off-by-one
3. What is the time complexity of the optimal solution that uses binary search on the answer space combined with prefix sums and binary search for feasibility checks in the Split Array Largest Sum problem?
medium
A. O(n log(sum(nums))) since binary search is done only on sums without extra binary searches
B. O(n^m) due to exploring all splits recursively
C. O(n^2 log(sum(nums))) because feasibility check scans all subarrays linearly
D. O(n log n log(sum(nums))) because each binary search iteration uses binary search on prefix sums
Solution
Step 1: Identify outer binary search on answer space
Binary search on possible sums takes O(log(sum(nums))) iterations.
Step 2: Analyze feasibility check using binary search on prefix sums
Each feasibility check uses binary search (O(log n)) for each subarray, repeated up to n times -> O(n log n).
Final Answer:
Option D -> Option D
Quick Check:
Nested binary searches yield O(n log n log(sum(nums))) [OK]
Assuming feasibility check is O(n) ignoring binary search
Confusing n and m in complexity
Ignoring log factor from binary search on sums
4. Suppose the problem is modified so that the multiplication table allows repeated use of the same row and column indices (i.e., infinite repetitions of each product). Which of the following changes to the algorithm is correct to find the k-th smallest number under this new condition?
hard
A. Use the same binary search with the counting function unchanged, since repetition doesn't affect counts.
B. Switch to generating all products up to k and sorting them, since binary search no longer applies.
C. Use a min-heap to generate products in ascending order with duplicates allowed, extracting k elements.
D. Modify the counting function to remove the cap by n, counting all multiples less than or equal to x for each i.
Solution
Step 1: Understand the new problem condition
Allowing infinite repetitions means the multiplication table is conceptually infinite, so counting by rows capped at n no longer applies.
Step 2: Analyze algorithmic implications
Binary search with counting function fails because counts become infinite or undefined; generating all values is impossible.
Step 3: Use a min-heap approach
A min-heap can generate products in ascending order with duplicates allowed, extracting the k-th smallest efficiently.
Hint: Infinite repetitions break counting; use min-heap [OK]
Common Mistakes:
Assuming counting function unchanged
Trying to generate all values
5. Suppose the rotated sorted array may contain duplicate elements. Which modification to the pivot-finding algorithm is necessary to correctly find the pivot in O(log n) time in the worst case?
hard
A. Add a linear scan fallback when nums[mid] == nums[high] to reduce high by one.
B. Use a hash map to store visited indices to avoid infinite loops.
C. No modification needed; the existing pivot-finding algorithm works unchanged.
D. Switch to linear search for pivot since duplicates break binary search.
Solution
Step 1: Understand duplicates impact
Duplicates can cause nums[mid] == nums[high], making it unclear which half is sorted.
Step 2: Modify pivot search
When nums[mid] == nums[high], reduce high by one to shrink search space safely.
Step 3: Complexity consideration
This modification keeps worst-case complexity close to O(n) but often better than linear scan.
Final Answer:
Option A -> Option A
Quick Check:
Reducing high on equality handles duplicates correctly [OK]
Hint: Handle nums[mid]==nums[high] by decrementing high [OK]
Common Mistakes:
Assuming no duplicates
Switching to linear search unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.