Yandex interview question

Leetcode : easy and medium