3 ms·
since it's java, you have access to a Set. add each node to the set if it is not present, O(1). A bit more aggressive, check System.Runtime.heapSize() calculate
by jfoutz 7y ago
since it's java, you have access to a Set. add each node to the set if it is not present, O(1).
A bit more aggressive, check System.Runtime.heapSize() calculate how many nodes can fit in the heap, and subtract 1 for each element visited. Still O(1)
With lower level access, recognize that pointers are always powers of 2, so go ahead and tag that pointer (p = p | 1, if *p & 1, it's a cycle.) you'll build up a stack, and have to fix the tagged pointers, but also O(1).
I dunno. the double advance is a cute trick, but if the fast moving pointer doesn't do the check, you can easily spin into an infinite loop.
It's not a _hard_ problem. You just have to keep your wits about you. Lots of ways to solve it.
- saagarjha 7y ago> add each node to the set if it is not present, O(1). Not in space complexity. > A bit more aggressive, check System.Runtime.heapSize() calculate how many nodes can fit in the heap, and subtract 1 for each element visited. This one will take quite a while… > recognize that pointers are always powers of 2, so go ahead and tag that pointer They're not always, and this is also technically uses extra space.