Target Interview Question

to write logic gor given problem