I have explained the solution in scala with complete illustration. Hope it would help. Please also subscribe !