Skip to content

Commit 269cd5d

Browse files
author
Oleksandr Kulkov
authored
Update mex.md
1 parent 55c1d05 commit 269cd5d

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

src/sequences/mex.md

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
---
2+
tags:
3+
- Original
24
title: MEX (minimal excluded) of a sequence
35
---
46
# MEX of a sequence in O(N)
57

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.
8+
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.
79

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.
10+
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.
911

1012
*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.
1113

@@ -20,28 +22,28 @@ int mex(vector<int> a) {
2022
}
2123
```
2224
23-
If an algorithm requires fast O(N) MEX computation, it is possible by computing an boolean vector of existing elements and then checking the first non-present one:
25+
If an algorithm requires fast $O(N)$ MEX computation, it is possible by computing an boolean vector of existing elements and then checking the first non-present one:
2426
2527
```cpp
2628
int mex (const vector<int> & a) {
2729
static bool used[D+1] = { 0 };
2830
int c = (int) a.size();
29-
31+
3032
for (int i=0; i<c; ++i)
3133
if (a[i] <= D)
3234
used[a[i]] = true;
33-
35+
3436
int result;
3537
for (int i=0; ; ++i)
3638
if (!used[i]) {
3739
result = i;
38-
2 break;
40+
break;
3941
}
4042
41-
for (int 1 i=0; i<c; ++i)
43+
for (int i=0; i<c; ++i)
4244
if (a[i] <= D)
4345
used[a[i]] = false;
44-
46+
4547
return result;
4648
}
4749
```

0 commit comments

Comments
 (0)