Find the Student that Will Replace the Chalk - Problem

Imagine a classroom where students take turns solving problems in a circular fashion. There are n students numbered from 0 to n-1, and they sit in a circle. The teacher starts with student 0, then moves to student 1, and so on. After reaching student n-1, the teacher wraps around back to student 0.

Each student needs a certain amount of chalk pieces to solve their assigned problem. You're given an array chalk where chalk[i] represents how many pieces student i needs. Initially, there are k chalk pieces available.

Here's the catch: if when it's a student's turn, there aren't enough chalk pieces left for them to complete their problem, that student must go replace the chalk instead of solving the problem.

Goal: Determine which student will be the one asked to replace the chalk.

Example: If chalk = [5,1,5] and k = 11, student 0 uses 5 pieces (6 left), student 1 uses 1 piece (5 left), student 2 uses 5 pieces (0 left), then when we cycle back to student 0, there are 0 pieces left but they need 5, so student 0 replaces the chalk.

Input & Output

example_1.py โ€” Basic Case
$ Input: chalk = [5,1,5], k = 22
โ€บ Output: 0
๐Ÿ’ก Note: Total chalk per round = 5+1+5 = 11. After 2 complete rounds (22 รท 11 = 2), we have 0 chalk left. Student 0 needs 5 chalk but there are 0 pieces available, so student 0 must replace the chalk.
example_2.py โ€” Partial Round
$ Input: chalk = [3,4,1,2], k = 25
โ€บ Output: 1
๐Ÿ’ก Note: Total chalk per round = 10. After 2 complete rounds, we have 25 % 10 = 5 chalk left. Student 0 uses 3 (2 left), then student 1 needs 4 but only 2 available, so student 1 replaces the chalk.
example_3.py โ€” Single Student Edge Case
$ Input: chalk = [1], k = 1000000
โ€บ Output: 0
๐Ÿ’ก Note: Only one student who needs 1 chalk. After 1000000 complete rounds, 0 chalk remains. Student 0 needs 1 but there are 0 pieces, so student 0 replaces the chalk.

Constraints

  • 1 โ‰ค chalk.length โ‰ค 105
  • 1 โ‰ค chalk[i] โ‰ค 105
  • 1 โ‰ค k โ‰ค 109
  • All array elements are positive integers

Visualization

Tap to expand
Students in Circle0needs 51needs 12needs 5Round Total = 115 + 1 + 5 = 11 chalkSkip Rounds22 % 11 = 0 remaining๐ŸŽฏ Result: Student 0 can't get 5 chalk from 0 remaining
Understanding the Visualization
1
Calculate Round Total
Add up all chalk requirements for one complete round
2
Skip Complete Rounds
Use modular arithmetic to jump to the final partial round
3
Find the Answer
Simulate only the final round to find who can't get enough chalk
Key Takeaway
๐ŸŽฏ Key Insight: Use modular arithmetic to avoid simulating every single turn, making the solution efficient for large k values!
Asked in
Amazon 45 Google 30 Microsoft 25 Meta 20
42.3K Views
Medium Frequency
~15 min Avg. Time
1.2K 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