I know there are related questions on stackoverflow but can\'t seem to find a good solution(if at all possible).
Here is scenario 1: