Skip to content

ORIGINAL CODING QUESTION

Segments with divisible totals

Given signed daily point changes and a positive k, count the nonempty contiguous segments whose total is a multiple of k. A total of 0 counts, and negative totals such as -k also count.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n values, then k. Print the segment count.

Constraints

1 ≤ n ≤ 200; -1000 ≤ value ≤ 1000; 1 ≤ k ≤ 1000.

Example 1

Input

4
3 1 2 3
3

Output

6

The segments [3], [1 2], [3], [3 1 2], [1 2 3] and [3 1 2 3] all have totals divisible by 3.

Example 2

Input

3
1 1 1
5

Output

0

No total among 1, 2 and 3 is a multiple of 5.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

A segment total is the difference of two prefix totals.

Hint 2

Two prefixes with the same remainder modulo k bound a segment divisible by k.

Hint 3

Count remainders of prefix totals in a map, starting with remainder 0 seen once; normalise negative remainders with ((p % k) + k) % k and add the earlier count for each new prefix.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →