diff --git a/python/leetcode/README.md b/python/leetcode/README.md new file mode 100644 index 0000000..2fab9ff --- /dev/null +++ b/python/leetcode/README.md @@ -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. + diff --git a/python/leetcode/easy/buy_sell_stock.py b/python/leetcode/easy/buy_sell_stock.py new file mode 100644 index 0000000..e528c70 --- /dev/null +++ b/python/leetcode/easy/buy_sell_stock.py @@ -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 max_profit: + max_profit = price - min_price + + + return max_profit + + +if __name__ == "__main__": + + prices = [7,1,5,3,6,4] + print(Solution().maxProfit(prices)) \ No newline at end of file diff --git a/python/leetcode/easy/buy_sell_stock_2.py b/python/leetcode/easy/buy_sell_stock_2.py new file mode 100644 index 0000000..7ae173e --- /dev/null +++ b/python/leetcode/easy/buy_sell_stock_2.py @@ -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)) \ No newline at end of file diff --git a/python/leetcode/easy/buy_sell_stock_3.py b/python/leetcode/easy/buy_sell_stock_3.py new file mode 100644 index 0000000..fbcc030 --- /dev/null +++ b/python/leetcode/easy/buy_sell_stock_3.py @@ -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)) \ No newline at end of file diff --git a/python/leetcode/easy/climbing_stairs.py b/python/leetcode/easy/climbing_stairs.py new file mode 100644 index 0000000..9f2523c --- /dev/null +++ b/python/leetcode/easy/climbing_stairs.py @@ -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)) \ No newline at end of file diff --git a/python/leetcode/easy/depth_btree.py b/python/leetcode/easy/depth_btree.py new file mode 100644 index 0000000..7e3e118 --- /dev/null +++ b/python/leetcode/easy/depth_btree.py @@ -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) \ No newline at end of file diff --git a/python/leetcode/easy/excel_sheet_col.py b/python/leetcode/easy/excel_sheet_col.py new file mode 100644 index 0000000..9300680 --- /dev/null +++ b/python/leetcode/easy/excel_sheet_col.py @@ -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)) \ No newline at end of file diff --git a/python/leetcode/easy/excel_sheet_col_2.py b/python/leetcode/easy/excel_sheet_col_2.py new file mode 100644 index 0000000..6675501 --- /dev/null +++ b/python/leetcode/easy/excel_sheet_col_2.py @@ -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')) \ No newline at end of file diff --git a/python/leetcode/easy/factorial_zero.py b/python/leetcode/easy/factorial_zero.py new file mode 100644 index 0000000..35b0264 --- /dev/null +++ b/python/leetcode/easy/factorial_zero.py @@ -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)) \ No newline at end of file diff --git a/python/leetcode/easy/is_same_tree.py b/python/leetcode/easy/is_same_tree.py new file mode 100644 index 0000000..6601613 --- /dev/null +++ b/python/leetcode/easy/is_same_tree.py @@ -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) \ No newline at end of file diff --git a/python/leetcode/easy/lcs.py b/python/leetcode/easy/lcs.py new file mode 100644 index 0000000..2bf9c63 --- /dev/null +++ b/python/leetcode/easy/lcs.py @@ -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)) \ No newline at end of file diff --git a/python/leetcode/easy/linked_list_cycle.py b/python/leetcode/easy/linked_list_cycle.py new file mode 100644 index 0000000..d5f5331 --- /dev/null +++ b/python/leetcode/easy/linked_list_cycle.py @@ -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)) \ No newline at end of file diff --git a/python/leetcode/easy/majority_elem.py b/python/leetcode/easy/majority_elem.py new file mode 100644 index 0000000..57465f8 --- /dev/null +++ b/python/leetcode/easy/majority_elem.py @@ -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])) \ No newline at end of file diff --git a/python/leetcode/easy/max_subarray.py b/python/leetcode/easy/max_subarray.py new file mode 100644 index 0000000..95bb796 --- /dev/null +++ b/python/leetcode/easy/max_subarray.py @@ -0,0 +1,13 @@ +""" +Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. + +""" +class Solution: + def maxSubArray(self, nums: list) -> int: + for i in range(1, len(nums)): + if nums[i-1] > 0: + nums[i] += nums[i-1] + return max(nums) + +if __name__ == "__main__": + print(Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4])) \ No newline at end of file diff --git a/python/leetcode/easy/max_swap.py b/python/leetcode/easy/max_swap.py new file mode 100644 index 0000000..34d3d5c --- /dev/null +++ b/python/leetcode/easy/max_swap.py @@ -0,0 +1,31 @@ +class Solution(object): + def maximumSwap(self, num): + """ + :type num: int + :rtype: int + """ + A = list(map(int, str(num))) + last = {x: i for i, x in enumerate(A)} + + print(last) + for i, x in enumerate(A): + for d in range(9, x, -1): + if last.get(d, -1) > i: + print(last[d]) + A[i], A[last[d]] = A[last[d]], A[i] + return int("".join(map(str, A))) + return num + + def max_swap_naive(self,num): + A = list(map(int, str(num))) + + for i in range(len(A)): + for j in range(1,len(A)): + if A[i] int: + for index,i in enumerate(nums): + print(index,i,val) + if i == val: + nums.remove(i) + + return len(nums),nums + + + +if __name__ == "__main__": + nums = [0,1,2,2,3,0,4,2] + print(nums) + print(removeElement(nums,2)) \ No newline at end of file diff --git a/python/leetcode/easy/palindrome.py b/python/leetcode/easy/palindrome.py new file mode 100644 index 0000000..1fb6036 --- /dev/null +++ b/python/leetcode/easy/palindrome.py @@ -0,0 +1,9 @@ +''' +Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. +''' +class Solution: + def isPalindrome(self, x: int) -> bool: + if x<0: + return False + else: + return list(str(x)) == list(reversed(list(str(x)))) \ No newline at end of file diff --git a/python/leetcode/easy/plus_one.py b/python/leetcode/easy/plus_one.py new file mode 100644 index 0000000..811fd20 --- /dev/null +++ b/python/leetcode/easy/plus_one.py @@ -0,0 +1,14 @@ +class Solution: + def plusOne(self, digits: list) -> list: + d ='' + digits = list(map(lambda x:str(x), digits)) + d = d.join(digits) + + result =list(map(lambda x:int(x),list(str(int(d)+1)))) + + return result + +if __name__ == "__main__": + + a = [1,2,3] + print(Solution().plusOne(a)) \ No newline at end of file diff --git a/python/leetcode/easy/remove_duplicates.py b/python/leetcode/easy/remove_duplicates.py new file mode 100644 index 0000000..8fb819c --- /dev/null +++ b/python/leetcode/easy/remove_duplicates.py @@ -0,0 +1,26 @@ +""" +Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. + +Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. +""" +class Solution: + def removeDuplicates(self, nums: list) -> int: + if len(nums)==0: + return 0 + i = 0 + + for j in range(1,len(nums)): + if nums[j] !=nums[i]: + i+=1 + nums[i] = nums[j] + + print(nums) + + return i+1,nums + + +if __name__ == "__main__": + nums = [0,0,1,1,2] + + solution = Solution() + print(solution.removeDuplicates(nums)) \ No newline at end of file diff --git a/python/leetcode/easy/remove_duplicates_sorted_list.py b/python/leetcode/easy/remove_duplicates_sorted_list.py new file mode 100644 index 0000000..2798e38 --- /dev/null +++ b/python/leetcode/easy/remove_duplicates_sorted_list.py @@ -0,0 +1,30 @@ +''' +Given a sorted linked list, delete all duplicates such that each element appear only once. + +Example 1: + +Input: 1->1->2 +Output: 1->2 +Example 2: + +Input: 1->1->2->3->3 +Output: 1->2->3 +''' +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + current = head + + while current is not None and current.next is not None: + if current.next.val == current.val: + current.next = current.next.next + else: + current = current.next + + return head + diff --git a/python/leetcode/easy/remove_element.py b/python/leetcode/easy/remove_element.py new file mode 100644 index 0000000..17f3caf --- /dev/null +++ b/python/leetcode/easy/remove_element.py @@ -0,0 +1,25 @@ +""" +Given an array nums and a value val, remove all instances of that value in-place and return the new length. + +Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. + +The order of elements can be changed. It doesn't matter what you leave beyond the new length. +""" +class Solution: + def removeElement(self, nums: list, val: int) -> int: + i = 0 + for j in range(0,len(nums)): + print(i,j) + if nums[j] != val: + nums[i] = nums[j] + i +=1 + + + return i + + + +if __name__ == "__main__": + nums = [0,1,2,2,3,0,4,2] + soln = Solution() + print(soln.removeElement(nums,2)) \ No newline at end of file diff --git a/python/leetcode/easy/roman_to_integer.py b/python/leetcode/easy/roman_to_integer.py new file mode 100644 index 0000000..b15552d --- /dev/null +++ b/python/leetcode/easy/roman_to_integer.py @@ -0,0 +1,66 @@ +''' +Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. + +Symbol Value +I 1 +V 5 +X 10 +L 50 +C 100 +D 500 +M 1000 +For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. + +Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: + +I can be placed before V (5) and X (10) to make 4 and 9. +X can be placed before L (50) and C (100) to make 40 and 90. +C can be placed before D (500) and M (1000) to make 400 and 900. +Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. +''' +class Solution: + def value(self,r): + if (r == 'I'): + return 1 + if (r == 'V'): + return 5 + if (r == 'X'): + return 10 + if (r == 'L'): + return 50 + if (r == 'C'): + return 100 + if (r == 'D'): + return 500 + if (r == 'M'): + return 1000 + return -1 + + def romanToInt(self, s: str) -> int: + inputs = list(s) + + result = 0 + i = 0 + + while i< len(s): + # getting value of current item + s1 = self.value(s[i]) + + if i+1 < len(s): + # getting value of next item + s2 = self.value(s[i+1]) + + # if value of current item is lesser or equal add it is + if s1>=s2: + result = result + s1 + i +=1 + # else add the next item and deduct current item + else: + result = result + s2 -s1 + i +=2 + + else: + result = result + s1 + i += 1 + + return result \ No newline at end of file diff --git a/python/leetcode/easy/search_insert.py b/python/leetcode/easy/search_insert.py new file mode 100644 index 0000000..1ff7c18 --- /dev/null +++ b/python/leetcode/easy/search_insert.py @@ -0,0 +1,31 @@ +''' +Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. + +You may assume no duplicates in the array. +''' + +class Solution: + def searchInsert(self, nums: list, target: int) -> int: + if target in nums: + return nums.index(target) + elif len(nums)==1: + if target int: + return int(x**(1/2)) \ No newline at end of file diff --git a/python/leetcode/easy/symmetric_tree.py b/python/leetcode/easy/symmetric_tree.py new file mode 100644 index 0000000..91a6a7d --- /dev/null +++ b/python/leetcode/easy/symmetric_tree.py @@ -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 isSymmetric(self, root: TreeNode) -> bool: + return self.isMirror(root,root) + + + def isMirror(self, root1:TreeNode, root2: TreeNode)->bool: + + if root1 is None and root2 is None: + return True + if root1 is None or root2 is None: + return False + + return root1.val==root2.val and isMirror(root1.left,root2.right) and isMirror(root1.right,root2.left) \ No newline at end of file diff --git a/python/leetcode/easy/two_sums.py b/python/leetcode/easy/two_sums.py new file mode 100644 index 0000000..88cce82 --- /dev/null +++ b/python/leetcode/easy/two_sums.py @@ -0,0 +1,13 @@ +''' +Given an array of integers, return indices of the two numbers such that they add up to a specific target. + +You may assume that each input would have exactly one solution, and you may not use the same element twice. +''' +class Solution: + def twoSum(self, nums: list, target: int) -> list: + + for i in range(len(nums)): + + x= target - nums[i] + if x in nums and nums.index(x)!=i: + return [i,nums.index(x)] \ No newline at end of file diff --git a/python/leetcode/easy/valid_palindrome.py b/python/leetcode/easy/valid_palindrome.py new file mode 100644 index 0000000..d30db67 --- /dev/null +++ b/python/leetcode/easy/valid_palindrome.py @@ -0,0 +1,29 @@ +import re + +class Solution(object): + def isPalindrome(self, s): + """ + :type s: str + :rtype: bool + """ + one_string = "" + for x in s: + if x.isalpha() or x.isdigit(): + one_string += x + + + one_string = one_string.lower() + + print(one_string,one_string[::-1]) + + if one_string == one_string[::-1]: + return True + else: + return False + + + +if __name__ == "__main__": + + + print(Solution().isPalindrome("a race:_&cara")) \ No newline at end of file diff --git a/python/leetcode/easy/valid_perfect_square.py b/python/leetcode/easy/valid_perfect_square.py new file mode 100644 index 0000000..0804616 --- /dev/null +++ b/python/leetcode/easy/valid_perfect_square.py @@ -0,0 +1,7 @@ +''' +Given a positive integer num, write a function which returns True if num is a perfect square else False. +''' +class Solution: + def isPerfectSquare(self, num: int) -> bool: + x= num**0.5 + return float(x).is_integer() \ No newline at end of file