Question bank › Prefix Sum
Dsa Prefix Sum Medium

Matching-End Sum

Find the length of the longest subarray whose elements sum to exactly S, with the additional constraint that the first and last elements of the subarray must be equal. Input Format: The first line contains N and S. The second line contains N integers. Output Format: A single integer representing the length of the longest such subarray. If none exist, output 0. Example: Input: 5 4 2 1 2 2 2 Output: 2 Explanation: The subarray [2, 2] at the end has sum 4 and starts/ends with 2. Length is 2.

Key concepts

prefix_sumhash_mapsubarray

Practise this out loud — free

Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.

🎙 Practise this question now
Part of InterviewLab's verified interview question bank. We show the prompt and concepts to practise with — never a copy-paste solution.