Find the number that appears once when every other number appears three times

Quick Overview

Given an integer array where every value appears three times except one, return the value that appears exactly once in linear time with constant extra space. It tests bit manipulation when the pairwise cancellation trick no longer works, and careful handling of negative 32-bit values.

Find the number that appears once when every other number appears three times

Company: AMD

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

You are given an integer array `nums` where every element appears three times except for one, which appears exactly once. Find the single element and return it. You must implement a solution with linear runtime complexity that uses only constant extra space. ### Function Signature ```python def single_number(nums: list[int]) -> int: ``` ### Constraints - `1 <= len(nums) <= 3 * 10^4` - `-2^31 <= nums[i] <= 2^31 - 1` - Each element in `nums` appears exactly three times except for one element, which appears exactly once. ### Examples #### Example 1 ```text Input: nums = [2,2,3,2] Output: 3 ``` The element 3 appears once, while 2 appears three times. #### Example 2 ```text Input: nums = [0,1,0,1,0,1,99] Output: 99 ``` The element 99 appears once, while 0 and 1 each appear three times. #### Example 3 ```text Input: nums = [7,-5,7,7] Output: -5 ``` The single element can be negative: 7 appears three times and -5 appears once, so the function returns -5.

Overview: Given an integer array where every value appears three times except one, return the value that appears exactly once in linear time with constant extra space. It tests bit manipulation when the pairwise cancellation trick no longer works, and careful handling of negative 32-bit values.

AMD logo
AMD
Nov 25, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

You are given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.

You must implement a solution with linear runtime complexity that uses only constant extra space.

Function Signature

def single_number(nums: list[int]) -> int:

Constraints

  • 1 <= len(nums) <= 3 * 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
  • Each element in nums appears exactly three times except for one element, which appears exactly once.

Examples

Example 1

Input: nums = [2,2,3,2]
Output: 3

The element 3 appears once, while 2 appears three times.

Example 2

Input: nums = [0,1,0,1,0,1,99]
Output: 99

The element 99 appears once, while 0 and 1 each appear three times.

Example 3

Input: nums = [7,-5,7,7]
Output: -5

The single element can be negative: 7 appears three times and -5 appears once, so the function returns -5.