Detecting Duplicates in O(1) Space and O(n) Time - Jason Davies
Given an array of n integers, each between 1 and n-1 inclusive, can you detect duplicates in O(1) space and O(n) time?
Assume that the input is available as an array (with O(1) lookup time). Note that there must be at least one duplicate due to the pigeonhole principle.
The trick is to treat each integer as an index of the input array, such that it points to another integer in the input i.e. treat it as a "pointer"
Read full article from Detecting Duplicates in O(1) Space and O(n) Time - Jason Davies
No comments:
Post a Comment