Count ways to remove objects such that exactly M equidistant objects remain
Given an integer N, representing objects placed adjacent to each other, the task is to count the number of ways to remove objects such that after their removal, exactly M objects are left and the distance between each adjacent object is equal.
Input: N = 5, M = 3
Let the initial arrangement be A1 A2 A3 A4 A5.
The following arrangements are possible:
- A1 A2 A3 _ _
- _ A2 A3 A4 _
- _ _ A3 A4 A5
- A1_ A3_ A5
Therefore, the total count of possible arrangements is 4.
Input: N = 2, M = 1
Approach: The idea is based on the observation that an arrangement of M objects with D adjacent spaces takes (M + (M – 1) * D) length, say L. For this arrangement, there are (N – L + 1) options. Therefore, the idea is to iterate over D from 0 till L ≤ N and find the number of ways accordingly.
Follow the steps below to solve the problem:
- If the value of M is 1, then the number of possible arrangements is N. Therefore, print the value of N.
- Otherwise, perform the following steps:
- Initialize two variables, say ans to 0, to store the total number of required arrangements.
- Iterate a loop using a variable D. Perform the following steps:
- Store the total length required for the current value of D in a variable, say L as M + (M – 1) * D.
- If the value of L is greater than N, then break out of the loop.
- Otherwise, update the number of arrangements by adding the value (N – L + 1) to the variable ans.
- After completing the above steps, print the value of ans as the total number of arrangements.
Below is the implementation of the above approach.
Time Complexity: O(N)
Auxiliary Space: O(1)