Skip to content

Commit 0df0562

Browse files
committed
Add MEX article
1 parent f53cdb7 commit 0df0562

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/sequences/mex.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
title: MEX (minimal excluded) of a sequence
3+
---
4+
# MEX of a sequence in O(N)
5+
6+
Given an array __A__ of size __N__. You have to find the minimal element that is not present in the array and is equal to or greater than 0. See [Wikipedia](https://en.wikipedia.org/wiki/Mex_(mathematics)) for more information.
7+
8+
First we have to create a set of all elements in the array to quickly check for element presence in O(1). Then check all numbers from 0 to __N__. If the current number is not present in the set, return it. If all numbers are present in the set, return __N__, because all elements from 0 to __N__ - 1 are present.
9+
10+
*NB*: This approach is fast, but works well only if your array doesn't change during program execution, e.g. it is not effective in problems with changing the initial array. If your array is changed by any type of array queries, use [O(N log N) approach](https://codeforces.com/blog/entry/81287?#comment-677837) instead.
11+
12+
## Implementation (Python, C++ will come soon):
13+
14+
```python
15+
def mex(array):
16+
items = set(array)
17+
for i in range(len(array)):
18+
if i not in items:
19+
return i
20+
return len(array)
21+
```
22+
23+
24+
## Practice Problems
25+
26+
- [CODEFORCES: Replace by MEX](https://codeforces.com/contest/1375/problem/D)

0 commit comments

Comments
 (0)