Wednesday, August 24, 2022
HomeWordPress DevelopmentDiscover the MEX of given Array

Discover the MEX of given Array


View Dialogue

Enhance Article

Save Article

Like Article

View Dialogue

Enhance Article

Save Article

Like Article

You’re given an array arr[] of dimension N, the duty is to find out the MEX of the array.

MEX is the smallest complete quantity that’s not current within the array.

Examples:

Enter: arr[] = {1, 0, 2, 4}
Output: 3
Clarification: 3 is the smallest complete quantity that’s not current within the array

Enter: arr[] = {-1, -5, 0, 4}
Output: 1
Clarification: 1 is the smallest complete quantity that’s lacking within the array.

Method: Observe the beneath thought to unravel the issue

Type the array in rising order and discover the primary quantity ranging from 0 which isn’t current within the array.

Observe the steps to unravel the issue:

  • Type the array.
  • Initialize a variable mex = 0.
  • Journey over the array from index 0 to N-1.
  • If the ingredient is the same as mex
    • Increment mex by 1 i.e., mex = mex + 1
    • Else proceed the iteration
  • Return mex as the ultimate reply.

Beneath is the implementation of the above method:

Python3

  

def mex(arr, N):

  

    

    arr.kind()

      

    mex = 0

    for idx in vary(N):

        if arr[idx] == mex:

  

            

            mex += 1

  

    

    return mex

  

  

if __name__ == '__main__':

  

    

    arr = [1, 0, 2, 4]

    N = len(arr)

  

    

    print(mex(arr, N))

Time Complexity: O(N * logN)
Auxiliary House: O(1)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments