oneby7

Binary Search Searching a sorted array

237. Single Element in a Sorted Array

Medium

You are given an array of integers nums, sorted in non-decreasing order. Every value in it appears exactly twice, except one value, which appears only once. Return the value that appears once.

Because the array is sorted, the two copies of a value always sit next to each other.

Aim for O(log n) time and O(1) extra space.

Example 1

Input: nums = [-4, -4, 1, 1, 6, 9, 9, 12, 12, 20, 20]

Output: 6

Explanation: −4, 1, 9, 12 and 20 each appear twice, side by side. Only 6, at index 4, has no copy.

Example 2

Input: nums = [3]

Output: 3

Example 3

Input: nums = [-1000000000, -1000000000, -6, -6, 0, 0, 1000000000]

Output: 1000000000

Explanation: The first three values all have their copy. The value without one is the largest, and it is the last element.

Check your understanding

Work out the answer for this input before you write any code.

nums = [-3, -3, 0, 4, 4, 9, 9]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • nums[i] ≤ nums[i + 1] (sorted)
  • Every value appears exactly twice, except one value, which appears once.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.