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

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Python/best-time-to-buy-sell-stock-i.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'''
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
'''
#using Two-Ptrs

class Solution:
def maxProfit(self, prices: List[int]) -> int:
l,r=0,1 #left ptr=buy, right ptr=sell
maxP=0

while r<len(prices):
if prices[l]<prices[r]:
profit=prices[r]-prices[l]
maxP=max(maxP,profit) #only updates if the current profit is higher
else:
l=r
r+=1
return maxP
25 changes: 25 additions & 0 deletions Python/merge-sorted-arrays.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'''
https://leetcode.com/problems/merge-sorted-array/
'''

class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
last = m + n - 1 #this will be the last index of nums1

# m - 1 = this will be the last of actual elements in nums1 before 0 elems starts
# n - 1 = this will be the last of n

# merge in reverse order
while m > 0 and n > 0: #m and n are ptrs
if nums1[m - 1] > nums2[n - 1]:
nums1[last] = nums1[m - 1]
m -= 1 #decrementing as merging in reverse
else:
nums1[last] = nums2[n -1]
n -= 1
last -= 1

# filling num1 with leftover num2 elements
while n > 0:
nums1[last] = nums2[n - 1]
n, last = n -1, last - 1
43 changes: 43 additions & 0 deletions Python/valid-anagram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
'''https://leetcode.com/problems/valid-anagram/'''
#brute
'''We keep count of every distinct character in a hashmap for both S & T.
Then compare if the count for each character in both is equal'''
from typing import Counter


class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s)!=len(t):
return False
S,T={},{}
for i in range(0,len(s)):
if s[i] in S.keys():
S[s[i]]+=1 #updating count
else:
S[s[i]]=1 #recording a distinct element

for i in range(0,len(t)):
if t[i] in T.keys():
T[t[i]]+=1
else:
T[t[i]]=1

for i in range(0,len(t)):
if t[i] in S.keys() and S[t[i]]==T[t[i]]:
continue
else:
return False
return True

#cocky way 1
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s)==Counter(t) #compares the count of every distinct element

#optimised in cocky way
'''We sort both the strings and compare them side by side.
Note that It is only space efficient but the one b4 is time efficient
also your interviewer may want you to write your own sort function for this'''
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s)==sorted(t)