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.
1function chalkReplacer(chalk, k) {
2 const total = chalk.reduce((acc, c) => acc + c, 0);
3 k %= total;
4 for (let i = 0; i < chalk.length; i++) {
5 if (k < chalk[i]) return i;
6 k -= chalk[i];
7 }
8 return -1;
9}
The JavaScript solution employs reduce to compute the total sum of chalk and leverages the modulo operator to find k
's effective remaining chalk, then iterates through the students to identify who will need to replace it.
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.
1function
The JavaScript solution employs prefix sums to allow binary search for the index exceeding the reduced chalk pieces k
. This method leverages JavaScript's native array handling and math functions.