3. Single Number
easyAsked at ConfluentFind the one element appearing once when every other appears twice — Confluent uses it to probe whether you know XOR tricks before scaling to deduplicating Kafka records.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given a non-empty array where every element appears twice except one, return the single one. Solve it with linear time and constant extra space.
Constraints
1 <= nums.length <= 3*10^4Every element appears twice except for one-3*10^4 <= nums[i] <= 3*10^4
Examples
Example 1
nums=[2,2,1]1Example 2
nums=[4,1,2,1,2]4Approaches
1. Hash map count
Count occurrences in a map and return the one with count 1.
- Time
- O(n)
- Space
- O(n)
const c=new Map();
for (const x of nums) c.set(x,(c.get(x)||0)+1);
for (const [k,v] of c) if (v===1) return k;Tradeoff:
2. XOR fold
XOR every element; pairs cancel and only the singleton remains. Constant space, single pass.
- Time
- O(n)
- Space
- O(1)
function singleNumber(nums) {
let r = 0;
for (const x of nums) r ^= x;
return r;
}Tradeoff:
Confluent-specific tips
Confluent will probe the streaming variant — explain how XOR aggregates over a partition let you dedupe without holding the full key set in memory across a consumer-group rebalance.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
More Confluent coding interview questions
- 1. Two Sum
- 2. Best Time to Buy and Sell Stock
- 4. Majority Element
- 5. Contains Duplicate
- 6. Valid Anagram
- 7. Missing Number
- 8. Design HashMap
- 9. LRU Cache