Find the mex of the array in o(n) time and constant space complexity; mex = smallest missing element from the array please share your ideas on this tia
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
Find the mex of the array in o(n) time and constant space complexity; mex = smallest missing element from the array please share your ideas on this tia
Name |
---|
Say n is the size of the array.
Loop through the array:
Let the element you are currently at be a.
If a > n, then just continue
otherwise, swap the values of the current element, and the a(th) element.
The answer will be the the (first index where the index(th) element of the list is not equal to index + 1) + 1.
Note that this is O(1) in space and O(n) time complexity.
In input/output problems (like codeforces, the web where he is asking) you will have to create an array for that, so its O(n) space complexity.
I understand that but i was under the impression that storing the input itself doesnt count towards the space complexity because i have seen editorials where this has happened (i think). Also, mex in O(1) space (by your standards) seems like quite a tall order. I feel like its probably impossible
This assumes all the elements are distinct.
Why do you say so? Notice that in this method, after the initial swaps are done, the value at position i will contain i + 1 if i + 1 exists in the array. Also, if the value at position i does not contain i + 1, then we can be confident that i+1 is not in the original array. So finding the first index where value at index does not equal index + 1 should work no?