Konrad Group Interview Question

Do this question in javascript (leetcode type of question, try to make it efficient)