ABC interview question

It was leetcode medium - hard