Find the Student that Will Replace the Chalk - Problem

There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with student number 0, then student number 1, and so on until reaching student number n - 1. After that, the teacher will restart the process, starting with student number 0 again.

You are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then student number i will be asked to replace the chalk.

Return the index of the student that will replace the chalk pieces.

Input & Output

Example 1 — Basic Case
$ Input: chalk = [5,1,5], k = 22
Output: 0
💡 Note: Students use chalk in cycles: Round 1: 5+1+5=11 (k=22→11), Round 2: 5+1+5=11 (k=11→0). In Round 3, student 0 needs 5 chalk but only 0 remains, so student 0 replaces chalk.
Example 2 — Replace in Middle
$ Input: chalk = [3,4,1,2], k = 25
Output: 1
💡 Note: Total per round = 10. After k%10 = 5 remaining: Student 0 uses 3 (remaining=2), Student 1 needs 4 but only 2 available, so student 1 replaces chalk.
Example 3 — Exact Match
$ Input: chalk = [1,1,1], k = 3
Output: 0
💡 Note: One complete round uses exactly 3 chalk. After that, k=0 and student 0 needs 1 chalk but none available, so student 0 replaces.

Constraints

  • n == chalk.length
  • 1 ≤ n ≤ 105
  • 1 ≤ chalk[i] ≤ 105
  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Find the Student that Will Replace the Chalk INPUT Students (0 to n-1): S0 5 chalk S1 1 chalk S2 5 chalk chalk[] array: 5 1 5 [0] [1] [2] Initial chalk pieces: k = 22 ALGORITHM STEPS 1 Calculate Total Sum sum = 5+1+5 = 11 2 Use Modulo k = 22 % 11 = 0 3 Find Student Check: k < chalk[i]? 4 Return Index 0 < 5? Yes! Return 0 Simulation Trace: Round Student Chalk Left 1 0,1,2 5,1,5 22-11=11 2 0,1,2 5,1,5 11-11=0 3 0 needs 5 0 < 5 Student 0 must replace! FINAL RESULT After 2 complete rounds: S0 REPLACE! S1 S2 Output: 0 Student at index 0 will replace the chalk OK Key Insight: Use modulo operation to skip complete rounds! Instead of simulating each round, calculate k % sum(chalk) to find remaining chalk after all complete rounds. Time: O(n), Space: O(1) - Avoids TLE for large k values! TutorialsPoint - Find the Student that Will Replace the Chalk | Optimal Solution
Asked in
Amazon 15 Google 8 Microsoft 5
32.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen