Search⌘ K
AI Features

Single Element in a Sorted Array

Understand how to find the single non-duplicate element in a sorted array where every other element appears twice. Explore modified binary search techniques to achieve O(log n) time and constant space, helping you solve this common coding interview problem efficiently.

Statement

You are given a sorted array of integers, nums, where all integers appear twice except for one. Your task is to find and return the single integer that appears only once.

The solution should have a time complexity of O(logn)O(\log n) or better and a space complexity of O(1)O(1).

Constraints:

  • 11 \leq nums.length 103\leq 10^3

  • 00 \leq nums[i] 103\leq 10^3

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps us to check if you’re solving the correct problem:

Single Element in a Sorted Array

1.

What is the output if the following array is provided as input?

[1, 1, 2, 2, 3, 4, 4]

A.

1

B.

3

C.

2

D.

4


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in main.js in the following coding playground. We have provided a useful code template in the other file that you may build on to solve this problem.

JavaScript
usercode > main.js
export function singleNonDuplicate(nums) {
// Replace this placeholder return statement with your code
return -1;
}
Single Element in a Sorted Array