fork download
  1. # your code goes here
  2. # Count all i,j pairs where i<j and abs(b[i]-b[j]) = k [k>=0]
  3.  
  4.  
  5. def func(arr, K):
  6. freq = {}
  7. result = 0
  8.  
  9. for n in arr:
  10. result += freq.get(K+n, 0)
  11. if K!=0:
  12. result += freq.get(n-K, 0)
  13. freq[n] = freq.get(n, 0)+1
  14.  
  15.  
  16. return result
  17.  
  18.  
  19. arr = [1, 5, 3, 4, 2]
  20. k = 2
  21.  
  22. print(func(arr, k))
Success #stdin #stdout 0.1s 14088KB
stdin
Standard input is empty
stdout
3