Bird
Raised Fist0
Interview Prepmodified-binary-searchmediumAmazonFacebookGoogle

Single Element in Sorted Array

Choose your preparation mode4 modes available
📋
Problem

Imagine you have a sorted list of product IDs where every product appears exactly twice except one unique product that appears only once. You want to find that unique product efficiently.

Given a sorted array consisting of only integers where every element appears exactly twice except for one element which appears exactly once, find this single element that appears only once. Your solution must run in O(log n) time and O(1) space. Input: A sorted integer array nums. Output: The single element that appears only once.

1 ≤ nums.length ≤ 10^50 ≤ nums[i] ≤ 10^9nums is sorted in ascending orderEvery element appears exactly twice except for one element which appears once
Edge cases: Single element array [5] → 5Single element at the start [2,3,3,4,4] → 2Single element at the end [1,1,2,2,3] → 3
</>
IDE
def singleNonDuplicate(nums: list[int]) -> int:public int singleNonDuplicate(int[] nums)int singleNonDuplicate(vector<int> &nums)function singleNonDuplicate(nums)
def singleNonDuplicate(nums):
    # Write your solution here
    pass
class Solution {
    public int singleNonDuplicate(int[] nums) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int singleNonDuplicate(vector<int> &nums) {
    // Write your solution here
    return 0;
}
function singleNonDuplicate(nums) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 1Always returning the first element without checking pairs or parity.✅ Implement binary search with parity checks to find the single element instead of returning nums[0].
Wrong: 3Returning the middle element without verifying if it is single or part of a pair.✅ Check if nums[mid] equals nums[mid+1] or nums[mid-1] and adjust search boundaries accordingly.
Wrong: 2Off-by-one error causing incorrect mid calculation or boundary update.✅ Use mid = low + (high - low) // 2 and update low or high carefully based on parity and pair checks.
Wrong: last element or out of bounds errorNot handling single-element or boundary cases properly, causing index errors or wrong returns.✅ Add base cases for single-element arrays and check boundaries before accessing nums[mid+1].
Wrong: Timeout or no outputUsing linear scan or exponential approach instead of binary search.✅ Implement O(log n) binary search using parity-based halving to avoid TLE.
✓
Test Cases
t1_01basic
Input{"nums":[1,1,2,3,3,4,4,8,8]}
Expected2

All elements except 2 appear twice. 2 is the single element.

t1_02basic
Input{"nums":[3,3,7,7,10,11,11]}
Expected10

10 is the single element appearing once; all others appear twice.

t2_01edge
Input{"nums":[5]}
Expected5

Single element array; the only element is the single element.

t2_02edge
Input{"nums":[2,3,3,4,4]}
Expected2

Single element is at the start of the array.

t2_03edge
Input{"nums":[1,1,2,2,3]}
Expected3

Single element is at the end of the array.

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

Single element 3 is in the middle; tests off-by-one errors in binary search.

t3_02corner
Input{"nums":[1,1,2,3,3,4,4,5,5]}
Expected2

Single element 2 is just after a pair; tests greedy approach trap.

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

Single element 4 is just before a pair; tests confusion between 0/1 and unbounded knapsack style indexing.

t4_01performance
Input{"nums":[1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,30,30,31,31,32,32,33,33,34,34,35,35,36,36,37,37,38,38,39,39,40,40,41,41,42,42,43,43,44,44,45,45,46,46,47,47,48,48,49,49,50]}
⏱ Performance - must finish in 2000ms

n=101 with one single element at the end (50). Algorithm must run in O(log n) time within 2 seconds.

Practice

(1/5)
1. You need to find the minimum speed to travel through a series of distances within a given total time, where each segment except the last must be completed in whole hours (rounded up). Which algorithmic approach guarantees finding the minimum feasible speed efficiently?
easy
A. Binary search on the speed range (answer space) combined with a feasibility check
B. Brute force linear search incrementing speed until the time constraint is met
C. Dynamic programming to store minimum speeds for subproblems
D. Greedy approach by always choosing the fastest possible speed for each segment

Solution

