Find the Student that Will Replace the Chalk — LeetCode 1894 Python Solution

MediumArrayBinary SearchPrefix SumSimulation
Problem
#1894
Pattern
Prefix Sum
Reading time
2 min

The problem

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

Example

Input
chalk = [5,1,5], k = 22
Output
0
Explanation
The students go in turns as follows:

Python solution

Python
class Solution:
    def chalkReplacer(self, chalk: List[int], k: int) -> int:
        s = sum(chalk)
        k %= s
        for i, x in enumerate(chalk):
            if k < x:
                return i
            k -= x

Complexity

MeasureComplexity
TimeO(n), where n is the number of students
SpaceO(1) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1894. Find the Student that Will Replace the Chalk is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1894. Find the Student that Will Replace the Chalk?
LeetCode 1894. Find the Student that Will Replace the Chalk is rated Medium on LeetCode.
What is the time complexity of LeetCode 1894. Find the Student that Will Replace the Chalk?
The Python solution on this page runs in O(n), where n is the number of students.
What is the space complexity of LeetCode 1894. Find the Student that Will Replace the Chalk?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1894. Find the Student that Will Replace the Chalk cover?
LeetCode 1894. Find the Student that Will Replace the Chalk is tagged Array, Binary Search, Prefix Sum and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview