algoadvance

Leetcode 2928. Distribute Candies Among Children I

Problem Statement

You are given an integer array candies where each candies[i] represents the number of candies of the i-th type you have. You are also given an integer k representing the number of children. You need to determine whether it’s possible to distribute all candies such that each child gets exactly the same number of candies of each type. If it is possible, return true; otherwise, return false.

Clarifying Questions

  1. What should we do if the sum of candies is not divisible by k?
    • If the sum of candies for each type is not divisible by k, then it is impossible to distribute them equally, and we should return false.
  2. Are there any constraints on the size of the candies array or the values within it?
    • This problem might assume typical array size and value constraints as found in competitive programming contests, so we’ll consider reasonable limits (e.g., 1 ≤ candies.length ≤ 10^4, 1 ≤ candies[i] ≤ 10^7.)

Strategy

  1. Check Divisibility:
    • For each candy type, check if the number of candies of that type is divisible by k.
    • If any candy type count is not divisible by k, return false.
  2. Return True if All Types Are Divisible:
    • If all candy type counts are divisible by k, then return true because it is possible to distribute the candies equally among the children.

Code

#include <vector>

class Solution {
public:
    bool canDistributeCandies(std::vector<int>& candies, int k) {
        for (int candyCount : candies) {
            if (candyCount % k != 0) {
                return false;
            }
        }
        return true;
    }
};

Time Complexity

This solution efficiently checks the divisibility condition for each type of candy, ensuring the problem constraints and requirements are met.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI