DDSA
Advertisement

1894. Find the Student that Will Replace the Chalk

Time: O(n)
Space: O(1)

Approach

Sum all chalk; reduce k mod total sum; linear scan to find who runs out.

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();
    }
}
Advertisement
Was this solution helpful?