Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding MEX of a changing set

I am trying to create a method add that adds elements x to the set one by one and returns MEX (=minimum non-negative number not in the set) of the list at each point.

class Mex:
    def __init__(self):
        self.mex = set()

    def add(self, x):
        self.mex.add(x)
        mex = 0
        while mex in self.mex:
            mex += 1
        return mex

This is not efficient enough and it’s probably because the set changes each time. I have also tried the following but the problem is the same

    def add(self,x):   
         self.mex.add(x)
         for i in range(len(self.mex)):
             if i not in self.mex:
                 return i
        
         return len(self.mex)

Tips?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Don’t always start from 0 again, remember where you were.

class Mex:
    def __init__(self):
        self.added = set()
        self.mex = 0

    def add(self, x):
        self.added.add(x)
        while self.mex in self.added:
            self.mex += 1
        return self.mex
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading