HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Finding duplicate in immutable array in linear time and constant space

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
linearspaceconstantarrayduplicatetimeimmutablefindingand

Problem

We have a array of $N$+1 integers. The integers range from 1 to $N$. The array contains at least one duplicate. Our goal is to find one of the duplicate entries. We have the constraint that we cannot modify the input array. Is there any solution to this problem which has $O(N)$ time complexity and $O(1)$ space complexity?

Solution

Let us denote the array by $a_1,\ldots,a_{n+1}$. Define a function from $\{1,\ldots,n+1\}$ to itself as follows: $f(i) = a_i$. The graph of the function is a directed graph in which each node has outdegree 1. Since $n+1$ has indegree 0, the connected component of $n+1$ has a node with indegree 2, which corresponds to a duplicate entry. This node can be found using a cycle detection algorithm in linear time and constant space.

Context

StackExchange Computer Science Q#95379, answer score: 6

Revisions (0)

No revisions yet.