Skip to content

Commit

Permalink
Cracking the coding interview initialisation
Browse files Browse the repository at this point in the history
  • Loading branch information
joffilyfe committed Jan 7, 2024
1 parent b8e2e4a commit c71e75b
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
3 changes: 3 additions & 0 deletions cracking-the-coding-interview/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Cracking the coding interview

This sub dir has some extracted lessons from the CCTI book. It may not be complete.
50 changes: 50 additions & 0 deletions cracking-the-coding-interview/vii/1-bottlenet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import unittest

# Example: Given an array of distinct integer values,
# count the number of pairs of integers that have difference k.
# For example, given the array {1, 7, 5, 9, 2, 12, 3} and
# the difference k = 2,there are four pairs with
# difference 2: (1, 3), (3, 5), (5, 7), (7, 9).

# the first approach is using brute force to iterate over the array nums
# from i to n and internally doing it from i + 1 to n
# until finding the last pair at (n, n).

# the O(n) approach is to dump the complement into as key into the
# hash table then iterate over the array again and try to find
# each num as key in the table. If it can be found then
# it has its pair.


class Solution:
def finding_pairs_of_k(self, nums, k: int):
table = {}
count = 0

for num in nums:
table[num - k] = num

for num in nums:
if table.get(num, None):
count += 1

return count


class Test(unittest.TestCase):
def setUp(self):
self.solution = Solution()

def test_first(self):
self.assertEqual(
self.solution.finding_pairs_of_k(nums=[1, 7, 5, 9, 2, 12, 3], k=2), 4
)

def test_second(self):
self.assertEqual(
self.solution.finding_pairs_of_k(nums=[1, 7, 5, 9, 2, 12, 3], k=10), 1
)


if __name__ == "__main__":
unittest.main()

0 comments on commit c71e75b

Please sign in to comment.