Tech Mahindra interview question

Asked for to do code for given scenario.