Algorithm to find a duplicate entry in constant space and O(n) time

后端 未结 8 2033
我在风中等你
我在风中等你 2020-12-16 04:30

Given an array of N integer such that only one integer is repeated. Find the repeated integer in O(n) time and constant space. There is no range for the value of integers or

相关标签:
8条回答
  • 2020-12-16 05:06

    If the range of the integers is bounded, you can perform a counting sort variant in O(n) time. The space complexity is O(k) where k is the upper bound on the integers(*), but that's a constant, so it's O(1).

    If the range of the integers is unbounded, then I don't think there's any way to do this, but I'm not an expert at complexity puzzles.

    (*) It's O(k) since there's also a constant upper bound on the number of occurrences of each integer, namely 2.

    0 讨论(0)
  • 2020-12-16 05:13

    In the case where the entries are bounded by the length of the array, then you can check out Find any one of multiple possible repeated integers in a list and the O(N) time and O(1) space solution.

    The generalization you mention is discussed in this follow up question: Algorithm to find a repeated number in a list that may contain any number of repeats and the O(n log^2 n) time and O(1) space solution.

    0 讨论(0)
提交回复
热议问题