1894. Find the Student that Will Replace the Chalk
UnknownView on LeetCode
Time: O(n)
Space: O(1)
Problem Overview
Find the Student that Will Replace the Chalk (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Binary Search pattern in coding interviews. Sum all chalk; reduce k mod total sum; linear scan to find who runs out.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Sum all chalk; reduce k mod total sum; linear scan to find who runs out.
Related patterns: Array, Binary Search, Prefix Sum
1894.cs
C#
// Approach: Sum all chalk; reduce k mod total sum; linear scan to find who runs out.
// Time: O(n) Space: O(1)
public class Solution
{
public int ChalkReplacer(int[] chalk, int k)
{
long k1 = k;
long sum = 0;
for (int i = 0; i < chalk.Length; i++)
sum += chalk[i];
k1 %= sum;
if (k1 == 0)
return 0;
for (int i = 0; i < chalk.Length; ++i)
{
k1 -= chalk[i];
if (k1 < 0)
return i;
}
throw new ArgumentException();
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)