Sum of Two Adjacent Elements
MediumPractice library · +20 XPrecursionsliding windowprefix sum
Given a list of N integers and a target sum K, find the number of pairs of adjacent elements in the list whose sum equals K. A pair (A[i], A[i+1]) is adjacent.
Input
The first line contains two integers N and K, separated by a space. The second line contains N integers A_1, A_2, ..., A_N, representing the list.
Output
Print a single integer, the count of adjacent pairs summing to K.
Constraints
1 <= N <= 200000 -10^9 <= A_i <= 10^9 -2 * 10^9 <= K <= 2 * 10^9
Time limit 1 s (native code; slower languages get more)Memory 256 MB15 hidden tests
Example 1
Input
5 10 1 9 5 5 2
Output
2
Pairs (1,9) and (5,5) sum to 10. Count is 2.
Example 2
Input
3 7 1 2 3
Output
0
No adjacent pair sums to 7. Count is 0.
Hints
Similar problems
- Maximum Subarray Sum with Fixed LengthMedium
- Optimal Training ScheduleMedium
- Longest Subarray with Sum at Most KMedium
- Longest Subarray With Sum XMedium
- Subsegment Sum Divisible by KMedium
- Count Pairs with Equal XOR SumMedium
More topics: Sliding Window problems, Prefix Sums problems, Recursion problems
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 10 1 9 5 5 2
Example 2 input
3 7 1 2 3