Check if two piles of coins can be emptied by repeatedly removing 2 coins from a pile and 1 coin from the other
Given two piles of coins consisting of N and M coins, the task is to check if both the piles can be emptied simultaneously by repeatedly removing 2 coins from one 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 Output: Yes Explanation: 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 Output: No
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) // since no loop is used the algorithm takes constant time for all the operations
Auxiliary Space: O(1) // since no extra array is used the space taken by the algorithm is constant
Please Login to comment...