You can clear any question in python, I will try my best to explain you the logic. For the people, working in other languages, I will explain the logic and then will convert the code to the specified language.