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.
1def chalkReplacer(chalk, k):
2 total_chalk = sum(chalk)
3 k %= total_chalk
4 for i, c in enumerate(chalk):
5 if k < c:
6 return i
7 k -= c
8 return -1
The Python solution first calculates the total chalk used per cycle, then updates k to be k modulo this total. It then iterates through the students to identify the first one that does not have enough chalk for their problem, thereby having their index returned.
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 the Java implementation, a prefix sum array is created to help parse through possible chalk usages quickly. Binary search expedites finding the precise index where the replacement should occur.