DDSA
Advertisement

1018. Binary Prefix Divisible By 5

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

Approach

Maintain running value mod 5; only the last 3 bits matter since 2^3 mod 5 cycles.

1018.cs
C#
// Approach: Maintain running value mod 5; only the last 3 bits matter since 2^3 mod 5 cycles.
// Time: O(n) Space: O(1)

public class Solution
{
    public IList<bool> PrefixesDivBy5(int[] nums)
    {
        IList<bool> ans = new List<bool>();
        int curr = 0;

        foreach (int num in nums)
        {
            curr = (curr * 2 + num) % 5;
            ans.Add(curr % 5 == 0);
        }

        return ans;
    }
}
Advertisement
Was this solution helpful?