Skip to content

Commit 974ae7e

Browse files
Imp Leetcode questions solved using python.
1 parent 3d7657e commit 974ae7e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+2042
-0
lines changed

3Sum.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def threeSum(self, nums: List[int]) -> List[List[int]]:
3+
4+
res = []
5+
nums.sort()
6+
for i in range(len(nums)-2):
7+
if(i > 0 and nums[i] == nums[i-1]):
8+
continue
9+
currA = nums[i]
10+
left = i+1
11+
right = len(nums)-1
12+
while(left < right):
13+
if((currA + nums[left] + nums[right]) == 0):
14+
res.append([currA,nums[left],nums[right]])
15+
while left < right and nums[left] == nums[left+1]:
16+
left += 1
17+
while left < right and nums[right] == nums[right-1]:
18+
right -= 1
19+
left+=1
20+
right-=1
21+
elif((currA + nums[left] + nums[right]) < 0):
22+
left+=1
23+
else:
24+
right-=1
25+
return res

4Sum-II.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution:
2+
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
3+
4+
tot = 0
5+
mapper = {}
6+
for i in range(0, len(nums1)):
7+
currA = nums1[i]
8+
for j in range(0,len(nums2)):
9+
currB = nums2[j]
10+
11+
if( currA + currB not in mapper):
12+
mapper[currA+currB] = 1
13+
else:
14+
mapper[currA+currB]+=1
15+
16+
for i in range(0, len(nums3)):
17+
currC = nums3[i]
18+
for j in range(0,len(nums4)):
19+
currD = nums4[j]
20+
ele = (currC + currD)*-1
21+
if( ele in mapper):
22+
tot+=mapper[ele]
23+
24+
return tot

4Sum.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution:
2+
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
3+
if not nums or len(nums)<4:
4+
return []
5+
6+
7+
#Without using hashmaps. Complexity - O(n3)
8+
9+
res = []
10+
nums.sort()
11+
for i in range(len(nums)-3):
12+
for j in range(i+1,len(nums)-2):
13+
sum2 = nums[i]+nums[j]
14+
left = j + 1
15+
right = len(nums)-1
16+
while(left < right):
17+
sumTot = sum2 + nums[left] + nums[right]
18+
if(sumTot == target and [nums[i],nums[j],nums[left],nums[right]] not in res):
19+
res.append([nums[i],nums[j],nums[left],nums[right]])
20+
left+=1
21+
right-=1
22+
elif sumTot < target:
23+
left+=1
24+
else:
25+
right-=1
26+
27+
return res

LRUCache.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from collections import deque
2+
class LRUCache:
3+
4+
def __init__(self, capacity: int):
5+
self.hmap = {}
6+
self.cap = capacity
7+
self.q = deque()
8+
9+
def get(self, key: int) -> int:
10+
if key in self.hmap:
11+
val = self.hmap[key]
12+
self.q.remove(key)
13+
self.q.append(key)
14+
return val
15+
else:
16+
return -1
17+
18+
19+
def put(self, key: int, value: int) -> None:
20+
if key not in self.hmap:
21+
if len(self.q) == self.cap:
22+
removed = self.q.popleft()
23+
del self.hmap[removed]
24+
else:
25+
self.q.remove(key)
26+
self.hmap[key] = value
27+
self.q.append(key)
28+
29+
30+
# Your LRUCache object will be instantiated and called as such:
31+
# obj = LRUCache(capacity)
32+
# param_1 = obj.get(key)
33+
# obj.put(key,value)

PermutationinString.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution:
2+
def checkInclusion(self, s1: str, s2: str) -> bool:
3+
if(len(s1) > len(s2)):
4+
return False
5+
l = 0
6+
r = len(s1) - 1
7+
targetDict = {}
8+
for currChar in s1:
9+
targetDict[currChar] = targetDict.get(currChar, 0) + 1
10+
11+
currDict = {}
12+
for i in range(r+1):
13+
currDict[s2[i]] = currDict.get(s2[i], 0) + 1
14+
15+
while(r < len(s2)):
16+
if(currDict == targetDict):
17+
return True
18+
currToDelete = s2[l]
19+
currDict[currToDelete] -= 1
20+
if(currDict[currToDelete] == 0):
21+
currDict.pop(currToDelete)
22+
l += 1
23+
r += 1
24+
25+
if(r < len(s2)):
26+
currDict[s2[r]] = currDict.get(s2[r], 0) + 1
27+
28+
return False
29+

addBinary.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
class Solution:
2+
def addBinary(self, a: str, b: str) -> str:
3+
n1 = int(a,2)
4+
n2 = int(b,2)
5+
numSum = n1 + n2
6+
return bin(numSum)[2:]
7+
8+
s = Solution()
9+
print(s.addBinary("010101001","0100100101"))

