YANDEX interview question

One distance apart Leetcode 161