  1. Step 1: Understand the problem constraints

    The problem requires finding the minimum speed that satisfies a time constraint with rounding up travel times for all but the last segment.
  2. Step 2: Identify the suitable algorithmic pattern

    Binary search on the answer space (speed) efficiently narrows down the minimum feasible speed by checking feasibility at midpoints, unlike greedy or DP which do not fit the problem structure.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Binary search on answer space is standard for optimization problems with monotonic feasibility [OK]
Hint: Binary search on answer space fits monotonic feasibility [OK]
Common Mistakes:
  • Thinking greedy or DP can solve this efficiently
  • Using brute force linear search without pruning
2. Consider the following code snippet that searches for a target in a 2D matrix by performing binary search on each row. Given the matrix = [[1,3,5],[7,9,11],[13,15,17]] and target = 9, what is the return value of the function searchMatrix(matrix, target)?
easy
A. True
B. Returns None
C. Raises an exception
D. False

Solution

  1. Step 1: Trace binary search on second row [7,9,11]

    Mid index 1 has value 9 which equals target, so binary_search returns True.
  2. Step 2: searchMatrix returns True immediately after finding target

    Since binary_search returns True for second row, searchMatrix returns True.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Target found in second row at mid index 1 [OK]
Hint: Binary search returns True when target found [OK]
Common Mistakes:
  • Off-by-one errors in mid calculation
  • Returning False prematurely
  • Confusing return values
3. What is the time complexity of the optimal binary search approach to find the kth positive missing number in a sorted array of length n?
medium
A. O(log n)
B. O(k + n)
C. O(n log k)
D. O(n)

Solution

  1. Step 1: Identify the binary search loop

    The algorithm performs binary search on the array indices, halving the search space each iteration.
  2. Step 2: Analyze loop iterations

    Binary search runs in O(log n) time, independent of k, since it only searches within the array length.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Binary search halves search space each step -> O(log n) [OK]
Hint: Binary search on array indices -> O(log n) [OK]
Common Mistakes:
  • Confusing with brute force O(k + n)
  • Assuming dependence on k
  • Thinking recursion stack adds complexity
4. Identify the bug in the following modified code snippet for the Minimum Days to Make m Bouquets problem:
medium
A. The feasibility function does not reset flowers count correctly.
B. Binary search boundaries are incorrectly set from 0 instead of min bloom day.
C. The initial check for m * k > n is missing, causing unnecessary computation.
D. Early stopping in feasibility function is missing, causing slower runtime.

Solution

  1. Step 1: Check initial conditions

    The code lacks the check if m * k > n, which means it's impossible to make required bouquets.
  2. Step 2: Consequences of missing check

    Without this, the code runs unnecessary binary search and feasibility checks, possibly returning wrong answers or timing out.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Adding the initial impossible case check fixes the bug. [OK]
Hint: Always check if total flowers suffice before processing [OK]
Common Mistakes:
  • Forgetting impossible case check
  • Misresetting flowers count in feasibility
5. Suppose the problem is modified so that the matrix rows are sorted but columns are not guaranteed to be sorted. Which approach would correctly find the kth smallest element efficiently?
hard
A. Use the min-heap approach merging rows as before, since rows remain sorted.
B. Flatten the matrix and sort it, then return the kth element.
C. Use binary search on the value range with a counting function scanning the entire matrix.
D. Use a min-heap merging columns instead of rows.

Solution

  1. Step 1: Analyze matrix properties

    Rows are sorted but columns are not, so min-heap merging rows only partially orders elements.
  2. Step 2: Evaluate approaches

    Min-heap merging rows assumes columns sorted for correctness; binary search counting requires sorted rows and columns for efficient counting; flatten and sort works regardless.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Flatten and sort is the fallback when only rows sorted [OK]
Hint: Partial sorting breaks heap and binary search assumptions [OK]
Common Mistakes:
  • Assuming min-heap merging rows still works
  • Using binary search counting without full sorting
  • Ignoring matrix sorting properties
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