Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions k-diff-pairs-in-an-array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# ------ Solution 1 ---
''' 1. Sort array
2. Maintain left and right pointer
3. Append the result in set for unique

Time complexity : O(nlogn)
Space Complexity : O(n)
'''
class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
n =len(nums)
nums.sort()
l ,r = 0, 1
res = set()
while l < n and r < n:
diff = nums[r] - nums[l]
if diff == k:
res.add((nums[l],nums[r]))
l += 1
r += 1
elif diff < k:
r += 1
else:
l += 1

if l == r:
r += 1
print(res)
return len(res)

#-------Soultion 2 : Creating hasmap with frequency
''' Time complexity : O(n)
Space Complexity : O(n)
'''
class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
n =len(nums)
count = 0
hashmap = {}
for n in nums:
hashmap[n] = 1 + hashmap.get(n,0)
for n in hashmap:
if k == 0:
if hashmap[n] >= 2:
count += 1
else:
comp = n + k
if comp in hashmap:
count += 1
return count



21 changes: 21 additions & 0 deletions pascals-triangle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'''
Time complexity : O(n ^ 2)
Space Complexity : O(1)

Approach : 1. Append 1 to start and end at each row
2. Middle element = Sum of j and j-1 of previous rows
'''

class Solution:
def generate(self, numRows: int) -> List[List[int]]:
result = []
for i in range(numRows):
l = []
for j in range(i+1):
if j == 0 or j == i:
l.append(1)
else:
l.append(result[i-1][j] + result[i-1][j-1])
result.append(l)
return result