How to tell if an array is a permutation in O(n)?

后端 未结 16 1647
粉色の甜心
粉色の甜心 2020-12-07 10:17

Input: A read-only array of N elements containing integer values from 1 to N (some integer values can appear more than once!). And a memory zone of a fixed<

16条回答
  •  北海茫月
    2020-12-07 10:36

    Depending on how much space you have, relative to N, you might try using hashing and buckets.

    That is, iterate over the entire list, hash each element, and store it in a bucket. You'll need to find a way to reduce bucket collisions from the hashes, but that is a solved problem.

    If an element tries to go into a bucket with an item identical to it, it is a permutation.

    This type of solution would be O(N) as you touch each element only once.

    However, the problem with this is whether space M is larger than N or not. If M > N, this solution will be fine, but if M < N, then you will not be able to solve the problem with 100% accuracy.

提交回复
热议问题