educative.io

Find Duplicate Number in O(1) space without modifying the array - why the extra work?

In the O(1) solution without modifying the array, why can’t we simply return the slow (or fast) value when they meet? I don’t see what the point is in trying to find the length of the cycle and then its starting point.

Did/does anyone else have the same question? Please clarify.

2 Likes

Exactly, we tried to the LinkedList approach but there we needed to find the node.
But here just the value. I think we can safely skip it.

The approach in happy numbers was similar.

I think it’s unnecessary.

Also I don’t get what consists of a cycle here? It’s an array and there are no pointers to point back, right?

Cheers

Actually it won’t work for this case

  const input4 = [4, 4, 1, 4, 3];
  const expected4= 4;

Hi there,
So, we knew that we have a cycle because if you trace the number then your are going inside an infinite loop.
take this as an example
[4, x, x, 1]
if you’re starting from index 0, can you tell me what’s going to happen?

Now, whenever you have limited numbers [1 -> n] and you had to do in place operations, you should think of (slow & fast pointers).

@Gaurav7 thank you for the example, it convened me that we always need to find the beginning of the cycle, but I also would say, that educative has a weird way of doing so.

Cheers