Set Mismatch

A set originally held every integer from 1 to n, but one number was overwritten by a copy of another, so one value now appears twice and another is missing. Given the resulting array nums, return [the number that occurs twice, the number that is missing].

30:00

Set Mismatch
easy
Free written solution
Topics
Companies

A set originally held every integer from 1 to n, but one number was overwritten by a copy of another, so one value now appears twice and another is missing. Given the resulting array nums, return [the number that occurs twice, the number that is missing].

Example 1:
Input: {"nums":[1,2,2,4]}
Output: [2,3]
Constraints:
  • 2≤nums.length≤1042 \leq \text{nums.length} \leq 10^4

  • 1≤nums[i]≤1041 \leq \text{nums}[i] \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,2,4]}

Box i holds a sign flag for the number i + 1. Reading a value v flips box v - 1 negative, so a box that is already negative means v showed up twice.

nums as boxes: box i is the flag for number i + 1

▼read

1

#1

▼read

2

#2

▼read

2

#3

▼read

4

#4

negative = number seen

already negative = duplicate

still positive at the end = missing

flags set: 0 of 4

dup = ?
missing = ?
Variables
VariableValue
n4
dup-1
missing-1
DepthFunction Call
Stack empty
0/10