#1894

Find the Student that Will Replace the Chalk

Medium
ArrayBinary SearchSimulationPrefix SumPrefix SumSimulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of simulating each student's turn, we can calculate the total chalk needed for one full round of students and then determine how many complete rounds can be done with the available chalk. This reduces unnecessary iterations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the total chalk needed for one complete round by summing all elements in the chalk array.
  2. 2Step 2: If `k` is greater than or equal to the total chalk, reduce `k` by the total chalk until `k` is less than the total chalk.
  3. 3Step 3: Iterate through the chalk array to find the first student where `k` is less than chalk[i] and return that index.
solution.py9 lines
1chalk = [5, 1, 5]
2k = 22
3total_chalk = sum(chalk)
4if k >= total_chalk:
5    k %= total_chalk
6for i in range(len(chalk)):
7    if k < chalk[i]:
8        print(i)
9        break

Complexity note: The time complexity is O(n) because we only need to sum the chalk array once and then iterate through it again to find the student, making it efficient.

  • 1Understanding the total chalk usage helps in reducing unnecessary iterations.
  • 2Using modulo operation allows us to efficiently determine remaining chalk after complete rounds.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.