HackerRank ‘Pairs’ Solution

Short Problem Definition:

Given N integers, count the number of pairs of integers whose difference is K.

Link

Pairs

Complexity:

time complexity is O(N*log(N))

space complexity is O(N)

Execution:

The solution is pretty straight-forward, just read the code :). The runtime complexity is calculated with log(N) access times for tree-based sets (not the case in Python).

Solution:
#!/usr/bin/py
def pairs(a,k):
    answer = 0
    s = set(a)
    for v in s:
        if v+k in s:
            answer += 1
    
    return answer
if __name__ == '__main__':
    n, k = map(int, raw_input().split())
    b = map(int, raw_input().split())
    print pairs(b, k)

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

Facebooktwittergoogle_plusredditpinterestlinkedin
  • Sujit Ugale

    Solution is pretty straight forward. But kindly can u make me understand why u used set instead of a list sir. I mean how that increases time efficiency of the code.