Problem:


Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000



Sample input:
4 2
1 3
2 4


Sample output:
2

Submission status: Accepted

Solution code:
N,M=map(int,input().split())
gate=[input() for __ in range(M)]
s,e=map(int,gate[0].split())
for n in gate:
    pre_s,pre_e=map(int,n.split())
    s=(s if s>pre_s else pre_s)
    e=(e if e<pre_e else pre_e)

print(e+1-s if e>=s else 0)

Submission status: Accepted

Solution code:
N, M = list(map(int,input().split()))

Nmin = 1
Nmax = N

for i in range(M):
    L, R = list(map(int,input().split()))
    Nmin = max(L,Nmin)
    Nmax = min(R,Nmax)

print(max(Nmax-Nmin+1,0))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
l = 1
r = n
for _ in range(m):
    a, b = map(int, input().split())
    l = max(l, a)
    r = min(r, b)
ans = r - l + 1
if (ans < 0):
    ans = 0
print(ans)

Submission status: Accepted

Solution code:
import sys

fin = sys.stdin.readline
N, M = [int(elem) for elem in fin().split()]
conditions = [tuple(int(elem) for elem in fin().split()) for _ in range(M)]

l_list = [x[0] for x in conditions]
r_list = [x[1] for x in conditions]

print(max(0, min(r_list) - max(l_list) + 1))

Submission status: Accepted

Solution code:
N, M = list(map(int, input().split()))
target = [list(map(int, input().split())) for i in range(M)]

'''
4 4
1 3
2 2
1 1
2 4


'''
tmp1 = 0
tmp2 = N + 1
for t in target:
    tmp1 = max(t[0],tmp1)
    tmp2 = min(t[1],tmp2)
    #print(tmp1)
    #print(tmp2)

if  tmp2-tmp1 < 0:
    print(0)
    exit(0)
print(tmp2-tmp1 + 1)

Submission status: Accepted

Solution code:
def main():
    N, M = map(int, input().split())
    A = [0] * (N + 1)
    for _ in range(M):
        L, R = map(int, input().split())
        A[L - 1] += 1
        A[R] -= 1
    c = 0
    ans = 0
    for i, a in enumerate(A):
        c += a
        if c == M:
            ans += 1
    print(ans)


main()

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc127_c
# Prison

N, M = map(int, input().split())
pairs = [[int(c) for c in input().split()] for _ in range(M)]
left = max(pair[0] for pair in pairs)
right = min(pair[1] for pair in pairs)
print(max(0, right - left + 1))

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
a=0
b=n*10**9
for i in range(m):
  x,y=map(int,input().split())  
  a=max(a,x)
  b=min(b,y)
if b>=a:
  ans=b-a+1
  print(ans)
else:
  print(0)

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
s = [list(map(int,input().split())) for i in range(m)]
l = s[0][0]
r = s[0][1]
for item in s:
  if item[0] > l:
    l = item[0]
  if item[1] < r:
    r = item[1]
if r-l+1 > 0:
  print(r-l+1)
else:
  print(0)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
LR = [[int(i) for i in input().split()] for _ in range(M)]

minTemp = min(LR[0])
maxTemp = max(LR[0])
for i in range(M):
    if minTemp <= min(LR[i]):
        minTemp = min(LR[i])
    if max(LR[i]) <= maxTemp:
        maxTemp = max(LR[i])

count = 0
for i in range(minTemp, maxTemp + 1):
    count += 1
print(count)

Submission status: Accepted

Solution code:
str = input().split()
N = int(str[0])
M = int(str[1])
L = []
R = []
for i in range(M):
    str = input().split()
    L.append(int(str[0]))
    R.append(int(str[1]))

mini = 1
maxi = N
    
for i in range(M):
    if mini <= L[i]:
        mini = L[i]
    if maxi >= R[i]:
        maxi = R[i]
        
if (maxi - mini) >= 0:
    print(maxi - mini+1)
else:
    print(0)

Submission status: Accepted

Solution code:
N,M = map(int,raw_input().split())
L = 1
R = N
for a in range(M):
  l,r = map(int,raw_input().split())
  if L < l: L=l
  if R > r: R=r
if R-L < 0: print 0
else: print R-L+1

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
l, r = [], []

for i in range(m):
    a, b = map(int, input().split())
    l.append(a)
    r.append(b)

