Question: I am making a complex algorithm in C# in which one step is to compare 2 very large lists of ranges and finding out the overlapping region. I have tried a lot of ways to find them, but m not sure if I am covering all possibilities. Also my algo on this step is taking too long with huge lists.

**Example:**

**range 1 = 1-400**

**range 2 = 200-600**

So when I want to check overlap between these two ranges I should get the answer = 200.

Because total 200 numbers are overlapping between these two ranges. So this is how I want the answer, I want the exact number of integers that are overlapping between two ranges.

**Example of Lists:**

List1 : 1-400, 401-800, 801-1200 and so on...  

List2 : 10240-10276, 10420 10456, 11646-11682 and so on...

Now I have to compare each range of list1 with each range of list2, and find out if a certain range of list1 overlaps with any of the range of list2 and if yes then what is the overlapping answer? These are just sample values for the purposes of understanding.

I only need a simple and most efficient/fast formula to find out the overlap answer between 2 ranges. I can manage the rest of the loop algorithm.

**Example formula** :

```
var OverlappingValue = FindOverlapping(range1.StartValue, range1.EndValue,range2.StartValue, range2.EndValue);

```

and if the two ranges are not overlapping at all, then function must return 0.

PS: I didn't post my code because it's really complicated with a lot of conditions, I only need one simple formula.

Answer: 
You can try something like this:

```
void Main()
{
    double adStart = 1.501;
    double adEnd = 21.83;
    double bdStart = 0.871;
    double bdEnd = 56.81;

    int aiStart = 21;
    int aiEnd = 35;
    int biStart = 29;
    int biEnd = 43;

    // 20.239
    double dOverlap = FindOverlapping((int)(adStart*1000), (int)(adEnd*1000), (int)(bdStart*1000), (int)(bdEnd*1000))/1000.0;

    // 6
    int iOverlap = FindOverlapping(aiStart, aiEnd, biStart, biEnd);

    // 0
    iOverlap = FindOverlapping(20, 25, 26, 30);

    // 0
    iOverlap = FindOverlapping(20, 25, 25, 30);
}

int FindOverlapping(int aStart, int aEnd, int bStart, int bEnd)
{
    int overlap = System.Linq.Enumerable.Range(aStart, aEnd - aStart).Intersect(System.Linq.Enumerable.Range(bStart, bEnd - bStart)).Count();

    return overlap;
}

```
A one-liner formula to use would be this one.

Let's say you have 2 intervals:
(a1, a2) and (b1, b2)

Then the overlapping region would be: max{0, min{a2-b1, b2-a1}}