Reversing List in groups of given size with F#

Problem Statement:

Given a list, write a function to reverse every K element when k is an input to the function.

Example:

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:

val reverseK : x:int list -> k:int -> int list
view raw gistfile1.fs hosted with ❤ by GitHub

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.

let rec reverseK (x:int list) (k:int):int list=
let rec reverseKAux (x:int list) (acc:int list list) (i:int)=
match x with
| [] -> acc
| xhd::xtl when k=i ->
reverseKAux (xhd::xtl) ([]::acc) 0
| xhd::xtl ->
match acc with
| h::t -> reverseKAux xtl ((xhd::h)::t) (i+1)
| [] -> reverseKAux xtl ([xhd]::[]) (i+1)
in
reverseKAux x [[]] 0
|> List.rev
|> List.collect (fun x -> x)
view raw gistfile1.fs hosted with ❤ by GitHub

These results are afterwards reversed and flattened using List.rev and List.collect as shown in Line 13 and in Line 14.

Algorithmic Complexity:

Complexity of the above algorithm: O(n).

Solution with c:

An implementation of this problem in C is available here.

Output:

> reverseK [1;2;3;4;5;6;7;8] 3;;
val it : int list = [3; 2; 1; 6; 5; 4; 8; 7]
> reverseK [] 3;;
val it : int list = []
view raw gistfile1.fs hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s