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
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
9 | nor | 153 |
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
Название |
---|
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?