diff --git a/Problem_1.py b/Problem_1.py new file mode 100644 index 00000000..1109046d --- /dev/null +++ b/Problem_1.py @@ -0,0 +1,17 @@ +# https://leetcode.com/problems/pascals-triangle/description/ + +# Time complexity: O(n ^ 2) +# Space complexity: O(1) +# Explanation: We can create rows one by one, and compute the in between values using the previous row. The first value and last value is always 1. + +class Solution: + def generate(self, numRows: int) -> List[List[int]]: + triangle = [] + + for r in range(numRows): + row = [1] * (r + 1) + for j in range(1, len(row) - 1): + row[j] = triangle[r - 1][j - 1] + triangle[r - 1][j] + triangle.append(row) + + return triangle diff --git a/Problem_2.py b/Problem_2.py new file mode 100644 index 00000000..daa0a12d --- /dev/null +++ b/Problem_2.py @@ -0,0 +1,20 @@ +# https://leetcode.com/problems/k-diff-pairs-in-an-array/description/ + +# Time complexity: O(n) +# Space complexity: O(n) +# Explanation: To avoid sorting we can use a hash map to keep a count of the frequencies of each number in nums, and then we have two cases +# - if k > 0, then we need sum of current number and k to be present in hash map to get diff to k +# - if k = 0, then we need more than 2 instances of a number to get diff to 0 + +from collections import Counter + +class Solution: + def findPairs(self, nums: List[int], k: int) -> int: + counter = Counter(nums) + res = 0 + for n in counter: + if k > 0 and n + k in counter: + res += 1 + elif k == 0 and counter[n] > 1: + res += 1 + return res