AlgoInsight

DSA problem

Set Mismatch

EasyBit ManipulationPattern: Bit Manipulationtop600AmazonMicrosoftGoogle

You have a set s that originally contained numbers from 1 to n. Due to an error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.

You are given an integer array nums representing the data status of this set after the error. Find the number that occurs twice and the number that is missing, and return them as an array [duplicate, missing].

A clean bit-manipulation approach XOR-es together every value from 1 to n and every element of nums. The result equals duplicate XOR missing. The lowest set bit of that result is a bit where the two differ, which lets you partition all numbers into two groups and isolate each one.

Examples

Example 1
Input: nums = [1,2,2,4]
Output: [2,3]
Explanation: The number 2 appears twice and the number 3 is missing from the range [1,4].
Example 2
Input: nums = [1,1]
Output: [1,2]
Explanation: The number 1 is duplicated and the number 2 is missing from the range [1,2].
Example 3
Input: nums = [3,2,3,4,6,5]
Output: [3,1]
Explanation: The number 3 appears twice and the number 1 is missing from the range [1,6].

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bit-manipulationxorarrayhash-table

Browse all DSA problems