Skip to content

ORIGINAL CODING QUESTION

Count target-sum segments

Count nonempty contiguous segments whose sum equals the target.

Open practice workspace

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

Input and output

n, then n signed values, then target. Print the segment count.

Constraints

1 ≤ n ≤ 200; -100 ≤ value ≤ 100. Inputs contain exactly the stated values.

Example 1

Input

3 1 1 1 2

Output

2

Two adjacent pairs sum to 2.

Example 2

Input

3 0 0 0 0

Output

6

All six nonempty segments qualify.

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

Negative numbers prevent a simple monotonic sliding window.

Hint 2

Two prefix sums with the right difference define a valid segment.

Hint 3

Seed prefix sum zero with frequency one.

Practice this question

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

Open practice workspaceBrowse the question library →