educative.io

Solution Review: Problem Challenge 1 - Grokking the Coding Interview:

The solution has a bug. The question states

If, in the end, you are left with a sub-list with less than ‘k’ elements, reverse it too.

The solution provided does not account for that.

When the input is 1-2-3-4-5-6-7-8-9-10-11, k = 3
The output should be: 3-2-1-4-5-6-9-8-7-11-10

The output that the solution provides is :

Blockquote Nodes of reversed LinkedList are: 3 2 1 4 5 6 9 8 7 10 11

Hello @Akash_Ramachandran ,
So the code is supposed to reverse k elements and then skip k elements which is why in your case it’s not reversing 10 11. So if you try the same code for numbers from 1 to 14 it will work. The reason is that after the code skips k elements it finds a sublist of less than k elements but it reverses it which is what’s required of the code. So if you reverse 1 2 3 4 5 6 7 8 9 10 11 12 13 14 with k =3 the reversed list comes out to be 3 2 1 4 5 6 9 8 7 10 11 12 14 13.
Hope this answers your query

So what is the meaning of “If, in the end, you are left with a sub-list with less than ‘k’ elements, reverse it too.” ?
Does it mean we still have to skip k elements but after skipping if there are less than k elements left then just reverse the less than k elements.
It does not mean that if after reversing k elements, the list has k-x elements left then dont skip them but reverse those k-x elements as well.

Correct?


Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Solution Review: Problem Challenge 1 - Grokking the Coding Interview: Patterns for Coding Questions

Hi @bee1
Yes, it’s correct.