educative.io

The example & the code looks incorrect; a simpler solution exists

The second example with k=8 looks incorrect.

Let’s rotate the list for 8 iterations manually:

1 → 2 → 3 → 4 → 5

  1. 2 → 3 → 4 → 5 → 1
  2. 3 → 4 → 5 → 1 → 2
  3. 4 → 5 → 1 → 2 → 3
  4. 5 → 1 → 2 → 3 → 4
  5. 1 → 2 → 3 → 4 → 5
  6. 2 → 3 → 4 → 5 → 1
  7. 3 → 4 → 5 → 1 → 2
  8. 4 → 5 → 1 → 2 → 3

So finally we got 4 → 5 → 1 → 2 → 3, not 3 → 4 → 5 → 1 → 2 as the article states.

To achieve that, why can’t we just:

  1. Find the tail of the list

  2. Move the nodes one by one from the head to the tail of the list, updating the counter?

    const rotate = function (head, rotations) {
    if (!head || !head.next) return head;

    let tail = head;

    while (tail.next) {
    tail = tail.next;
    }

    for (let i = 0; i < rotations; i++) {
    tail.next = head;
    tail = head;
    head = head.next;
    tail.next = null;
    }

    return head;
    };


Type your question above this line.

Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/5497500834201600

Hi there,
You are rotating from the left side, but the example given in the lesson is rotating from the right.
The example and code given in the lesson are correct both.