Given two piles of coins consisting of N and M number of coins, the task is to check if both the piles can be emptied simultaneously by repeatedly removing 2 coins from a pile and 1 coin from the other pile. If both the piles can be made empty, then print “Yes”. Otherwise, print “No”.
Input: N = 1, M = 2
Remove 1 coin from 1st pile and 2 coins from the other pile. Therefore, the number of coins in both the piles is 0.
Input: N = 2, M = 2
Approach: The given problem can be solved based on the following observations:
- There are two ways to remove coins from piles, i.e. either remove 2 coins from pile 1 and 1 coin from pile 2 or 1 coin from pile 1 and 2 coins from pile 2.
- Let X be the number of moves made for the first removal and Y be the number of moves made for the second removal, then the remaining number of coins in the two piles are (N – 2*X – Y) and (M – 2*Y – X) respectively.
- After performing (X + Y) moves, the piles must be emptied i.e.,
(N – 2*X – Y) = 0 and (M – 2*Y – X) = 0
Rearranging terms in the above equations generates the equations:
N = 2*X + Y and M = 2*Y + X
- The total number of coins in both piles is (N + M) = (2*X + Y) + (X + 2*Y) = 3(X + Y).
- Therefore, to make both the piles empty, below are the conditions:
- The sum of the coins in both piles should be a multiple of 3.
- The maximum of N and M must less than twice the minimum of N and M as one whole pile will become empty and some coins will still be left in another one. Therefore, the size of the larger pile should not be more than twice the size of the smaller pile.
Therefore, the idea is to check if the sum of total number of coins is a multiple of 3 and the maximum number of coins is at most twice the minimum number of coins, then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.