Skip to content

Commit 99220f2

Browse files
authored
Add C++ implementation
1 parent 0df0562 commit 99220f2

1 file changed

Lines changed: 35 additions & 9 deletions

File tree

src/sequences/mex.md

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,41 @@ First we have to create a set of all elements in the array to quickly check for
99

1010
*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.
1111

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)
12+
## Implementation (C++):
13+
14+
```cpp
15+
int mex(vector<int> a) {
16+
set<int> b(a.begin(), a.end());
17+
for (int i=0; ; ++i)
18+
if (!b.count(i))
19+
return i;
20+
}
21+
```
22+
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:
24+
25+
```cpp
26+
int mex (const vector<int> & a) {
27+
static bool used[D+1] = { 0 };
28+
int c = (int) a.size();
29+
30+
for (int i=0; i<c; ++i)
31+
if (a[i] <= D)
32+
used[a[i]] = true;
33+
34+
int result;
35+
for (int i=0; ; ++i)
36+
if (!used[i]) {
37+
result = i;
38+
2 break;
39+
}
40+
41+
for (int 1 i=0; i<c; ++i)
42+
if (a[i] <= D)
43+
used[a[i]] = false;
44+
45+
return result;
46+
}
2147
```
2248

2349

0 commit comments

Comments
 (0)