Distinct Consecutive Pairs
MediumPractice library · +20 XParrayshash mapcounting
Given an array of N integers, find the number of distinct pairs (a, b) such that 'a' and 'b' are adjacent elements in the array (i.e., b appears immediately after a) and 'a' != 'b'.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers representing the elements of the array.
Output
Print a single integer, the count of distinct consecutive pairs (a, b) where a != b.
Constraints
1 <= N <= 200000. Each array element will be between -10^9 and 10^9.
Time limit 1 s (native code; slower languages get more)Memory 256 MB16 hidden tests
Example 1
Input
5 1 2 1 2 3
Output
3
The consecutive pairs are (1,2), (2,1), (1,2), (2,3). The distinct pairs are (1,2), (2,1), (2,3), so the count is 3.
Example 2
Input
4 5 5 5 5
Output
0
All adjacent elements are equal, so no pairs satisfy a != b. The count is 0.
Hints
# 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 1 2 1 2 3
Example 2 input
4 5 5 5 5