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
Student Chalk Distribution ProblemInput: chalk = [5,1,5], k = 22515Student 0Student 1Student 2Total chalk: k = 2222 piecesRound 1: 5 + 1 + 5 = 11 used (11 remaining)Round 2: 5 + 1 + 5 = 11 used (0 remaining)Round 3: Student 0 needs 5 chalk, but 0 < 5 ❌REPLACEOutput: 0 (Student 0 replaces chalk)
Understanding the Visualization
1
Input
Array of chalk needed per student, total chalk k
2
Process
Students take chalk in cycles until insufficient chalk remains
3
Output
Index of student who needs to replace chalk
Key Takeaway
🎯 Key Insight: Use modular arithmetic to skip complete cycles and only simulate the final partial round
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