addTwoNumbers.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
7+
''' Not the cleanest approach, but in-place code,
8+
the sum is overwritten in 2nd LinkedList
9+
Runtime was 60 ms, faster than 96.68% of Python3 online submission'''
10+
11+
class Solution:
12+
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
13+
ans = l2
14+
carry = 0
15+
inL1 = False
16+
while(l1 and l2):
17+
curr1 = l1.val
18+
curr2 = l2.val
19+
prev1 = l1
20+
prev2 = l2
21+
if(curr1 + curr2 + carry) == 10:
22+
l2.val = 0
23+
elif (curr1 + curr2 + carry) > 10:
24+
l2.val = curr1 + curr2 - 10 + carry
25+
else:
26+
l2.val = curr1 + curr2 + carry
27+
l1 = l1.next
28+
l2 = l2.next
29+
carry = int((curr1 + curr2 + carry) / 10)
30+
31+
# the last element of the shorter list is pointed towards the element after the last
32+
# one of the bigger list and the summation is continued there
33+
if(l1):
34+
prev2.next = l1
35+
else:
36+
prev1.next = l2
37+
while(l1):
38+
inL1 = True
39+
prev1 = l1
40+
tot = l1.val + carry
41+
l1.val = (tot)%10
42+
carry = int(tot / 10)
43+
l1 = l1.next
44+
while(l2):
45+
prev2 = l2
46+
tot = l2.val + carry
47+
l2.val = (tot)%10
48+
carry = int(tot / 10)
49+
l2 = l2.next
50+
51+
if(carry == 1):
52+
if(inL1):
53+
prev1.next = ListNode(1)
54+
else:
55+
prev2.next = ListNode(1)
56+
57+
58+
return ans
59+

allConstruct-dp.py

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# allConstruct
2+
# from dynamic programming video YT
3+
# https://www.youtube.com/watch?v=oBt53YbR9Kk&t=11470s
4+
# Timestamp: 05:10:01
5+
6+
7+
# ------------------ i guess this is top down approach ----------------------
8+
ansFin = []
9+
def allConstruct(target, wordBank, currList = []):
10+
11+
if target == '':
12+
return True
13+
14+
for currWord in wordBank:
15+
if(target.startswith(currWord)):
16+
currList += [currWord]
17+
remainingTarget = target[len(currWord):]
18+
res = allConstruct(remainingTarget, wordBank, currList)
19+
if res == True:
20+
ansFin.append(currList.copy())
21+
currList.pop()
22+
23+
24+
allConstruct('abcdef', ['ab', 'cd', 'cde', 'ef', 'def', 'abcd', 'f'])
25+
# allConstruct('purple', ['purp', 'p', 'ur', 'le', 'purpl'])
26+
# allConstruct('happ', ['cat', 'p', 'dog', 'le', 'mouse']) # this should give [[]] but gives []
27+
print(ansFin)
28+
29+
30+
# ------------ approach in the video ----------------------------------------------
31+
# this gives the o/p, but return early hence only gives one occurance
32+
# not all
33+
34+
ansFin = []
35+
def allConstruct(target, wordBank):
36+
if target == '':
37+
return []
38+
currList = []
39+
for currWord in wordBank:
40+
if(target.startswith(currWord)):
41+
remainingTarget = target[len(currWord):]
42+
res = allConstruct(remainingTarget, wordBank)
43+
44+
if res is not None:
45+
currList += [currWord] + res
46+
return currList
47+
print(ansFin)
48+
ansFin.append(currList)
49+
50+
print('ths gives one occurance only coz of early return')
51+
print(allConstruct('abcdef', ['ab', 'cd', 'cde', 'ef', 'def', 'abcd', 'f']))
52+
# print(ansFin)
53+
54+
55+
#----------------- from gemini and this works -_- --------------------------------------
56+
# without DP
57+
# check the explaination in the chat: https://g.co/gemini/share/479ee118861d
58+
59+
60+
def allConstruct(target, wordBank):
61+
if target == "":
62+
return [[]] # Base case: empty target has one combination (the empty list)
63+
64+
all_combinations = []
65+
for word in wordBank:
66+
if target.startswith(word):
67+
remaining = target[len(word):]
68+
remaining_combinations = allConstruct(remaining, wordBank)
69+
for combo in remaining_combinations:
70+
all_combinations.append([word] + combo)
71+
print(all_combinations)
72+
73+
return all_combinations
74+
75+
result = allConstruct('abcdef', ['ab', 'cd', 'cde', 'ef', 'def', 'abcd', 'f'])
76+
print(result)
77+
78+
79+
# ----------------- gemini solution with DP --------------------------
80+
81+
def allConstruct(target, wordBank, memo=None):
82+
if memo is None:
83+
memo = {} # Initialize memoization dictionary
84+
85+
if target == "":
86+
return [[]] # Base case: empty target has one combination (the empty list)
87+
88+
if target in memo:
89+
return memo[target] # Use memoized result if available
90+
91+
all_combinations = []
92+
for word in wordBank:
93+
if target.startswith(word):
94+
remaining = target[len(word):]
95+
remaining_combinations = allConstruct(remaining, wordBank, memo)
96+
for combo in remaining_combinations:
97+
all_combinations.append([word] + combo) # Add current word to each combination
98+
99+
memo[target] = all_combinations # Store result for memoization
100+
return all_combinations
101+
102+
# result = allConstruct('aaaaaa', ['a', 'aaa', 'aaaa', 'aaaaaa'])
103+
# print(result)

avoidScreen.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
## This script will simulate a keypress and prevent Windows from locking
2+
3+
import pyautogui
4+
import time
5+
6+
def no_lock(button):
7+
try:
8+
print ('Press CTRL+C to stop.')
9+
while True:
10+
pyautogui.press(button) # Key pressed
11+
time.sleep(2)
12+
13+
except Exception as ex:
14+
print ('no_lock | Error: ', ex)
15+
16+
def main():
17+
try:
18+
print ('\nPrevent Windows screenlock')
19+
kb_button = str(input('Enter keyboard button: '))
20+
21+
print ('\nRunning')
22+
no_lock(kb_button)
23+
24+
except KeyboardInterrupt:
25+
print('\nStopped')
26+
27+
except Exception as ex:
28+
print ('main | Error: ', ex)
29+
30+
if __name__ == "__main__":
31+
main()

0 commit comments

Comments
 (0)