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
3 changes: 3 additions & 0 deletions python/leetcode/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# leetcodesoln
This repository contains list of Leetcode[https://leetcode.com] solutions to their problems categorized by difficulties i.e easy, medium and hard.

26 changes: 26 additions & 0 deletions python/leetcode/easy/buy_sell_stock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import sys

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
min_price = sys.maxsize
max_profit = 0

for price in prices:

if price<min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price


return max_profit


if __name__ == "__main__":

prices = [7,1,5,3,6,4]
print(Solution().maxProfit(prices))
41 changes: 41 additions & 0 deletions python/leetcode/easy/buy_sell_stock_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import sys

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""

i = 0
valley = prices[0]
peak = prices[0]
max_profit = 0

while i < (len(prices)-1):

while (i<(len(prices)-1) and prices[i] >= prices[i+1]):

i += 1
print("valley",i)
valley = prices[i]

while (i<(len(prices)-1) and prices[i] <= prices[i+1]):

i += 1

peak = prices[i]


print("valley andpeak",valley,peak)

max_profit += peak - valley


return max_profit


if __name__ == "__main__":

prices = [7,1,5,3,6,4]
print(Solution().maxProfit(prices))
24 changes: 24 additions & 0 deletions python/leetcode/easy/buy_sell_stock_3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import sys

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""

i = 0
valley = prices[0]
peak = prices[0]
max_profit = 0

for i in range(1,len(prices)-1):

if prices[i+1] > prices[i]:
max_profit += prices[i+1]-prices[i]
return max_profit

if __name__ == "__main__":

prices = [7,1,5,3,6,4]
print(Solution().maxProfit(prices))
14 changes: 14 additions & 0 deletions python/leetcode/easy/climbing_stairs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Solution:
def climbStairs(self, n: int) -> int:
if n==1:
return 1
dp = [0] * (n+1)
dp[1] = 1
dp[2] = 2
for i in range(3,n+1):
dp[i] = dp[i-1] + dp[i-2]

return dp[n]

if __name__ == "__main__":
print(Solution().climbStairs(6))
20 changes: 20 additions & 0 deletions python/leetcode/easy/depth_btree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def maxDepth(self, root: TreeNode) -> int:
left = 0
right =0
org = root
while root.left is not None:
root = root.left
left +=1
while org.right is not None:
org = org.left
right +=1

return max(left,right)
26 changes: 26 additions & 0 deletions python/leetcode/easy/excel_sheet_col.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import string

class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
converter = [chr(x) for x in range(ord('A'), ord('Z')+1)]
if n == 0 or n is None:
return None
ret_str = ""
while n > 26:
to_append = n % 26
n = n // 26
if to_append == 0:
n -= 1
ret_str = converter[to_append - 1] + ret_str
if n > 0:
ret_str = converter[n - 1] + ret_str
return ret_str


if __name__ == "__main__":
for i in range(700,800):
print(i,Solution().convertToTitle(i))
47 changes: 47 additions & 0 deletions python/leetcode/easy/excel_sheet_col_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import string

class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
converter = [chr(x) for x in range(ord('A'), ord('Z')+1)]
if n == 0 or n is None:
return None
ret_str = ""
while n > 26:
to_append = n % 26
n = n // 26
if to_append == 0:
n -= 1
ret_str = converter[to_append - 1] + ret_str
if n > 0:
ret_str = converter[n - 1] + ret_str
return ret_str

def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""

alphas = list(string.ascii_uppercase)
alphas_dict = {v:i+1 for i,v in enumerate(alphas)}

value = 0
for i in range(len(s)):
if i==len(s)-1:
value+=alphas_dict[s[i]]
else:
value +=26 ** (len(s)-1-i)*alphas_dict[s[i]]

return value



if __name__ == "__main__":
# for i in range(25,1000):
# print(i,Solution().convertToTitle(i),Solution().titleToNumber(Solution().convertToTitle(i)))

print(Solution().titleToNumber('BA'))
28 changes: 28 additions & 0 deletions python/leetcode/easy/factorial_zero.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from collections import Counter
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
if n<5:
return 0
x=0
while n != 0:
x += n // 5
n //= 5
print(x,n)

return x

def factorial(self,n):
fact = 1
for i in reversed(range(1,n+1)):
fact = fact*i

return fact



if __name__ == "__main__":
print(Solution().trailingZeroes(10))
58 changes: 58 additions & 0 deletions python/leetcode/easy/is_same_tree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
'''
Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input: 1 1
/ \ / \
2 3 2 3

[1,2,3], [1,2,3]

Output: true
Example 2:

Input: 1 1
/ \
2 2

[1,2], [1,null,2]

Output: false
Example 3:

Input: 1 1
/ \ / \
2 1 1 2

[1,2,1], [1,1,2]

Output: false
'''

# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
# p and q are both None
if not p and not q:
return True
# one of p and q is None
if not q or not p:
return False
if p.val != q.val:
return False
return self.isSameTree(p.right, q.right) and \
self.isSameTree(p.left, q.left)
36 changes: 36 additions & 0 deletions python/leetcode/easy/lcs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""

if not strs:return ''

return self.longest_prefix(strs,0,len(strs)-1)

def longest_prefix(self,strs,l,r):

if l==r:
return strs[l]
else:
mid = (l+r)//2
print(mid)
lcp_left = self.longest_prefix(strs,l,mid)
lcp_right = self.longest_prefix(strs,mid+1,r)
print(lcp_left,lcp_right)
return self.common_prefix(lcp_left,lcp_right)

def common_prefix(self,left,right):

mi = min(len(left),len(right))

for i in range(mi):
if left[i] != right[i]:
return left[0:i]
return left[0:mi]

if __name__ == "__main__":
a = ['leetcode','leet','lee','le']
b= ['a','a','b']
print(Solution().longestCommonPrefix(a))
34 changes: 34 additions & 0 deletions python/leetcode/easy/linked_list_cycle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None

class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""

if head is None or head.next is None:
return False

slow = head
fast = head.next

while slow != fast:
if fast is None or fast.next is None:
return False

slow = slow.next
fast = fast.next.next


return True


if __name__ == "__main__":
a = [3,2,0,-4]

print(Solution().hasCycle(a))
16 changes: 16 additions & 0 deletions python/leetcode/easy/majority_elem.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from collections import Counter
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
counter = Counter(nums)
counter = dict(counter)

for k in counter:
if counter[k] > len(nums)/2:
return k

if __name__ == "__main__":
print(Solution().majorityElement([1,1,1,2,3,3,3,3,3]))
Loading