Sponsored
Sponsored
This approach takes advantage of the cyclical nature of the problem. Initially, the teacher provides problems to each student in sequence. We calculate the total sum of chalk required for one full pass through the students. If k is greater than this sum, it implies that the whole cycle can be repeated multiple times. Therefore, we reduce k by this sum repeatedly to get only the relevant chalk pieces needed as a remainder, then find the student who will run out of chalk.
Time Complexity: O(n), where n is the number of students since we iterate over the chalk array twice, once to find the total chalk and then to find the replacer.
Space Complexity: O(1) as we use only a constant amount of extra space.
1#include <vector>
2using namespace std;
3
4int chalkReplacer(vector<int>& chalk, int k) {
5 long long total_chalk = 0;
6 for (int c : chalk) {
7 total_chalk += c;
8 }
9 k %= total_chalk;
10 for (int i = 0; i < chalk.size(); ++i) {
11 if (k < chalk[i]) return i;
12 k -= chalk[i];
13 }
14 return -1;
15}
In C++, the solution uses a long long
data type for total_chalk to handle large sums safely. The algorithm first calculates the sum of chalk in one cycle, uses modulo to reduce k, and iterates over the students until it finds the one who needs to replace the chalk.
This approach accumulates a prefix sum of chalk costs as an extra preprocessing step. With prefix sums, one can quickly determine the range that k
falls into using binary search, leading to the index of the student who will run out of chalk.
Time Complexity: O(n log n) due to sorting and binary search.
Space Complexity: O(n) for the prefix sums array.
1import
In this Python solution, the prefix sum of the chalk array allows a binary search to find the appropriate student when a sufficient chalk cycle is calculated out of k using modulo. Binary search helps efficiently navigate the prefix sums.