print(max(0, min(r) - max(l) + 1))

Submission status: Accepted

Solution code:
N,M=input().split()
N = int(N)
M = int(M)

L_max = 0
R_min = N

for i in range(M):
    L_x,R_x=input().split()
    L_x = int(L_x)
    R_x = int(R_x)
    
    if L_x > L_max:
        L_max = L_x
    if R_x < R_min:
        R_min = R_x

        
if R_min < L_max:
    print(0)
else:
    print(R_min - L_max + 1)

Submission status: Accepted

Solution code:
from operator import itemgetter

R = lambda: map(int, input().split())
n, m = R()  
a = [tuple(R()) for _ in range(m)]
print(max(0, min(map(itemgetter(1), a)) - max(map(itemgetter(0), a)) + 1))

Submission status: Accepted

Solution code:
from sys import stdin
def main():
    N, M = map(int, stdin.readline().rstrip().split())
    Lmax = 1
    Rmin = N
    for i in range(M):
      L, R = map(int, stdin.readline().rstrip().split())
      if Lmax < L:
        Lmax = L
      if Rmin > R:
        Rmin = R
    if Rmin - Lmax < 0:
      print(0)
    else:
      print(Rmin - Lmax + 1)

input = lambda: stdin.readline()
main()

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
L = []
R = []

for _ in range(m):
  l, r = map(int, input().split())
  L.append(l)
  R.append(r)
  
if min(R) - max(L) >= 0:
  print(min(R)-max(L)+1)
else:
  print(0)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
for num in range(M):
    l, r = map(int, input().split())
    if num == 0:
        minimam = l
        maximam = r
    else:
        minimam = max(minimam, l)
        maximam = min(maximam, r)
result = maximam - minimam + 1
if result >= 0:
    print(maximam - minimam + 1)
else:
    print(0)

Submission status: Accepted

Solution code:
N, M = list(map(int,input().split()))

L_li = []
R_li = []

for i in range(M):
    Li, Ri = list(map(int,input().split()))
    L_li.append(Li)
    R_li.append(Ri)


ans = min(R_li) - max(L_li) + 1
if ans < 0:
    ans = 0
    
    
print(str(int(ans)))

Submission status: Accepted

Solution code:
def main():
    n, m = map(int, input().split())
    left = 1
    right = n

    for _ in range(m):
        left_i, right_i = map(int, input().split())
        left = max(left, left_i)
        right = min(right, right_i)
    
    print(max(0, right - left + 1))

main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

N, M = map(int, input().split())
LR_list = [list(map(int, input().split())) for i in range(M)]

L = 1
R = N

for LR in LR_list:
    if LR[0] > L:
        L = LR[0]
    if LR[1] < R:
        R = LR[1]

output = 0
if L <= R:
    output = R - L + 1

print (output)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
l = 1
m = N
for i in range(M):
    l_i, m_i = map(int, input().split())
    l = max(l, l_i)
    m = min(m, m_i)
if m < l:
    print(0)
else:
    print(m - l + 1)

Submission status: Accepted

Solution code:
N,M= map(int, input().split())

L=[0]*M
R=[0]*M
for i in range(M):
    L[i],R[i]= map(int, input().split())

ans=min(R)-max(L)+1
if ans>0:
    print(ans)
else:
    print(0)

Submission status: Accepted

Solution code:
l = 0
r = 100001

(n,m) = map(int, input().split())

for i in range(m):
    (li,ri) = map(int, input().split())
    l = max(l,li)
    r = min(r,ri)

ans = max(0,r-l+1)
print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, log2
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N, M = MAP()
LR = [LIST() for _ in range(M)]
lis = [0]*(N+1)

for L, R in LR:
	lis[L] += 1
	if R+1 <= N:
		lis[R+1] -= 1

tmp = 0
max_ = 0
range_ = 0
flag = False
for i in lis:
	tmp += i
	if tmp == M:
		flag = True
		range_ += 1
if flag == True:
	print(range_)
else:
	print(0)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())

L = 0
R = N

for _ in range(M):
    preL, preR = map(int, input().split())
    if preL > L:
        L = preL
    if preR < R:
        R = preR

res = 0
if R-L >= 0:
    res= R - L + 1
print(res)

Submission status: Accepted

Solution code:
N, M = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(M)]
left, right = 0, 10**6

for i in range(M):
    if A[i][1] < left:
        print(0)
        exit()
    if A[i][0] > right:
        print(0)
        exit()
    left = max(left, A[i][0])
    right = min(right, A[i][1])

print(right-left+1)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
maxl = 0
minr = N + 1
for i in range(M):
    L, R = map(int, input().split())
    maxl = max(maxl, L)
    minr = min(minr, R)
print(max(0, minr - maxl + 1))

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
lis = [list(map(int,input().split())) for x in range(m)]
key = [-1,100001]
for x in lis:
    if key[0] < x[0]:
        key[0] = x[0]
    if key[1] > x[1]:
        key[1] = x[1]
print(len(range(key[0],key[1]+1)))

Submission status: Accepted

Solution code:
import sys

N, M = map(int, sys.stdin.readline().split())

L = []
R = []

for i in range(M):
    temp_l, temp_r = map(int, sys.stdin.readline().split())
    L.append(temp_l)
    R.append(temp_r)

temp = min(R) - max(L) + 1

if temp > 0:
    print(temp)
else:
    print(0)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

input = sys.stdin.readline

def main():
    N, M = [int(e) for e in input().split()]
    min_l = 1
    min_r = 100000
    for l in sys.stdin:
        l, r = [int(e) for e in l.strip().split()]
        if l > min_l:
            min_l = l
        if r < min_r:
            min_r = r

    res = min_r + 1 - min_l

    print(res if res > 0 else 0)

main()

Submission status: Accepted

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import math
import collections

N, M = map(int, sys.stdin.readline().rstrip().split(" "))
Lmax, Rmin = 0, N
for _ in range(M):
    L, R = map(int, sys.stdin.readline().rstrip().split(" "))
    Lmax = max(L, Lmax)
    Rmin = min(R, Rmin)
if Rmin >= Lmax:
    print(Rmin - Lmax + 1)
else:
    print(0)
exit(0)

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
l=[]
r=[]
for i in range(m):
    a,b=map(int,input().split())
    l.append(a)
    r.append(b)
    
start=0
end=100000
for i in range(m):
    if start<l[i]:
        start=l[i]
    if end>r[i]:
        end=r[i]

if start<=end:
    print(end-start+1)
else:
    print(0)

Submission status: Accepted

Solution code:
import queue

"""
N = int(input())
#S = input()
# (N,M) = (int(i) for i in input().split(" "))
# A = [int(i) for i in input().split()]
A = []
for i in range(N):
	A.append(int(input()))

print(A)

"""
(N,M) = (int(i) for i in input().split(" "))
S = [[int(i) for i in input().split()]for m in range(M)]
L = [s[0] for s in S]
R = [s[1] for s in S]
print(min(R)-max(L)+1 if min(R)-max(L)+1>0 else 0)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
 
L, R = 0, N
for _ in range(M):
    l, r = map(int, input().split())
    l-=1
    r-=1
    L = max(l, L)
    R = min(r, R)

print(R-L+1 if R-L>=0 else 0)

Submission status: Accepted

Solution code:
from collections import defaultdict


class Solution:
    def main(self):
        N, M = map(int, input().split())
        L = []
        R = []
        cards = set(list(range(1, N+1)))
        left = 1
        right = N
        for _ in range(M):
            l, r = map(int, input().split())
            if right < l or r < left:
                print(0)
                return 0

            left = max(l, left)
            right = min(r, right)
        else:
            print(right-left+1)
            return


if __name__ == '__main__':
    Solution().main()

Submission status: Accepted

Solution code:
N, M = map(int,input().split())
L =[]
R =[]
for i in range(M):
    L1, R1 = map(int,input().split())
    L.append(L1-1)
    R.append(R1+1)
if min(R) - max(L) -1<0:
    print("0")
else:
    print(min(R)-max(L)-1)

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
L=[0]*M
R=[0]*M
for i in range(M):
    L[i],R[i] = map(int,input().split())

# N,M=10,3
# L=[1,2]
# R=[3,4]
if min(R)-max(L)+1 < 0:
    print(0)
else:
    print(min(R)-max(L)+1)

Submission status: Accepted

Solution code:
n, m = map(int,input().split())

lefts = [0] * m
rights = [0] * m

for i in range(m):
	l, r = map(int,input().split())
	lefts[i] = l
	rights[i] = r

lefts_max = max(lefts)
rights_min = min(rights)

result = rights_min - lefts_max + 1

print(max(result,0))

Submission status: Accepted

Solution code:
N,M=(int(i) for i in input().split())
gate=[]
for i in range(M):
    gate.append([int(i) for i in input().split()])
    
maxl=max(gate,key=lambda x:x[0])[0]
minr=min(gate,key=lambda x:x[1])[1]
if maxl<=minr:
    print(minr-maxl+1)
else:
    print(0)

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
L = [[int(i) for i in input().split()] for i in range(M)]
left = 0
right = N
for i,j in L:
    left = max(left,i)
    right = min(right,j)
print(max(0,right-left+1))

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
#ll,rr = map(int, input().split())
ll = 0
rr = n
for i in range(m):
  l, r = map(int, input().split())
  if ll > r or rr < l:
    ll = 2
    rr = 1
    break
  if ll <= l:
    ll = l
  if r <= rr:
    rr = r

print(rr-ll+1)

Submission status: Accepted

Solution code:
#!/usr/bin/python
# coding: UTF-8

n,m = input().split()

n = int(n)
m = int(m)

min = 1
max = n
for i in range(m):
    _min,_max = input().split()
    _min = int(_min)
    _max = int(_max)

    if min < _min:
        min = _min

    if max > _max:
        max = _max

if max - min + 1 > -1:
    print(max - min + 1)
else:
    print(0)

Submission status: Accepted

Solution code:
import sys,collections,math,random;sys.setrecursionlimit(10**7)
def Is(): return [int(x) for x in sys.stdin.readline().split()]
def Ss(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

n,m = Is()
left,right = 0,n
for i in range(m):
    l,r = Is()
    left = max(left,l)
    right = min(right,r)
#    print(left,right)
if right-left < 0:
    print(0)
else:
    print(right-left+1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3


def solv(n, ls, rs):
    n = min(rs) - max(ls) + 1
    return max(n, 0)


if __name__ == '__main__':

    n, m = map(int, input().split())
    ls = []
    rs = []
    for _ in range(m):
        li, ri = map(int, input().split())
        ls.append(li)
        rs.append(ri)

    ans = solv(n, ls, rs)

    print(ans)

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
l = 1
r = n
for i in range(m):
    L, R = map(int, input().split())
    l = max(L, l)
    r = min(R, r)

ans = r - l + 1 if r - l + 1 > 0 else 0
print(ans)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())

l,r = 0,100000
for m in range(M):
  L,R = map(int, input().split())
  l = max(l, L)
  r = min(r, R)

if l > r:
  print(0)
else:
  print(r-l+1)

Submission status: Accepted

Solution code:
inputs = list(map(int, input().split(' ')))[:2]
N = inputs[0]
M = inputs[1]

min_R = N
max_L = 0

for i in range(0,M):
    LR = list(map(int, input().split(' ')))[:2]
    max_L = max(max_L,LR[0])
    min_R = min(min_R,LR[1])

print(len(range(max_L,min_R+1)))

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
lr_list = list(list(map(int,input().split())) for _ in range(m))
res = [0]*(n+2)
for l,r in lr_list:
    res[l] += 1
    res[r+1] -= 1

for i in range(1,n+2):
    res[i] += res[i-1]

max_num = max(res)
if max_num == m:
    print(res.count(max_num))
else:
    print(0)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
LR = [[int(_) for _ in input().split()] for _ in range(M)]
L = 0
R = 10 ** 5
for l, r in LR:
    L = max(L, l)
    R = min(R, r)

if L > R:
    print(0)
else:
    print(R - L + 1)

Submission status: Accepted

Solution code:
i = input().split(" ")

N = int(i[0])
M = int(i[1])

mi = 0
ma = N

for j in range(M):
	i = input().split(" ")
	l = int(i[0])
	r = int(i[1])
	if l >= mi:
		mi = l
	if r <= ma:
		ma = r

r = ma - mi + 1

if r > 0:
	print(r)
else:
	print(0)

Submission status: Accepted

Solution code:
a,b=input().split()
a=int(a)
b=int(b)
ll=[]
l2=[]
for i in range(b):
    c,d=input().split()
    c=int(c)
    d=int(d)
    ll.append(c)
    l2.append(d)
x=max(ll)
y=min(l2)
z=y-x
if z>=0:
    print(z+1)
else:
    print(0)

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
maxl = 1
minr = N
for i in range(M):
    l,r = map(int,input().split())
    if l >= maxl:
        maxl = l
    if r <= minr:
        minr = r
if maxl > minr:
    print(0)
else:
    print(minr-maxl+1)

Submission status: Accepted

Solution code:
a,b=map(int,input().split())
s=[input().split() for i in range(b)]
c=0
d=100000
for j in s:
    j[0]=int(j[0])
    j[1]=int(j[1])
    if j[0]>c:
        c=j[0]
    if j[1]<d:
        d=j[1]
if d-c+1<0:
    ans=0
else:
    ans=d-c+1
print(ans)

Submission status: Accepted

Solution code:
from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()



# ///==========Libraries, Constants and Functions=============///

inf = float("inf")
mod = 10**9+7

#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import ceil,floor,log,sqrt,factorial,pow,pi
#from bisect import bisect_left,bisect_right
#from decimal import *,threading

def dmain():
    sys.setrecursionlimit(100000000)
    threading.stack_size(40960000)
    thread = threading.Thread(target=main)
    thread.start()
    

abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod,MOD=1000000007,998244353
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[0] 
def sort2(l):return sorted(l, key=getKey)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x


def factorial_p(n, p):
    ans = 1
    if n <= p // 2:
        for i in range(1, n + 1):
            ans = (ans * i) % p
    else:
        for i in range(1, p - n):
            ans = (ans * i) % p
        ans = pow(ans, p - 2, p)
        if n % 2 == 0:
            ans = p - ans
    return ans

def nCr_p(n, r, p):
    ans = 1
    while (n != 0) or (r != 0):
        a, b = n % p, r % p
        if a < b:
            return 0
        ans = (ans * factorial_p(a, p) * pow(factorial_p(b, p), p - 2, p) * pow(factorial_p(a - b, p), p - 2, p)) % p
        n //= p
        r //= p
    return ans

def prime_sieve(n):
    """returns a sieve of primes >= 5 and < n"""
    flag = n % 6 == 2
    sieve = bytearray((n // 3 + flag >> 3) + 1)
    for i in range(1, int(n**0.5) // 3 + 1):
        if not (sieve[i >> 3] >> (i & 7)) & 1:
            k = (3 * i + 1) | 1
            for j in range(k * k // 3, n // 3 + flag, 2 * k):
                sieve[j >> 3] |= 1 << (j & 7)
            for j in range(k * (k - 2 * (i & 1) + 4) // 3, n // 3 + flag, 2 * k):
                sieve[j >> 3] |= 1 << (j & 7)
    return sieve

def prime_list(n):                            #<----- You have to call me if you wanna get list of primes upto range n
    """returns a list of primes <= n"""
    res = []
    if n > 1:
        res.append(2)
    if n > 2:
        res.append(3)
    if n > 4:
        sieve = prime_sieve(n + 1)
        res.extend(3 * i + 1 | 1 for i in range(1, (n + 1) // 3 + (n % 6 == 1)) if not (sieve[i >> 3] >> (i & 7)) & 1)
    return res

def is_prime(n):
    """returns True if n is prime else False"""
    if n < 5 or n & 1 == 0 or n % 3 == 0:
        return 2 <= n <= 3
    s = ((n - 1) & (1 - n)).bit_length() - 1
    d = n >> s
    for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
        p = pow(a, d, n)
        if p == 1 or p == n - 1 or a % n == 0:
            continue
        for _ in range(s):
            p = (p * p) % n
            if p == n - 1:
                break
        else:
            return False
    return True


def all_factors(n):
    """returns a sorted list of all distinct factors of n"""
    small, large = [],[]
    for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1):
        if not n % i:
            small.append(i)
            large.append(n//i)
    large.reverse()
    small.extend(large)
    return small

def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def input(): return sys.stdin.readline().strip()

#======================================================================================================

def main():
	n,m=get_ints()
	l,r=get_ints()
	total=r-l+1
	for i in range(1,m):
		ln,rn=get_ints()
		total=min(rn,r)-max(ln,l)+1
		r=min(rn,r);l=max(ln,l)
	print(max(total,0))
		
# region fastio===================================================================================================================

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        if self.buffer.tell():
            return self.buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()


sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

# endregion=========================================================================================================

# ///===========MAIN=============///

if __name__ == "__main__":
    main()
    #dmain()

Submission status: Accepted

Solution code:
N, M = [int(x) for x in input().split()]

max_a, min_b = 0, 10000000
for _ in range(M):
  a, b = [int(x) for x in input().split()]
  if a > max_a:
    max_a = a
  if b < min_b:
    min_b = b
if min_b < max_a:
  print(0)
else:
  print(min_b - max_a + 1)

Submission status: Accepted

Solution code:
from sys import stdin
data = stdin.readline().split()
N, M = int(data[0]), int(data[1])
left = [None] * M
right = [None] * M
for itr in range(M):
    gate = stdin.readline().split()
    left[itr] = int(gate[0])
    right[itr] = int(gate[1])
if (min(right)-max(left) + 1) < 0:
    print(0)
else:
    print(min(right)-max(left) + 1)

Submission status: Accepted

Solution code:
N,M = list(map(int,input().split()))

L = []
R = []
for i in range(M):
    L1,R1=[int(i) for i in input().split()]
    L.append(L1)
    R.append(R1)
lmax = max(L)
rmin = min(R)
if rmin >= lmax:
    print (rmin-lmax+1)
else:
    print(0)

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
lr = [list(map(int, input().split())) for _ in range(m)]

lr_min=1145141919
lr_max=0

for i in range(m):
    lr_max=max(lr_max,lr[i][0])
    lr_min=min(lr_min,lr[i][1])

if (lr_min-lr_max+1)<=0:
    print(0)
else:
    print(lr_min-lr_max+1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python

import sys

n,m = [ int(x) for x in sys.stdin.readline().split() ]

li, ri = [0] * m, [0] * m
for i in range(m):
    li[i], ri[i] = [ int(x) for x in sys.stdin.readline().split() ]
#    
imin=1
imax=n
for i in range(m):
    if li[i]>imin: imin=li[i]
    if ri[i]<imax: imax=ri[i]
#
if imax>=imin:
    print( imax-imin+1 )
else:
    print( 0 )

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
lmax = 0
rmin = n
for i in range(m):
    l,r = map(int,input().split())
    if l > lmax:
        lmax = l
    if r < rmin:
        rmin = r
#print(lmax,rmin)
if rmin-lmax < 0:
    print(0)
else:
    print(rmin-lmax+1)

Submission status: Accepted

Solution code:
t = input().split()
n = int(t[0])
m = int(t[1])

low = 0
high = n
for i in range(0, m):
  tmp = input().split()
  if int(tmp[0]) > low:
    low = int(tmp[0])
  if int(tmp[1]) < high:
    high = int(tmp[1])

if (high-low)<0:
  num = 0
else:
  num = high-low+1
print(num)

Submission status: Accepted

Solution code:
n, m = [int(i) for i in input().split()]
lfix = 0
rfix = n + 1
for i in range(m):
    l, r = [int(i) for i in input().split()]
    lfix = max(lfix, l)
    rfix = min(rfix, r)
print(max(rfix - lfix + 1, 0))

Submission status: Accepted

Solution code:
import sys
from fractions import gcd

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()
s = lambda h: [list(map(int, stdin.readline().split())) for i in range(h)]



n, m = na()
l, r = [0] * m, [0] * m
for i in range(m):
    l[i], r[i] = na()

if min(r) - max(l) < 0:
    ans = 0
else:
    ans = min(r) - max(l) + 1
print(ans)

Submission status: Accepted

Solution code:
n,m=list(map(int,input().split()))
a=1
b=n
for i in range(m):
    l,r=list(map(int,input().split()))
    if a<l:
        a=l
    if b>r:
        b=r
if b-a+1>0:
    print(b-a+1)
else:
    print(0)

Submission status: Accepted

Solution code:
N, M = [int(i) for i in input().split()]
inputs = [[int(i) for i in input().split()] for _ in range(M)]

mi = max([i[0] for i in inputs])
ma = min([i[1] for i in inputs])

diff = ma - mi + 1
print(diff if diff > 0 else 0)

Submission status: Accepted

Solution code:
N, M = map(int,input().split())
List = [list(map(int,input().split())) for i in range(M)]

mi = 1
ma = N

for i in range(M):
    if mi < List[i][0]:
        mi = List[i][0]
    if ma > List[i][1]:
        ma = List[i][1]

diff = ma - mi + 1
if diff < 0:
    diff = 0
print("{}".format(diff))

Submission status: Accepted

Solution code:
n, m = [int(_) for _ in input().split()]
g = [[int(_) for _ in input().split()] for __ in range(m)]
l = g[0][0]; r = g[0][1]
for i in range(1,m):
    l = max(l, g[i][0])
    r = min(r, g[i][1])
print(max(0, r-l+1))

Submission status: Accepted

Solution code:
n,m = map(int, input().split())
p,q = float('-inf'),float('inf')
for i in range(m):
  a,b = map(int, input().split())
  if a > p:
    p = a
  if b < q:
    q = b
if (q-p) < 0:
  print(0)
else:
  print(q-p+1)

Submission status: Accepted

Solution code:
N, M = map(int, input().strip().split())
L = [0] * M
R = [0] * M
for i in range(M):
    L[i], R[i] = map(int, input().strip().split())

diff = min(R) - max(L)
if diff >= 0:
    print(diff + 1)
else:
    print(0)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
L = []
R = []

for _ in range(M):
    l, r = map(int, input().split())
    L.append(l)
    R.append(r)

ml = max(L)
mr = min(R)

if ml > mr:
    print(0)
else:
    print(mr - ml + 1)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
L_min = 0
R_min = N
for i in range(M):
    L_i, R_i = map(int, input().split())
    if L_min < L_i:
        L_min = L_i
    if R_min > R_i:
        R_min = R_i
if R_min >= L_min:
    print(R_min - L_min + 1)
else:
    print(0)

Submission status: Accepted

Solution code:
# def gcd(a_gcd, b_gcd):
#     while b_gcd != 0:
#         a_gcd, b_gcd = b_gcd, a_gcd % b_gcd
#     return a_gcd
#
#
# def lcm(a_lcm, b_lcm):
#     return a_lcm * b // gcd(a_lcm, b_lcm)
#
#
# def max_sum(N_max_sum, a_max_sum):
#     dp = [0] * (N_max_sum + 1)
#     for i in range(N_max_sum):
#         dp[i + 1] = max(dp[i], dp[i] + a_max_sum[i])
#     return dp[N]
#
#
# def knapsack(N_knapsack, W, weight, value):
#     inf = float("inf")
#     dp = [[-inf for _ in range(W+1)] for j in range(N_knapsack + 1)]
#     for i in range(W+1):
#         dp[0][i] = 0
#
#     for i in range(N_knapsack):
#         for w in range(W+1):
#             if weight[i] <= w:
#                 dp[i+1][w] = max(dp[i][w-weight[i]]+value[i], dp[i][w])
#             else:
#                 dp[i+1][w] = dp[i][w]
#     return dp[N_knapsack][W]
#
#
# class UnionFind:
#     def __init__(self, n):
#         self.par = [i for i in range(n+1)]
#         self.rank = [0] * (n+1)
#
#     # 検索
#     def find(self, x):
#         if self.par[x] == x:
#             return x
#         else:
#             self.par[x] = self.find(self.par[x])
#             return self.par[x]
#
#     # 併合
#     def union(self, x, y):
#         x = self.find(x)
#         y = self.find(y)
#         if self.rank[x] < self.rank[y]:
#             self.par[x] = y
#         else:
#             self.par[y] = x
#             if self.rank[x] == self.rank[y]:
#                 self.rank[x] += 1
#
#     # 同じ集合に属するか判定
#     def same_check(self, x, y):
#         return self.find(x) == self.find(y)
#
# S = input()
# N = int(input())
# A = list(map(int, input().split()))

N, M = map(int, input().split())
L = []
R = []

for i in range(M):
    l, r = map(int, input().split())
    L.append(l)
    R.append(r)

print(max(0, min(R) - max(L) + 1))

Submission status: Accepted

Solution code:
N,M=map(int,input().split())
lmax=0
rmin=9999999
for i in range(M):
    l,r=map(int,input().split())
    lmax=max(lmax,l)
    rmin=min(rmin,r)

print(max(rmin-lmax+1,0))