Code for leetcode problem