Sometimes complicated algorithms are really easy to be written down. The current problem is solved in 6 lines of code (from line 5 to line 11), but it you need to put effort to understand how the algorithm works and what are…