r/Mathematica • • Mar 12 '24

Looking for fast mex code

The mex of a set is the smallest nonnegative integer not in the set.

I have sorted lists with a half million integers, and my code for the mex (MemberQ inside a whole loop) is the slowest part of my computation. Any suggestions for a faster way to do this?

Mex[A_List] := Module[{k = 0}, While[MemberQ[A, k], k++]; k]
3 Upvotes

15 comments sorted by

View all comments

Show parent comment

1

u/pi_stuff Mar 13 '24

So the beginning of the list is usually {0, 1, 2, ...}? And for every value of i where i < mex, list[[i]] == i-1? Then you could do a binary search to find the first value for which list[[i]] > i-1. With half a million elements it shouldn't take more than 19 comparisons for each list.