Pergunta de entrevista da empresa SAP

LeetCode question (I think it was a leetcode medium)