DISCLAIMER: This is NOT a homework and neither I'm asking you to provide working code for this question.
Hi folks, I'm studying a problem with a particular property that allows to solve it in linear time with O(1) additional memory.
Here is the problem:
Given an array "A" of size N with elements ranging from 1 to N, find the duplicated element in linear time with constant space of additional memory.
In case of more than one duplicated pair, return the one that the second element has the lower index.
If there are no duplicates, return -1.
Examples:
- A = [1, 2, 3, 4] --> -1
- A = [1, 1, 3] --> 1
- A = [3, 3, 1, 1, 5] --> 1
This problem is very easy to solve using a map and counting frequencies, but I'm curious about using only O(1) of extra memory...
I know that the sum of 1 + 2 + 3 + ... + N = (N*(N + 1)) / 2
and this fact may help with this problem but I really can't see how can I do better than my existing solution.
If anyone could shed some light on this for me, it would be awesome!