title: Codility Counting Lesson
body: <p>I'm studying Codility Counting Lesson (<a href="https://codility.com/media/train/2-CountingElements.pdf" rel="noreferrer">https://codility.com/media/train/2-CountingElements.pdf</a>) and I need help to understand the fastest solution.</p>
  
  <p>I am wondering why the difference is divided by 2 in line 8 <code>d //= 2</code>? Shouldn't the difference be sufficient to find the elements that we can swap between the arrays?</p>
  
  <p>The Problem: </p>
  
  <blockquote>
    <p>You are given an integer <code>m</code> (<code>1 &lt; m &lt; 1000000</code>) and two non-empty,
    zero-indexed arrays <code>A</code> and <code>B</code> of <code>n</code> integers, <code>a0</code>, <code>a1</code>, ... ,
    <code>an−1</code> and <code>b0</code>, <code>b1</code>, ... , <code>bn−1</code> respectively (<code>0 &lt; ai</code>, <code>bi &lt; m</code>).
    The goal is to check whether there is a swap operation which can be
    performed on these arrays in such a way that the sum of elements in
    array <code>A</code> equals the sum of elements in array <code>B</code> after the swap. By
    swap operation we mean picking one element from array <code>A</code> and one
    element from array <code>B</code> and exchanging them.</p>
  </blockquote>
  
  <p>The solution:</p>
  
  <pre><code> def fast_solution(A, B, m):
     n = len(A)
     sum_a = sum(A)
     sum_b = sum(B)
     d = sum_b - sum_a
     if d % 2 == 1:
         return False
     d //= 2
     count = counting(A, m)
     for i in xrange(n):
         if 0 &lt;= B[i] - d and B[i] - d &lt;= m and count[B[i] - d] &gt; 0:
             return True
     return False
  </code></pre>