All problems

Tent Age Pairs

Medium · two pointers

A summer camp is putting campers into two-person tents. The list ages holds the age of every camper, in no particular order, and several campers can have the same age.

The camp leaders think two campers will get along when their ages differ by at most gap years. They would like to know how many different pairs of campers could share a tent.

Return the number of pairs of campers (two different positions i < j in the list) whose ages differ by at most gap. Campers with the same age are still different campers, and a pair is counted once.

Examples

Example 1

Input: ages = [30, 5, 12, 9, 14, 40], gap = 4

Output: 3

The pairs are (5, 9), (9, 12) and (12, 14). The pair (9, 14) differs by 5, which is too much.

Example 2

Input: ages = [7, 7, 7], gap = 0

Output: 3

Three campers of the same age make three pairs: (1st, 2nd), (1st, 3rd) and (2nd, 3rd).

Example 3

Input: ages = [1, 100], gap = 5

Output: 0

The only pair differs by 99.

Constraints