leetcode optimal solution of C++ and Python