Pensees interview question

np-medium question from leet code