VOOZH about

URL: https://www.geeksforgeeks.org/dsa/distribute-n-candies-among-k-people/

⇱ Distribute N candies among K people - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Distribute N candies among K people

Last Updated : 4 Mar, 2025

Given N candies and K people. In the first turn, the first person gets 1 candy, the second gets 2 candies, and so on till K people. In the next turn, the first person gets K+1 candies, the second person gets k+2 candies, and so on. If the number of candies is less than the required number of candies at every turn, then the person receives the remaining number of candies. 

The task is to find the total number of candies every person has at the end. 

Examples:

Input: N = 7, K = 4 
Output: 1 2 3 1 
Explanation: In ,the first turn, the fourth person has to be given 4 candies, but there is 
only 1 left, hence he takes one only.

Input: N = 10, K = 3 
Output: 5 2 3 
Explanation: At the second turn first one receives 4 and then we have no more candies left.

[Naive Approach] Progressive Turnwise Distribution - O(N) Time and O(K) Space

We can solve this problem by distributing candies in a cyclic manner. Each person receives candies incrementally: the first person gets 1, the second gets 2, and so on up to K people. In the next cycle, the first person receives K+1, the second gets K+2, and this continues until all candies are distributed.


Output
5 2 3 

[Better Approach] Using formulas - O(turns + K) Time and O(K) Space

Start with total candies NNN, KKK people, and a turn counter. Distribute candies in increasing order (1, 2, ..., K) while decreasing the remaining candies. After each full cycle, update the turn count and continue. If a full cycle isn’t possible, distribute the remaining candies individually. Finally, use the arithmetic progression formula for efficient distribution and output the result.


Output
5 2 3 

[Expected Approach] Using the binary search - O(logn + K) Time + O(K) Space

Use binary search to find the maximum number of complete turns, then distribute leftover candies from the last incomplete turn using a loop. Finally, apply the arithmetic progression formula to efficiently allocate candies for complete turns.


Output
5 2 3 


Comment
Article Tags: