algoblazerEarly Access
LearnProblemsLeaderboard
Log inSign up

All problems

‹ Back to map
2 shown · 0/261 solved

Count Intervals Without Forbidden Pairs

SilverCommunity Beta
Asked atUber
Solve problem →
2000ms256MBAdded Aug 3, 2026

You are given an integer n (labels 0 to n - 1) and an array pairs, where each pairs[i] = [a, b] (a != b) is a forbidden pair.

An interval [L, R] (with 0 <= L <= R <= n - 1) contains a forbidden pair [a, b] if both a and b lie inside it, meaning L <= min(a, b) and max(a, b) <= R.

Return the number of intervals [L, R] that contain no forbidden pair. The same pair may appear multiple times in pairs; duplicates do not change the answer.

Examples

Example 1

Input: n = 4, pairs = [[1,3]]
Output: 8
Explanation: Of the 10 intervals over labels 0..3, only [0,3] and [1,3] contain both 1 and 3. The other 8 are valid.

Example 2

Input: n = 3, pairs = [[0,1],[1,2]]
Output: 3
Explanation: Only the single-label intervals [0,0], [1,1], [2,2] avoid both pairs.

Example 3

Input: n = 5, pairs = []
Output: 15
Explanation: With no forbidden pairs, all n * (n + 1) / 2 = 15 intervals are valid.

Constraints

  • 1≤n≤2⋅1051 \leq n \leq 2 \cdot 10^51≤n≤2⋅105
  • 0≤0 \leq0≤ pairs.length ≤2⋅105\leq 2 \cdot 10^5≤2⋅105
  • pairs[i] =[a,b]= [a, b]=[a,b] with 0≤a,b<n0 \leq a, b < n0≤a,b<n and a≠ba \neq ba=b

Details

Solved by5 people
Time limit2000ms
Memory256MB
AddedAug 3, 20265 weeks ago