v9.1.1
Menu

Single Number

easyFREEHash Maps & SetsApple DSA

Given an array where every element appears twice except one, find the single element. Must run in O(n) time and O(1) space.

Example

Input
2,2,1
Output
1
Reasoning
  • nums holds the values 2,2,12, 2, 1, so n=3n = 3. The promise is that every value occurs exactly twice except one value that occurs once, so nn is always odd: n=2k+1n = 2k + 1, here k=1k = 1.
  • Counting occurrences: the value 22 sits at positions 00 and 11 (count 22); the value 11 sits at position 22 (count 11).
  • The answer is the one value whose count is odd, here v=1v = 1, so the output is 1.
  • The output is a single integer taken from the array itself, not an index or a count. Order is irrelevant: the arrangements 1, 2, 2 or 2, 1, 2 give the same answer.
  • Notice the limits: O(n)O(n) time means each element is looked at a constant number of times, and O(1)O(1) space means the extra memory cannot grow with nn, so a separate tally for every distinct value is off the table. Values can be negative (down to −3×104-3 \times 10^4), and a one-element array such as [1][1] just returns its element.

Constraints

  • 1 <= len(nums) <= 3 * 10^4
  • -3 * 10^4 <= nums[i] <= 3 * 10^4

More from Apple DSA

solution.py

Test results

Sign in to run your code against the test cases.