Implemented the algorithm (not optimized or linted)