Find the smallest non-negative integer missing from an array (MEX)

Quick Overview

Given an array of non-negative integers, return its MEX, the smallest non-negative integer that does not appear in it. It tests hash set lookups, bounding the range of values worth checking, and handling duplicates and very large values without wasting memory.

Find the smallest non-negative integer missing from an array (MEX)

Company: Mercari

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given an integer array `nums`, find its **MEX** (minimum excluded value). The MEX of an array is the smallest non-negative integer that does not appear in the array. For example, the MEX of `[0, 1, 2, 4]` is `3`, the MEX of `[1, 2, 3]` is `0`, and the MEX of `[0, 1, 2, 3]` is `4`. ### Function Signature ```python def find_mex(nums: list[int]) -> int: ``` ### Constraints - `1 <= len(nums) <= 10^5` - `0 <= nums[i] <= 10^9` ### Examples ```text Input: nums = [0,1,2,4] Output: 3 ``` The numbers 0, 1 and 2 are present, but 3 is missing, so the MEX is 3. ```text Input: nums = [1,2,3] Output: 0 ``` 0 is the smallest non-negative integer not in the array, so the MEX is 0. ```text Input: nums = [3,0,1,1,1000000000] Output: 2 ``` 0 and 1 are present (1 twice), and 2 is the first value that is missing. The values 3 and 1000000000 do not change the answer.

Overview: Given an array of non-negative integers, return its MEX, the smallest non-negative integer that does not appear in it. It tests hash set lookups, bounding the range of values worth checking, and handling duplicates and very large values without wasting memory.

Mercari logo
Mercari
Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given an integer array nums, find its MEX (minimum excluded value).

The MEX of an array is the smallest non-negative integer that does not appear in the array.

For example, the MEX of [0, 1, 2, 4] is 3, the MEX of [1, 2, 3] is 0, and the MEX of [0, 1, 2, 3] is 4.

Function Signature

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

Constraints

  • 1 <= len(nums) <= 10^5
  • 0 <= nums[i] <= 10^9

Examples

Input: nums = [0,1,2,4]
Output: 3

The numbers 0, 1 and 2 are present, but 3 is missing, so the MEX is 3.

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

0 is the smallest non-negative integer not in the array, so the MEX is 0.

Input: nums = [3,0,1,1,1000000000]
Output: 2

0 and 1 are present (1 twice), and 2 is the first value that is missing. The values 3 and 1000000000 do not change the answer.