InternDoor

Flip the list in groups

Hardlinked lists · pointers

Reported in interviews at (where)

You are given the head of a linked list and a number k. Cut the list, from the front, into groups of k nodes and reverse the order of the nodes inside each group. A group at the end with fewer than k nodes stays as it is.

Return the head of the changed list. Move the nodes themselves: do not just change their values.

Example 1
Input
head = [2,4,6,8,10,12,14,16]
k = 3
Output
[6,4,2,12,10,8,14,16]

Two full groups of 3 flip; 14, 16 are only 2 nodes and stay.

Example 2
Input
head = [5,1,9]
k = 1
Output
[5,1,9]

Groups of one do not change.

Limits

  • 1 <= number of nodes <= 5000
  • 1 <= k <= number of nodes
  • -1000 <= Node.val <= 1000

Hints

Hint 1

Before flipping a group, check that k nodes are left.

Hint 2

Keep a pointer to the node just before the group, so the flipped group can be joined back in.

Where this was reported

Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.

Run your code to check it on the examples. Submit runs every hidden test.

Ready for the real one?

Engineering internships and entry-level jobs in India, newest first.