30/39
Part 6 of 7 · The worked exampleLearn

The copy is a little faster in Python, and the in-place version saves the memory

One walk to the middle, two reverses of n/2 nodes and one compare: O(n) time and O(1) extra memory.

Measured on a 1,000,000-node list that reads the same both ways, 0 up to 499,999 and back down, median of 5 runs:

  • in place: 56.6 ms, with no measurable memory
  • the copy: 50.1 ms, with a peak of 16,448,812 bytes

So in Python the copy is a little faster, and it's the right answer at work unless memory is tight. Say that too.

The in-place version has one more catch to name: while it runs, the list is cut short at the middle, so nothing else may read it at the same time.