Alternative solution tested on leetcode