final version, passed leetcode tests