Implementation correctness verified on sample cases in data/ folder.