Question from an exam:
- Given a linked list with unknown size
n, where3dividesn, how can we print the middle group of elements (e.g. between 1/3 and 2/3) of the linked list, using only3pointers, without counters ? - How can we do that with only two pointers?
Remark: we cannot go left, only right!
Couldn’t come up with an answer that doesn’t involve counters, any suggestions?
Try to imagine the pointers as pickup heads on a tape. You start them all at the beginning, but then you move them at different speeds (hint, those speeds are multiple of fractions of 1/3 to each other). Now think about where the slower pointers are, when the fastest moving pointer has reached the end.
Now how to make the pointers move like that, even if you can only increment and can’t to multiplication or division. Think about how a mechanical counter carries over its digits.
And how to do it with only two pointers: Think about what you can do after you’ve reached the starting position: Place the fast pointer at the position of the slow pointer and repeat.