KatInterview

Locate the Lone Value in a Sorted Paired List

Heaps, Sorting & SearchAuto-graded · 18 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchsorted-arrayparity

Last updated

Use parity-based binary search on a sorted array of duplicated values to find the one value without a partner in logarithmic time and constant extra space.

Lone Value in a Sorted Paired List

You receive a list of integers values that is sorted in non-decreasing order. Every number in it occurs exactly two times, with a single exception: one number occurs only once.

Return that number that has no partner.

Your algorithm must run in O(log n) time and use O(1) extra space, where n is the length of the list.

Input

  • values: a sorted list of integers whose length is odd, in which exactly one value appears once and every other value appears exactly twice.

Output

  • A single integer: the value that appears exactly once.

Notes

  • A list with a single element is valid, and that element is the answer.
  • The lone value may be at the very start or the very end of the list.

Constraints

  • 1 <= len(values) <= 10^5
  • 0 <= values[i] <= 10^5
  • values is sorted in non-decreasing order.
  • Exactly one value appears once; all other values appear exactly twice.

Examples

Example 1

Input: find_lone_value([1, 1, 2, 3, 3, 4, 4, 8, 8])

Output: 2

Example 2

Input: find_lone_value([3, 3, 7, 7, 10, 11, 11])

Output: 10

Hints

Hint 1

Equal values are adjacent because the list is sorted. Think about the index positions where each pair begins, rather than the values themselves.

Hint 2

Before the lone value, each pair starts at an even index. After it, every pair starts at an odd index. This gives you a condition that flips exactly once.

Hint 3

Binary search over even indices only: if values[mid] equals values[mid + 1] (with mid even), the lone value is to the right of that pair; otherwise it is at mid or to its left.