title: The most efficient way to find the point where maximum number of intervals overlap with python
body: <p>Consider I have a log register for users' entry and exit times from some server. I need to find the time at which there are maximum sessions. If there are more than one possible answer, the smallest should be chosen. The input contains the number of sessions in the first line.</p>
  
  <p>Example
  Input: </p>
  
  <pre><code>5
  4 5
  0 3
  1 9
  7 8
  2 6
  </code></pre>
  
  <p>Output: </p>
  
  <pre><code>2
  </code></pre>
  
  <p>I tried this script:</p>
  
  <pre><code>from collections import Counter, OrderedDict
  
  load = Counter()
  with open("input.txt", "r") as f:
      n = int(f.readline())
      for i in range(n):
          session = f.readline()
          session = session.split()
          load.update(range(int(session[0]), int(session[1])+1))
  
  load = load.most_common()
  i = 0
  max = load[0][1]
  candidates = []
  while load[i][1] == max:
      candidates.append(load[i][0])
      i += 1
  print(min(candidates))
  </code></pre>
  
  <p>First, I use <code>Counter()</code> to count the occurrences of all points. Second, I use <code>load = load.most_common()</code> to order the resulting dict by occurrences. Finally I find the minimum value of all keys with the corresponding maximum value (= # of occurrences). </p>
  
  <p>In fact, if <code>Counter()</code> returned a dict ordered by key, it would be much simpler. </p>
  
  <p>Anyway, it is my home task and it runs more than 1 second (given time limit) on one of the test inputs. What could be done to speed it up? I've read about interval trees but I'm not sure if it is relevant. </p>