Fastest way to find if a lot numbers are in multiple intervals So I have a task. I've been given \$n\$ numbers and \$m\$ intervals and I need to figure out how many numbers are in the \$m\$ \$i\$-th interval. I've written some code with a complexity of \$O(n \times m)\$, though I need to optimize it more. Any help? Code:

#include &lt;bits/stdc++.h&gt;
using namespace std;

int main()
{
    cin.tie(0);
    ios_base::sync_with_stdio(0);
    cout.tie(0);
    int n,m,temp,temp1;
    vector &lt;pair&lt;int, int&gt;&gt; uogienes;
    vector &lt;int&gt; erskeciai;

cin &gt;&gt; n &gt;&gt; m;
for (int i = 0; i&lt; n; i++){
    cin&gt;&gt;temp;
    erskeciai.push_back(temp);
}
temp = 0;
for (int i = 0; i&lt;m; i++){
    cin&gt;&gt; temp &gt;&gt; temp1;
    uogienes.push_back(make_pair(temp, temp1));
}
for(int i = 0; i&lt;m; i++){
        temp=0;
    for(int h = 0; h&lt;n; h++){
       if(uogienes[i].first &lt;= erskeciai[h] &amp;&amp; uogienes[i].second &gt;= erskeciai[h]){
        temp++;
        }
    }
cout  &lt;&lt; temp &lt;&lt; "\n";
}
return 0;
}
Review

Please don't use using namespace; on the gobal scope. It's considered bad practice. Next, try to keep the scope of your variables smaller. Also indent your code properly to make it easier for you (and others) to see the program flow.

Don't include bits/c++. It's not a standard header. It's somewhat OK in programming challenges, but you should use the proper includes in your real/production code.

If you use a smaller scope for your variables, you will also be able to use better names for them, for example lower instead of temp and upper instead of temp1.

If we apply these changes (and translate your names into English), we end up with

#include &lt;iostream&gt;
#include &lt;utility&gt;
#include &lt;vector&gt;

int main()
{
    std::cin.tie(0);
    ios_base::sync_with_stdio(0);
    std::cout.tie(0);

    std::vector&lt;std::pair&lt;int, int&gt;&gt; ranges;
    std::vector&lt;int&gt; numbers;

    int number_count, range_count;

    std::cin &gt;&gt; number_count &gt;&gt; range_count;

    for (int i = 0; i &lt; number_count; i++){
        int number;
        std::cin &gt;&gt; number;
        numbers.push_back(number);
    }

    for (int i = 0; i &lt; range_count; i++){
        int lower, upper;
        std::cin &gt;&gt; lower &gt;&gt; upper;
        ranges.push_back({lower, upper});
    }

    for(int i = 0; i &lt; range_count; i++){        
        int count = 0;

        for(int h = 0; h &lt;number_count; h++){
            if(ranges[i].first &lt;= numbers[h] &amp;&amp; ranges[i].second &gt;= numbers[h]){
                count++;
            }
        }
        std::cout &lt;&lt; count &lt;&lt; "\n";
    }
    return 0;
}


It would be even better to use the proper types and more functions for I/O.

Performance

Instead of \$\mathcal O(nm)\$, you can get \$\mathcal O((n+m) \log n)\$ if you std::sort the numbers and then use std::lower_bound and std::upper_bound.