Implemented a solution in scala