Reference from LeetCode solution, need to review