Skip to content

Commit

Permalink
Update 03. Count Number of Pairs With Absolute Difference K.py
Browse files Browse the repository at this point in the history
  • Loading branch information
SamirPaulb authored Jul 28, 2023
1 parent f2cce9a commit cbe8c0f
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions 19_HashMap/03. Count Number of Pairs With Absolute Difference K.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,22 @@

class Solution:
def countKDifference(self, nums, k):
seen = defaultdict(int) # make dictionary of integers as key and value as 0
# seen = {i:0 for i in range(min(nums)-k, max(nums)+k+1)}
count = 0
cnt = collections.Counter()
for n in nums:
cnt[n] += 1

res = 0
taken = set()
for n in cnt:
l, r = n-k, n+k
if l not in taken:
res += cnt[n] * cnt[l]
if r not in taken:
res += cnt[n] * cnt[r]
taken.add(n)

for num in nums:
# count of num - (num-k) is seen[num-k]
# count of num - (num+k) is seen[num+k]
count += seen[num-k] + seen[num+k]
seen[num] += 1
return res

return count

'''
class Solution:
Expand All @@ -33,4 +38,4 @@ def countKDifference(self, nums, k):


# Time: O(N)
# Space: O(N)
# Space: O(N)

1 comment on commit cbe8c0f

@vercel
Copy link

@vercel vercel bot commented on cbe8c0f Jul 28, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

dsalgo – ./

ds-algo.vercel.app
dsalgo-git-main-samirpaul.vercel.app
dsalgo-samirpaul.vercel.app

Please sign in to comment.