Find the Student That Will Replace the Chalk

medium prefix sum binary search

Problem

Students 0..n−1 in a circle consume chalk[i] units of chalk on their turn. With k units of chalk, who will be next to need a replacement?

Inputchalk = [5,1,5], k = 22
Output0
Sum=11; 22 mod 11 = 0; student 0 needs 5 but only 0 left → answer 0.

def chalk_replacer(chalk, k):
    s = sum(chalk)
    k %= s
    for i, c in enumerate(chalk):
        if k < c: return i
        k -= c
    return -1  # unreachable
function chalkReplacer(chalk, k) {
  let s = 0;
  for (const c of chalk) s += c;
  k %= s;
  for (let i = 0; i < chalk.length; i++) {
    if (k < chalk[i]) return i;
    k -= chalk[i];
  }
  return -1;
}
class Solution {
    public int chalkReplacer(int[] chalk, int k) {
        long s = 0;
        for (int c : chalk) s += c;
        long rem = k % s;
        for (int i = 0; i < chalk.length; i++) {
            if (rem < chalk[i]) return i;
            rem -= chalk[i];
        }
        return -1;
    }
}
int chalkReplacer(vector<int>& chalk, int k) {
    long s = 0;
    for (int c : chalk) s += c;
    long rem = k % s;
    for (int i = 0; i < (int)chalk.size(); i++) {
        if (rem < chalk[i]) return i;
        rem -= chalk[i];
    }
    return -1;
}
Time: O(n) Space: O(1)