Skip to content

1894. Find the Student that Will Replace the Chalk 👍

  • Time: $O(n)$
  • Space: $O(1)$;
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int chalkReplacer(vector<int>& chalk, int k) {
    k %= accumulate(chalk.begin(), chalk.end(), 0L);
    if (k == 0)
      return 0;

    for (int i = 0; i < chalk.size(); ++i) {
      k -= chalk[i];
      if (k < 0)
        return i;
    }

    throw;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int chalkReplacer(int[] chalk, int k) {
    k %= Arrays.stream(chalk).asLongStream().sum();
    if (k == 0)
      return 0;

    for (int i = 0; i < chalk.length; ++i) {
      k -= chalk[i];
      if (k < 0)
        return i;
    }

    throw new IllegalArgumentException();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def chalkReplacer(self, chalk: list[int], k: int) -> int:
    k %= sum(chalk)
    if k == 0:
      return 0

    for i, c in enumerate(chalk):
      k -= c
      if k < 0:
        return i