Given a list, write a function to reverse every K element when k is an input to the function.
Input: [1;2;3;4;5;6;7;8] and k = 3 Output:[3;2;1;6;5;4;8.7]
In case of an empty list, it just returns .
Solution with F#:
From the problem definition, the signature of
reverseK is quite trivial:
In order to implement this function, we have used
int list list, which in essence, acts as an accumulator to store the intermediate results. In addition, for every Kth element, we are creating a new list (Line 5) and resetting counter
i to zero for further processing. In a sense, we are splitting the list in K chunks and reversing it.
These results are afterwards reversed and flattened using
List.collect as shown in Line 13 and in Line 14.
Complexity of the above algorithm: O(n).
Solution with c:
An implementation of this problem in C is available here.