Find the Student that Will Replace the Chalk LeetCode solution in C++

1
class Solution {
2
public:
3
// T(n) = O(n) S(n) = O(1)
4
int chalkReplacer(vector<int> &chalk, int k) {
5
// Size of the vector
6
int n = chalk.size();
7
// Store the sum of the elements in the vector
8
long sum = 0;
9
// Calculate the sum of the elements
10
for (int n : chalk) sum += n;
11
// Update k as the remainder of the sum
12
// to make sure that the while loop
13
// will traverse the vector at most 1 time
14
k = k % sum;
15
// Start from the initial value in the array
16
int idx = 0;
17
// While the next student has enough chalk
18
while (k >= chalk[idx]) {
19
// Decrease the remaining chalk
20
k -= chalk[idx];
21
// Increase the index
22
idx = (idx + 1) % n;
23
}
24
// Return the index of the student without
25
// enough chalk
26
return idx;
27
}
28
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0