Leetcode Problem:
Summary
- Find the index of the student who will replace the chalk pieces
Approach
- The solution uses the modulo operator to find the remaining chalk pieces after each student's turn
- It then iterates through the chalk array to find the student who will run out of chalk first.
Complexity
- O(n) where n is the number of students
Explain
- The solution works by first calculating the total amount of chalk available
- It then uses the modulo operator to find the remaining chalk pieces after each student's turn
- The student who will run out of chalk first is the one whose index is returned
- This approach ensures that the student who will replace the chalk is found efficiently, even for large inputs.
Solution Code:
class Solution {
public:
int chalkReplacer(vector& chalk, int k) {
long long sum = 0;
for(int i = 0 ; i < chalk.size(); i++){
sum += chalk[i];
}
k = k % sum;
for(int i = 0 ; i < chalk.size(); i++){
k -= chalk[i];
if (k < 0) return i;
}
return 0;
}
};