├── merge2sortedlist ├── problem.txt └── solution.py ├── lexicographical numbers ├── problem.txt └── solution.py ├── Generate Parenthesis ├── problem.txt └── solution.py ├── inordertraversal ├── problem.txt └── solution.py ├── permutations ├── permutations.py └── README.md ├── Longest Palindromic Substring ├── problem.txt └── solution.py ├── maximumSubarray ├── solution.py └── problem.txt ├── jumpgame ├── solution.py └── problem.txt ├── README.md ├── rightSideView ├── problem.txt └── solution.py ├── N Queens ├── problem.txt └── solution.py ├── uniqChar ├── README.md └── uniqChar.py ├── kthlargestelement ├── problem.txt ├── Longest common subsequence │ ├── solution.py │ └── problem.txt └── solution.py ├── uglynumber2 ├── problems.txt └── uglynumber.py ├── bestsightseeingpair ├── solution.py └── problem.txt ├── uniquepaths ├── solution.py └── problem.txt ├── minimumTimeDifference ├── problem.txt └── solution.py ├── permutationsInString ├── problem.txt └── solution.py ├── arithmeticProgressionFromSequence ├── solution.py └── problem.txt ├── contains duplicate 2 ├── problem.txt └── solution.py ├── reverseInt ├── README.md └── reverseInt.py ├── ReverseString ├── solution.py └── problem.txt ├── Longest Substring Without Repeating Characters ├── solution.py └── problem.txt ├── partitionToKSubsets ├── problem.txt └── solution.py ├── carfleet ├── solution.py └── problem.txt ├── findfirstandlastposition ├── problem.txt └── solution.py ├── fractiontoreocurringdecimal ├── problem.txt └── solution.py ├── rangeSumQueryImmutable ├── problem.txt └── solution.py ├── decodeways ├── solution.py └── problem.txt ├── FIZZBUZZ ├── solution.py └── problem.txt ├── Two Sum ├── README.md └── twoSum.py ├── mergeIntervals ├── problem.txt └── solution.py ├── RangeSumOfBST ├── problem.txt └── solution.py ├── FindKClosestElements ├── problem.txt └── solution.py ├── palindromPermutation ├── README.md └── palindromPermutation.py ├── SearchInRotatedSortedArray ├── problem.txt └── solution.py ├── PartitionArrayInto3PartsWithEqualSum ├── solution.py └── problem.txt ├── longestArithmeticSubsequenceForGivenDiff ├── solution.py └── problem.txt ├── longestarithmeticsequence ├── solution.py └── problems.txt ├── oneAwayEdit ├── README.md └── oneAwayEdit.py ├── ContainerWithMostWater ├── problem.txt └── solution.py ├── Median of 2 sorted arrays ├── README.md └── median.py ├── HandOfStraight ├── problem.txt └── solution.py ├── deleteNodesAndReturnForest ├── problem.txt └── solution.py ├── validBST ├── problem.txt └── solution.py ├── splitArrayIntoConsecutive ├── problem.txt └── solution.py ├── subtreeOfAnotherTree ├── problem.txt └── solution.py ├── SerializeAndDeserializeBST ├── problem.txt └── solution.py ├── boatsToSavePeople ├── problem.txt └── solution.py ├── BinaryTreeCompleteness ├── problem.txt └── solution.py ├── Binarywatch ├── problem.txt └── solution.py ├── stringToIntegar ├── atoi.py └── README.md ├── decodeString ├── README.md └── decodeString.py ├── constructTreeFromString ├── solution.py └── problem.txt ├── minStack ├── problem.txt └── solution.py ├── countandsay ├── solution.py └── problem.txt ├── divideArrayInSetsOfKConsecutiveNumbers ├── problem.txt └── solution.py ├── flipEquivalentBinaryTree ├── problem.txt └── solution.py ├── maximumWidthOfBinaryTree ├── solution.py └── problem.txt ├── insertdeletegetrandom ├── problem.txt └── solution.py ├── verifyAlienDIctionary ├── solution.py └── problem.txt └── reorderroutetomakepathleadtozero ├── problem.txt └── solution.py /merge2sortedlist/problem.txt: -------------------------------------------------------------------------------- 1 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 2 | 3 | Example: 4 | 5 | Input: 1->2->4, 1->3->4 6 | Output: 1->1->2->3->4->4 7 | -------------------------------------------------------------------------------- /lexicographical numbers/problem.txt: -------------------------------------------------------------------------------- 1 | Given an integer n, return 1 - n in lexicographical order. 2 | 3 | For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. 4 | 5 | Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000. -------------------------------------------------------------------------------- /Generate Parenthesis/problem.txt: -------------------------------------------------------------------------------- 1 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 2 | 3 | For example, given n = 3, a solution set is: 4 | 5 | [ 6 | "((()))", 7 | "(()())", 8 | "(())()", 9 | "()(())", 10 | "()()()" 11 | ] 12 | -------------------------------------------------------------------------------- /inordertraversal/problem.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree, return the inorder traversal of its nodes' values. 2 | 3 | Example: 4 | 5 | Input: [1,null,2,3] 6 | 1 7 | \ 8 | 2 9 | / 10 | 3 11 | 12 | Output: [1,3,2] 13 | Follow up: Recursive solution is trivial, could you do it iteratively? 14 | -------------------------------------------------------------------------------- /permutations/permutations.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | def permutation(str1, str2): 4 | str1 = str1.strip() 5 | str2 = str2.strip() 6 | if len(str1) != len(str2): 7 | return False 8 | count_str1 = Counter(str1) 9 | count_str2 = Counter(str2) 10 | return count_str1 == count_str2 -------------------------------------------------------------------------------- /Longest Palindromic Substring/problem.txt: -------------------------------------------------------------------------------- 1 | Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 2 | 3 | Example 1: 4 | 5 | Input: "babad" 6 | Output: "bab" 7 | Note: "aba" is also a valid answer. 8 | Example 2: 9 | 10 | Input: "cbbd" 11 | Output: "bb" 12 | -------------------------------------------------------------------------------- /maximumSubarray/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | tempMax, maxSub = float('-inf'), float('-inf') 4 | for i in range(len(nums)): 5 | tempMax = max(tempMax + nums[i], nums[i]) 6 | maxSub = max(maxSub, tempMax) 7 | return maxSub 8 | -------------------------------------------------------------------------------- /jumpgame/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | if not nums: 4 | return False 5 | prevPath = nums[0] 6 | for i in range(1, len(nums)): 7 | if prevPath <= 0: 8 | return False 9 | prevPath = max(prevPath-1 , nums[i]) 10 | return True 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DESCRIPTION 2 | 3 | I created this repository to upload the various problems on Algorithms and Data structures I solved while preparing to take Technical Interviews in various companies for a Software Engineering Intern role. 4 | 5 | I hope this repository can also assist others who are in a similar position and are preparing to take a technical Interview or a coding exam. -------------------------------------------------------------------------------- /permutations/README.md: -------------------------------------------------------------------------------- 1 | # Permutations 2 | 3 | ## DESCRIPTION 4 | 5 | Check Permutation: Given two strings, write a method to decide if one is a permutation of the other 6 | 7 | 8 | ## Source 9 | [Cracking the Coding Interview](https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/0984782850/ref=sr_1_1?keywords=cracking+the+coding+interview&qid=1578002684&sr=8-1) -------------------------------------------------------------------------------- /rightSideView/problem.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. 2 | 3 | Example: 4 | 5 | Input: [1,2,3,null,5,null,4] 6 | Output: [1, 3, 4] 7 | Explanation: 8 | 9 | 1 <--- 10 | / \ 11 | 2 3 <--- 12 | \ \ 13 | 5 4 <--- 14 | -------------------------------------------------------------------------------- /N Queens/problem.txt: -------------------------------------------------------------------------------- 1 | The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. 2 | 3 | 4 | 5 | Given an integer n, return all distinct solutions to the n-queens puzzle. 6 | 7 | Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively. 8 | -------------------------------------------------------------------------------- /uniqChar/README.md: -------------------------------------------------------------------------------- 1 | # Unique Char 2 | 3 | ## DESCRIPTION 4 | 5 | Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? 6 | 7 | 8 | ## Source 9 | [Cracking the Coding Interview](https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/0984782850/ref=sr_1_1?keywords=cracking+the+coding+interview&qid=1578002684&sr=8-1) -------------------------------------------------------------------------------- /kthlargestelement/problem.txt: -------------------------------------------------------------------------------- 1 | Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 2 | 3 | Example 1: 4 | 5 | Input: [3,2,1,5,6,4] and k = 2 6 | Output: 5 7 | Example 2: 8 | 9 | Input: [3,2,3,1,2,4,5,5,6] and k = 4 10 | Output: 4 11 | Note: 12 | You may assume k is always valid, 1 ≤ k ≤ array's length. 13 | -------------------------------------------------------------------------------- /uglynumber2/problems.txt: -------------------------------------------------------------------------------- 1 | Write a program to find the n-th ugly number. 2 | 3 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 4 | 5 | Example: 6 | 7 | Input: n = 10 8 | Output: 12 9 | Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. 10 | Note: 11 | 12 | 1 is typically treated as an ugly number. 13 | n does not exceed 1690. -------------------------------------------------------------------------------- /bestsightseeingpair/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxScoreSightseeingPair(self, A: List[int]) -> int: 3 | 4 | # minimize distance 5 | # maximize sum 6 | 7 | m = M = 0 8 | 9 | n = len(A) 10 | for i in range(1,n): 11 | m = max(m, A[i-1] + i-1) 12 | M = max(M, m + A[i] - i) 13 | 14 | return M 15 | -------------------------------------------------------------------------------- /uniquepaths/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m: int, n: int) -> int: 3 | 4 | map = [[1 for j in range(m)]for i in range(n)] 5 | # print(map) 6 | for i in range(1, n): 7 | for j in range(1, m): 8 | map[i][j] = map[i-1][j] + map[i][j-1] 9 | # map[1][2] = 4 10 | 11 | # print(map) 12 | 13 | return map[n-1][m-1] 14 | 15 | -------------------------------------------------------------------------------- /minimumTimeDifference/problem.txt: -------------------------------------------------------------------------------- 1 | Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes difference between any two time points in the list. 2 | Example 1: 3 | Input: ["23:59","00:00"] 4 | Output: 1 5 | Note: 6 | The number of time points in the given list is at least 2 and won't exceed 20000. 7 | The input time is legal and ranges from 00:00 to 23:59. 8 | Accepted 9 | 52,164 10 | Submissions 11 | 101,047 -------------------------------------------------------------------------------- /maximumSubarray/problem.txt: -------------------------------------------------------------------------------- 1 | 2 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 3 | 4 | Example: 5 | 6 | Input: [-2,1,-3,4,-1,2,1,-5,4], 7 | Output: 6 8 | Explanation: [4,-1,2,1] has the largest sum = 6. 9 | Follow up: 10 | 11 | If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 12 | -------------------------------------------------------------------------------- /permutationsInString/problem.txt: -------------------------------------------------------------------------------- 1 | Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: s1 = "ab" s2 = "eidbaooo" 8 | Output: True 9 | Explanation: s2 contains one permutation of s1 ("ba"). 10 | Example 2: 11 | 12 | Input:s1= "ab" s2 = "eidboaoo" 13 | Output: False 14 | -------------------------------------------------------------------------------- /arithmeticProgressionFromSequence/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canMakeArithmeticProgression(self, arr: List[int]) -> bool: 3 | if not arr or len(arr) == 1: 4 | return True 5 | 6 | 7 | n = len(arr) 8 | arr = sorted(arr) 9 | 10 | diff = arr[1] - arr[0] 11 | for i in range(1,n): 12 | if arr[i] - arr[i-1] != diff: 13 | return False 14 | return True -------------------------------------------------------------------------------- /contains duplicate 2/problem.txt: -------------------------------------------------------------------------------- 1 | Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 2 | 3 | Example 1: 4 | 5 | Input: nums = [1,2,3,1], k = 3 6 | Output: true 7 | Example 2: 8 | 9 | Input: nums = [1,0,1,1], k = 1 10 | Output: true 11 | Example 3: 12 | 13 | Input: nums = [1,2,3,1,2,3], k = 2 14 | Output: false -------------------------------------------------------------------------------- /reverseInt/README.md: -------------------------------------------------------------------------------- 1 | # REVERSE INT 2 | 3 | ## DESCRIPTION 4 | 5 | Given a 32-bit signed integer, reverse digits of an integer. 6 | 7 | 8 | ### EXAMPLE 1 9 | 10 | ```BASH 11 | Input: 123 12 | Output: 321 13 | ``` 14 | ### EXAMPLE 2 15 | 16 | ```BASH 17 | Input: -123 18 | Output: -321 19 | ``` 20 | ### EXAMPLE 3 21 | 22 | ```BASH 23 | Input: 120 24 | Output: 21 25 | ``` 26 | 27 | 28 | ## Source 29 | [LEETCODE](https://leetcode.com/problems/reverse-integer/) -------------------------------------------------------------------------------- /ReverseString/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseString(self, s: List[str]) -> None: 3 | """ 4 | Do not return anything, modify s in-place instead. 5 | """ 6 | start = 0 7 | end = len(s) - 1 8 | 9 | while start <= end: 10 | # print((start,end)) 11 | s[start], s[end] = s[end], s[start] 12 | start += 1 13 | end -=1 14 | 15 | 16 | -------------------------------------------------------------------------------- /Longest Substring Without Repeating Characters/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | # s = "pwwkew" 4 | start, maxArr = 0, 0 5 | maxArr = 0 6 | a = {} 7 | for i in range(len(s)): 8 | if s[i] in a and a[s[i]] >= start: 9 | start = a[s[i]] + 1 10 | a[s[i]] = i 11 | maxArr = max(maxArr, i - start + 1) 12 | return maxArr 13 | -------------------------------------------------------------------------------- /partitionToKSubsets/problem.txt: -------------------------------------------------------------------------------- 1 | Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-empty subsets whose sums are all equal. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4 8 | Output: True 9 | Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums. 10 | 11 | 12 | Note: 13 | 14 | 1 <= k <= len(nums) <= 16. 15 | 0 < nums[i] < 10000. 16 | -------------------------------------------------------------------------------- /carfleet/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: 3 | cars = sorted(zip(position, speed)) 4 | times = [(target-pos)/speed for pos,speed in cars] 5 | ans = 0 6 | while len(times) > 1: 7 | lead = times.pop() 8 | if lead < times[-1]: 9 | ans += 1 10 | else: 11 | times[-1] = lead 12 | return ans + bool(times) -------------------------------------------------------------------------------- /findfirstandlastposition/problem.txt: -------------------------------------------------------------------------------- 1 | Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. 2 | 3 | Your algorithm's runtime complexity must be in the order of O(log n). 4 | 5 | If the target is not found in the array, return [-1, -1]. 6 | 7 | Example 1: 8 | 9 | Input: nums = [5,7,7,8,8,10], target = 8 10 | Output: [3,4] 11 | Example 2: 12 | 13 | Input: nums = [5,7,7,8,8,10], target = 6 14 | Output: [-1,-1] 15 | 16 | -------------------------------------------------------------------------------- /fractiontoreocurringdecimal/problem.txt: -------------------------------------------------------------------------------- 1 | Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. 2 | 3 | If the fractional part is repeating, enclose the repeating part in parentheses. 4 | 5 | Example 1: 6 | 7 | Input: numerator = 1, denominator = 2 8 | Output: "0.5" 9 | Example 2: 10 | 11 | Input: numerator = 2, denominator = 1 12 | Output: "2" 13 | Example 3: 14 | 15 | Input: numerator = 2, denominator = 3 16 | Output: "0.(6)" 17 | -------------------------------------------------------------------------------- /rangeSumQueryImmutable/problem.txt: -------------------------------------------------------------------------------- 1 | Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 2 | 3 | Example: 4 | 5 | Given nums = [-2, 0, 3, -5, 2, -1] 6 | 7 | sumRange(0, 2) -> 1 8 | sumRange(2, 5) -> -1 9 | sumRange(0, 5) -> -3 10 | 11 | 12 | Constraints: 13 | 14 | You may assume that the array does not change. 15 | There are many calls to sumRange function. 16 | 0 <= nums.length <= 10^4 17 | -10^5 <= nums[i] <= 10^5 18 | 0 <= i <= j < nums.length -------------------------------------------------------------------------------- /decodeways/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numDecodings(self, s: str) -> int: 3 | # s = '22106' 4 | dp = [0] * (len(s) + 1) 5 | dp[0] = 1 6 | for i in range(1, len(s) + 1): 7 | if i > 1 and 0 < (int(s[i-1]) + int(s[i-2]) * 10) <= 26 and s[i-2] != '0': 8 | dp[i] += dp[i-2] 9 | 10 | if s[i-1] != '0': 11 | dp[i] += dp[i-1] 12 | 13 | 14 | return dp[len(s)] 15 | 16 | -------------------------------------------------------------------------------- /FIZZBUZZ/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fizzBuzz(self, n: int) -> List[str]: 3 | 4 | out = [] 5 | for i in range(1,n+1): 6 | if not i % 3 and not i % 5: 7 | out.append('FizzBuzz') 8 | elif not i % 3: 9 | out.append('Fizz') 10 | elif not i % 5: 11 | out.append('Buzz') 12 | else: 13 | out.append(str(i)) 14 | 15 | return out 16 | 17 | -------------------------------------------------------------------------------- /Two Sum/README.md: -------------------------------------------------------------------------------- 1 | # Two sum 2 | 3 | ## DESCRIPTION 4 | 5 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 6 | 7 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 8 | 9 | 10 | ### EXAMPLE 11 | 12 | ```BASH 13 | Given nums = [2, 7, 11, 15], target = 9, 14 | 15 | Because nums[0] + nums[1] = 2 + 7 = 9, 16 | return [0, 1]. 17 | ``` 18 | 19 | 20 | 21 | ## License 22 | [LEETCODE](https://leetcode.com/problems/two-sum/) -------------------------------------------------------------------------------- /decodeways/problem.txt: -------------------------------------------------------------------------------- 1 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 2 | 3 | 'A' -> 1 4 | 'B' -> 2 5 | ... 6 | 'Z' -> 26 7 | Given a non-empty string containing only digits, determine the total number of ways to decode it. 8 | 9 | Example 1: 10 | 11 | Input: "12" 12 | Output: 2 13 | Explanation: It could be decoded as "AB" (1 2) or "L" (12). 14 | Example 2: 15 | 16 | Input: "226" 17 | Output: 3 18 | Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). 19 | -------------------------------------------------------------------------------- /mergeIntervals/problem.txt: -------------------------------------------------------------------------------- 1 | Given a collection of intervals, merge all overlapping intervals. 2 | 3 | Example 1: 4 | 5 | Input: [[1,3],[2,6],[8,10],[15,18]] 6 | Output: [[1,6],[8,10],[15,18]] 7 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 8 | Example 2: 9 | 10 | Input: [[1,4],[4,5]] 11 | Output: [[1,5]] 12 | Explanation: Intervals [1,4] and [4,5] are considered overlapping. 13 | NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature. 14 | -------------------------------------------------------------------------------- /reverseInt/reverseInt.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x: int) -> int: 3 | if x == 0: 4 | return 0 5 | min, max = (-2**31, 2**31 - 1) 6 | val = str(x) 7 | sign = "" 8 | if val[0] == "-": 9 | sign = val[0] 10 | val = val[1:len(val)] 11 | val = val[::-1].lstrip("0") 12 | if len(val) > 10: 13 | return 0 14 | val = sign + val 15 | if (int(val) > min) and (int(val) < max): 16 | return val 17 | return 0 -------------------------------------------------------------------------------- /ReverseString/problem.txt: -------------------------------------------------------------------------------- 1 | 2 | Write a function that reverses a string. The input string is given as an array of characters char[]. 3 | 4 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 5 | 6 | You may assume all the characters consist of printable ascii characters. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: ["h","e","l","l","o"] 13 | Output: ["o","l","l","e","h"] 14 | Example 2: 15 | 16 | Input: ["H","a","n","n","a","h"] 17 | Output: ["h","a","n","n","a","H"] 18 | -------------------------------------------------------------------------------- /uniqChar/uniqChar.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def uniqChar(word): 4 | char_hash = [False]*256 5 | isRepeated = False 6 | if len(word) > 128: 7 | return True 8 | for i in range(len(word)): 9 | # print(char_hash[ord(word[i])]) 10 | if char_hash[ord(word[i])] == False: 11 | char_hash[ord(word[i])] = True 12 | else: 13 | isRepeated = True 14 | break 15 | return isRepeated 16 | 17 | 18 | -------------------------------------------------------------------------------- /RangeSumOfBST/problem.txt: -------------------------------------------------------------------------------- 1 | Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). 2 | 3 | The binary search tree is guaranteed to have unique values. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 10 | Output: 32 11 | Example 2: 12 | 13 | Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 14 | Output: 23 15 | 16 | 17 | Note: 18 | 19 | The number of nodes in the tree is at most 10000. 20 | The final answer is guaranteed to be less than 2^31. -------------------------------------------------------------------------------- /FindKClosestElements/problem.txt: -------------------------------------------------------------------------------- 1 | Given a sorted array arr, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: arr = [1,2,3,4,5], k = 4, x = 3 8 | Output: [1,2,3,4] 9 | Example 2: 10 | 11 | Input: arr = [1,2,3,4,5], k = 4, x = -1 12 | Output: [1,2,3,4] 13 | 14 | 15 | Constraints: 16 | 17 | 1 <= k <= arr.length 18 | 1 <= arr.length <= 10^4 19 | Absolute value of elements in the array and x will not exceed 104 -------------------------------------------------------------------------------- /palindromPermutation/README.md: -------------------------------------------------------------------------------- 1 | # Palindrom Permutations 2 | 3 | ## DESCRIPTION 4 | 5 | Given a string, write a function to check if it is a permutation of 6 | a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A 7 | permutation is a rearrangement of letters. The palindrome does not need to be limited to just 8 | dictionary words. 9 | 10 | 11 | ## Source 12 | [Cracking the Coding Interview](https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/0984782850/ref=sr_1_1?keywords=cracking+the+coding+interview&qid=1578002684&sr=8-1) -------------------------------------------------------------------------------- /lexicographical numbers/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lexicalOrder(self, n: int) -> List[int]: 3 | out = [] 4 | temp = [0] 5 | while temp: 6 | val = temp.pop() 7 | if 1<= val <= n: 8 | out.append(val) 9 | val = val * 10 10 | for i in range(9,-1,-1): 11 | if val == 0 and i == 0: 12 | continue 13 | tempval = val + i 14 | if tempval > n: 15 | continue 16 | temp.append(tempval) 17 | return out -------------------------------------------------------------------------------- /rangeSumQueryImmutable/solution.py: -------------------------------------------------------------------------------- 1 | class NumArray: 2 | 3 | def __init__(self, nums: List[int]): 4 | self.nums = nums 5 | self.rundict = {} 6 | self.rundict[-1] = 0 7 | n = len(nums) 8 | for i in range(n): 9 | self.rundict[i] = self.rundict[i-1] + self.nums[i] 10 | 11 | 12 | def sumRange(self, i: int, j: int) -> int: 13 | 14 | return self.rundict[j] - self.rundict[i-1] 15 | 16 | 17 | # Your NumArray object will be instantiated and called as such: 18 | # obj = NumArray(nums) 19 | # param_1 = obj.sumRange(i,j) -------------------------------------------------------------------------------- /FIZZBUZZ/problem.txt: -------------------------------------------------------------------------------- 1 | 2 | Write a program that outputs the string representation of numbers from 1 to n. 3 | 4 | But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. 5 | 6 | Example: 7 | 8 | n = 15, 9 | 10 | Return: 11 | [ 12 | "1", 13 | "2", 14 | "Fizz", 15 | "4", 16 | "Buzz", 17 | "Fizz", 18 | "7", 19 | "8", 20 | "Fizz", 21 | "Buzz", 22 | "11", 23 | "Fizz", 24 | "13", 25 | "14", 26 | "FizzBuzz" 27 | ] 28 | -------------------------------------------------------------------------------- /Longest Substring Without Repeating Characters/problem.txt: -------------------------------------------------------------------------------- 1 | Given a string, find the length of the longest substring without repeating characters. 2 | 3 | Example 1: 4 | 5 | Input: "abcabcbb" 6 | Output: 3 7 | Explanation: The answer is "abc", with the length of 3. 8 | Example 2: 9 | 10 | Input: "bbbbb" 11 | Output: 1 12 | Explanation: The answer is "b", with the length of 1. 13 | Example 3: 14 | 15 | Input: "pwwkew" 16 | Output: 3 17 | Explanation: The answer is "wke", with the length of 3. 18 | Note that the answer must be a substring, "pwke" is a subsequence and not a substring. 19 | -------------------------------------------------------------------------------- /SearchInRotatedSortedArray/problem.txt: -------------------------------------------------------------------------------- 1 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 2 | 3 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 4 | 5 | You are given a target value to search. If found in the array return its index, otherwise return -1. 6 | 7 | You may assume no duplicate exists in the array. 8 | 9 | Your algorithm's runtime complexity must be in the order of O(log n). 10 | 11 | Example 1: 12 | 13 | Input: nums = [4,5,6,7,0,1,2], target = 0 14 | Output: 4 15 | Example 2: 16 | 17 | Input: nums = [4,5,6,7,0,1,2], target = 3 18 | Output: -1 19 | -------------------------------------------------------------------------------- /PartitionArrayInto3PartsWithEqualSum/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canThreePartsEqualSum(self, A: List[int]) -> bool: 3 | summ = sum(A) 4 | T = summ / 3 5 | if summ % 3 != 0: 6 | return False 7 | runSum = 0 8 | count = 0 9 | for i in range(len(A)): 10 | runSum += A[i] 11 | if runSum == T: 12 | # print('triggered for ', i) 13 | count += 1 14 | runSum = 0 15 | if count >= 3: 16 | return True 17 | return False 18 | 19 | 20 | -------------------------------------------------------------------------------- /contains duplicate 2/solution.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | class Solution: 4 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 5 | 6 | if k <= 0 or not nums: 7 | return False 8 | 9 | 10 | 11 | buckets = OrderedDict() 12 | 13 | for num in nums: 14 | if num in buckets: 15 | return True 16 | buckets[num] = None 17 | if len(buckets) == k+1: 18 | buckets.popitem(last = False) 19 | 20 | return False 21 | 22 | -------------------------------------------------------------------------------- /longestArithmeticSubsequenceForGivenDiff/solution.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | class Solution: 3 | def longestSubsequence(self, arr: List[int], difference: int) -> int: 4 | 5 | cache = DefaultDict(int) 6 | maxcount = 1 7 | n = len(arr) 8 | for i in range(n): 9 | v = arr[i] 10 | if cache[v-difference] <= 0: 11 | cache[v] = 1 12 | else: 13 | cache[v] = max(cache[v], cache[v-difference] + 1) 14 | 15 | maxcount = max(maxcount, cache[v]) 16 | 17 | return maxcount -------------------------------------------------------------------------------- /longestarithmeticsequence/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestArithSeqLength(self, A: List[int]) -> int: 3 | n = len(A) 4 | # out = [1] * n 5 | outdict = {} 6 | longseq = 0 7 | for i in range(n): 8 | for j in range(0, i): 9 | diff = A[i] - A[j] 10 | if diff not in outdict: 11 | outdict[diff] = [1] * n 12 | pointer = outdict[diff] 13 | pointer[i] = max(pointer[i], pointer[j] + 1) 14 | longseq = max(longseq, pointer[i]) 15 | # print(longseq) 16 | return longseq -------------------------------------------------------------------------------- /mergeIntervals/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 3 | if not intervals: 4 | return intervals 5 | intervals.sort(key=lambda x: x[0]) 6 | start, end = intervals[0][0], intervals[0][1] 7 | out = [] 8 | for interval in intervals: 9 | if interval[0] <= end: 10 | end = max(end, interval[1]) 11 | else: 12 | out.append([start, end]) 13 | start, end = interval[0], interval[1] 14 | 15 | out.append([start, end]) 16 | return out 17 | -------------------------------------------------------------------------------- /minimumTimeDifference/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMinDifference(self, timePoints: List[str]) -> int: 3 | def convertTime(time): 4 | hour, mins = time.split(':') 5 | return int(hour) * 60 + int(mins) 6 | 7 | 8 | timePoints.sort() 9 | n = len(timePoints) 10 | ans = float('inf') 11 | for i in range(n): 12 | 13 | j = (i+1) % n 14 | diff = (convertTime(timePoints[j]) - convertTime(timePoints[i])) % 1440 15 | 16 | ans = min(ans, diff) 17 | 18 | return ans 19 | -------------------------------------------------------------------------------- /bestsightseeingpair/problem.txt: -------------------------------------------------------------------------------- 1 | Given an array A of positive integers, A[i] represents the value of the i-th sightseeing spot, and two sightseeing spots i and j have distance j - i between them. 2 | 3 | The score of a pair (i < j) of sightseeing spots is (A[i] + A[j] + i - j) : the sum of the values of the sightseeing spots, minus the distance between them. 4 | 5 | Return the maximum score of a pair of sightseeing spots. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: [8,1,5,2,6] 12 | Output: 11 13 | Explanation: i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11 14 | 15 | 16 | Note: 17 | 18 | 2 <= A.length <= 50000 19 | 1 <= A[i] <= 1000 -------------------------------------------------------------------------------- /palindromPermutation/palindromPermutation.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | def palindromePermutation(str1): 4 | str1 = str1.replace(" ", "").lower() 5 | strCount = Counter(str1) 6 | oneDetected = False 7 | isPermutation = True 8 | print(strCount) 9 | for k,v in strCount.items(): 10 | if (v%2) != 0: 11 | if v == 1: 12 | if not oneDetected: 13 | oneDetected = True 14 | continue 15 | isPermutation = False 16 | break 17 | else: 18 | isPermutation = False 19 | break 20 | 21 | return isPermutation 22 | 23 | print(palindromePermutation("Tact Coa")) -------------------------------------------------------------------------------- /kthlargestelement/Longest common subsequence/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 3 | r, c = len(text1) + 1, len(text2) + 1 4 | mem = [[0 for j in range(c)] for i in range(r)] 5 | 6 | res = 0 7 | for i in range(1, r): 8 | for j in range(1, c): 9 | if text1[i-1] != text2[j-1]: 10 | mem[i][j] = max(mem[i-1][j-1], mem[i-1][j], mem[i][j-1]) 11 | else: 12 | mem[i][j] = mem[i-1][j-1] + 1 13 | res = max(res, mem[i][j]) 14 | 15 | return res -------------------------------------------------------------------------------- /oneAwayEdit/README.md: -------------------------------------------------------------------------------- 1 | # One Away Edit 2 | 3 | ## DESCRIPTION 4 | 5 | One Away: There are three types of edits that can be performed on strings: insert a character, 6 | remove a character, or replace a character. Given two strings, write a function to check if they are 7 | one edit (or zero edits) away. 8 | 9 | ### EXAMPLE 10 | 11 | ```BASH 12 | pale, ple -> true 13 | pales, pale -> true 14 | pale, bale -> true 15 | pale, bae -> false 16 | ``` 17 | 18 | ## Source 19 | [Cracking the Coding Interview](https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/0984782850/ref=sr_1_1?keywords=cracking+the+coding+interview&qid=1578002684&sr=8-1) -------------------------------------------------------------------------------- /ContainerWithMostWater/problem.txt: -------------------------------------------------------------------------------- 1 | Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 2 | 3 | Note: You may not slant the container and n is at least 2. 4 | 5 | 6 | 7 | 8 | 9 | The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. 10 | 11 | 12 | 13 | Example: 14 | 15 | Input: [1,8,6,2,5,4,8,3,7] 16 | Output: 49 17 | -------------------------------------------------------------------------------- /ContainerWithMostWater/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def calcArea(self, height, start, end): 3 | return min(height[start], height[end]) * (end - start) 4 | 5 | def maxArea(self, height: List[int]) -> int: 6 | start = 0 7 | end = len(height) - 1 8 | maxArea = 0 9 | while start < end: 10 | area = self.calcArea(height, start, end) 11 | maxArea = max(area, maxArea) 12 | minVertix = min(height[start], height[end]) 13 | if minVertix == height[start]: 14 | start += 1 15 | else: 16 | end -= 1 17 | return maxArea 18 | 19 | -------------------------------------------------------------------------------- /Median of 2 sorted arrays/README.md: -------------------------------------------------------------------------------- 1 | # Median of 2 sorted Arrays 2 | 3 | ## DESCRIPTION 4 | 5 | There are two sorted arrays nums1 and nums2 of size m and n respectively. 6 | 7 | Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 8 | 9 | You may assume nums1 and nums2 cannot be both empty. 10 | 11 | 12 | ### EXAMPLE 1 13 | 14 | ```BASH 15 | nums1 = [1, 3] 16 | nums2 = [2] 17 | 18 | The median is 2.0 19 | ``` 20 | ### EXAMPLE 2 21 | 22 | ```BASH 23 | nums1 = [1, 2] 24 | nums2 = [3, 4] 25 | 26 | The median is (2 + 3)/2 = 2.5 27 | ``` 28 | 29 | 30 | ## License 31 | [LEETCODE](https://leetcode.com/problems/median-of-two-sorted-arrays/) -------------------------------------------------------------------------------- /arithmeticProgressionFromSequence/problem.txt: -------------------------------------------------------------------------------- 1 | Given an array of numbers arr. A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. 2 | 3 | Return true if the array can be rearranged to form an arithmetic progression, otherwise, return false. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: arr = [3,5,1] 10 | Output: true 11 | Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements. 12 | Example 2: 13 | 14 | Input: arr = [1,2,4] 15 | Output: false 16 | Explanation: There is no way to reorder the elements to obtain an arithmetic progression. -------------------------------------------------------------------------------- /HandOfStraight/problem.txt: -------------------------------------------------------------------------------- 1 | Alice has a hand of cards, given as an array of integers. 2 | 3 | Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards. 4 | 5 | Return true if and only if she can. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: hand = [1,2,3,6,2,3,4,7,8], W = 3 12 | Output: true 13 | Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]. 14 | Example 2: 15 | 16 | Input: hand = [1,2,3,4,5], W = 4 17 | Output: false 18 | Explanation: Alice's hand can't be rearranged into groups of 4. 19 | 20 | 21 | Constraints: 22 | 23 | 1 <= hand.length <= 10000 24 | 0 <= hand[i] <= 10^9 25 | 1 <= W <= hand.length -------------------------------------------------------------------------------- /deleteNodesAndReturnForest/problem.txt: -------------------------------------------------------------------------------- 1 | Given the root of a binary tree, each node in the tree has a distinct value. 2 | 3 | After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). 4 | 5 | Return the roots of the trees in the remaining forest. You may return the result in any order. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | 12 | 13 | Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] 14 | Output: [[1,2,null,4],[6],[7]] 15 | 16 | 17 | Constraints: 18 | 19 | The number of nodes in the given tree is at most 1000. 20 | Each node has a distinct value between 1 and 1000. 21 | to_delete.length <= 1000 22 | to_delete contains distinct values between 1 and 1000. -------------------------------------------------------------------------------- /validBST/problem.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree, determine if it is a valid binary search tree (BST). 2 | 3 | Assume a BST is defined as follows: 4 | 5 | The left subtree of a node contains only nodes with keys less than the node's key. 6 | The right subtree of a node contains only nodes with keys greater than the node's key. 7 | Both the left and right subtrees must also be binary search trees. 8 | 9 | 10 | Example 1: 11 | 12 | 2 13 | / \ 14 | 1 3 15 | 16 | Input: [2,1,3] 17 | Output: true 18 | Example 2: 19 | 20 | 5 21 | / \ 22 | 1 4 23 | / \ 24 | 3 6 25 | 26 | Input: [5,1,4,null,null,3,6] 27 | Output: false 28 | Explanation: The root node's value is 5 but its right child's value is 4. 29 | -------------------------------------------------------------------------------- /splitArrayIntoConsecutive/problem.txt: -------------------------------------------------------------------------------- 1 | Given an array nums sorted in ascending order, return true if and only if you can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and has length at least 3. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: [1,2,3,3,4,5] 8 | Output: True 9 | Explanation: 10 | You can split them into two consecutive subsequences : 11 | 1, 2, 3 12 | 3, 4, 5 13 | 14 | Example 2: 15 | 16 | Input: [1,2,3,3,4,4,5,5] 17 | Output: True 18 | Explanation: 19 | You can split them into two consecutive subsequences : 20 | 1, 2, 3, 4, 5 21 | 3, 4, 5 22 | 23 | Example 3: 24 | 25 | Input: [1,2,3,4,4,5] 26 | Output: False 27 | 28 | 29 | Constraints: 30 | 31 | 1 <= nums.length <= 10000 -------------------------------------------------------------------------------- /Median of 2 sorted arrays/median.py: -------------------------------------------------------------------------------- 1 | import statistics 2 | class Solution: 3 | def merge(self, first_half, second_half): 4 | size = len(first_half) + len(second_half) 5 | arr = [] 6 | for i in range(size): 7 | if not second_half or (first_half and first_half[0] <= second_half[0]): 8 | arr.append(first_half[0]) 9 | first_half.pop(0) 10 | else: 11 | arr.append(second_half[0]) 12 | second_half.pop(0) 13 | return arr 14 | 15 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 16 | arr = self.merge(nums1, nums2) 17 | ans = statistics.median(arr) 18 | return ans 19 | -------------------------------------------------------------------------------- /rightSideView/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def rightSideView(self, root: TreeNode) -> List[int]: 9 | if not root: 10 | return 11 | 12 | out = [] 13 | def helper(node,i): 14 | if i > len(out): 15 | out.append(node.val) 16 | if node.right: 17 | helper(node.right, i+1) 18 | if node.left: 19 | helper(node.left, i+1) 20 | 21 | 22 | helper(root, 1) 23 | return out 24 | -------------------------------------------------------------------------------- /subtreeOfAnotherTree/problem.txt: -------------------------------------------------------------------------------- 1 | Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. 2 | 3 | Example 1: 4 | Given tree s: 5 | 6 | 3 7 | / \ 8 | 4 5 9 | / \ 10 | 1 2 11 | Given tree t: 12 | 4 13 | / \ 14 | 1 2 15 | Return true, because t has the same structure and node values with a subtree of s. 16 | 17 | 18 | Example 2: 19 | Given tree s: 20 | 21 | 3 22 | / \ 23 | 4 5 24 | / \ 25 | 1 2 26 | / 27 | 0 28 | Given tree t: 29 | 4 30 | / \ 31 | 1 2 32 | Return false. 33 | -------------------------------------------------------------------------------- /uglynumber2/uglynumber.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class Solution: 4 | def nthUglyNumber(self, n: int) -> int: 5 | 6 | 7 | heap = [] 8 | res = [1] 9 | 10 | heap.append((2,0,2)) 11 | heap.append((3,0,3)) 12 | heap.append((5,0,5)) 13 | 14 | 15 | 16 | while n > 1: 17 | 18 | multi, ind, factor = heapq.heappop(heap) 19 | 20 | if multi != res[-1]: 21 | res.append(multi) 22 | n -= 1 23 | ind += 1 24 | multi = factor * res[ind] 25 | form = ((multi, ind, factor)) 26 | heapq.heappush(heap, form) 27 | 28 | return res[-1] -------------------------------------------------------------------------------- /partitionToKSubsets/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: 3 | elemSum = sum(nums) 4 | if elemSum % k != 0: 5 | return False 6 | T = elemSum // k 7 | nums.sort() 8 | def helper(groups): 9 | if not nums: 10 | return True 11 | v = nums.pop() 12 | for i in range(len(groups)): 13 | if groups[i] + v <= T: 14 | groups[i] += v 15 | if helper(groups): 16 | return True 17 | groups[i] -= v 18 | nums.append(v) 19 | return False 20 | 21 | 22 | return helper([0] * k) 23 | -------------------------------------------------------------------------------- /jumpgame/problem.txt: -------------------------------------------------------------------------------- 1 | JUMP GAME 2 | 3 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 4 | 5 | Each element in the array represents your maximum jump length at that position. 6 | 7 | Determine if you are able to reach the last index. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: nums = [2,3,1,1,4] 14 | Output: true 15 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 16 | Example 2: 17 | 18 | Input: nums = [3,2,1,0,4] 19 | Output: false 20 | Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. 21 | 22 | 23 | Constraints: 24 | 25 | 1 <= nums.length <= 3 * 10^4 26 | 0 <= nums[i][j] <= 10^5 27 | -------------------------------------------------------------------------------- /splitArrayIntoConsecutive/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPossible(self, nums: List[int]) -> bool: 3 | count = collections.Counter(nums) 4 | tail = collections.Counter() 5 | n = len(nums) 6 | 7 | for i in range(n): 8 | v = nums[i] 9 | v1 = v+1 10 | v2 = v+2 11 | if count[v] == 0: 12 | continue 13 | elif tail[v] > 0: 14 | tail[v+1] += 1 15 | tail[v] -= 1 16 | elif count[v1] > 0 and count[v2] > 0: 17 | count[v1] -= 1 18 | count[v2] -= 1 19 | tail[v2+1] += 1 20 | else: 21 | return False 22 | 23 | count[v] -= 1 24 | return True -------------------------------------------------------------------------------- /SerializeAndDeserializeBST/problem.txt: -------------------------------------------------------------------------------- 1 | Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. 2 | 3 | Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure. 4 | 5 | The encoded string should be as compact as possible. 6 | 7 | Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless. -------------------------------------------------------------------------------- /PartitionArrayInto3PartsWithEqualSum/problem.txt: -------------------------------------------------------------------------------- 1 | Given an array A of integers, return true if and only if we can partition the array into three non-empty parts with equal sums. 2 | 3 | Formally, we can partition the array if we can find indexes i+1 < j with (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1]) 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: A = [0,2,1,-6,6,-7,9,1,2,0,1] 10 | Output: true 11 | Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1 12 | Example 2: 13 | 14 | Input: A = [0,2,1,-6,6,7,9,-1,2,0,1] 15 | Output: false 16 | Example 3: 17 | 18 | Input: A = [3,3,6,5,-2,2,5,1,-9,4] 19 | Output: true 20 | Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4 21 | 22 | 23 | Constraints: 24 | 25 | 3 <= A.length <= 50000 26 | -10^4 <= A[i] <= 10^4 27 | -------------------------------------------------------------------------------- /boatsToSavePeople/problem.txt: -------------------------------------------------------------------------------- 1 | The i-th person has weight people[i], and each boat can carry a maximum weight of limit. 2 | 3 | Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit. 4 | 5 | Return the minimum number of boats to carry every given person. (It is guaranteed each person can be carried by a boat.) 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: people = [1,2], limit = 3 12 | Output: 1 13 | Explanation: 1 boat (1, 2) 14 | Example 2: 15 | 16 | Input: people = [3,2,2,1], limit = 3 17 | Output: 3 18 | Explanation: 3 boats (1, 2), (2) and (3) 19 | Example 3: 20 | 21 | Input: people = [3,5,3,4], limit = 5 22 | Output: 4 23 | Explanation: 4 boats (3), (3), (4), (5) 24 | Note: 25 | 26 | 1 <= people.length <= 50000 27 | 1 <= people[i] <= limit <= 30000 -------------------------------------------------------------------------------- /longestArithmeticSubsequenceForGivenDiff/problem.txt: -------------------------------------------------------------------------------- 1 | Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: arr = [1,2,3,4], difference = 1 8 | Output: 4 9 | Explanation: The longest arithmetic subsequence is [1,2,3,4]. 10 | Example 2: 11 | 12 | Input: arr = [1,3,5,7], difference = 1 13 | Output: 1 14 | Explanation: The longest arithmetic subsequence is any single element. 15 | Example 3: 16 | 17 | Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2 18 | Output: 4 19 | Explanation: The longest arithmetic subsequence is [7,5,3,1]. 20 | 21 | 22 | Constraints: 23 | 24 | 1 <= arr.length <= 10^5 25 | -10^4 <= arr[i], difference <= 10^4 -------------------------------------------------------------------------------- /BinaryTreeCompleteness/problem.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree, determine if it is a complete binary tree. 2 | 3 | Definition of a complete binary tree from Wikipedia: 4 | In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | 11 | 12 | Input: [1,2,3,4,5,6] 13 | Output: true 14 | Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible. 15 | Example 2: 16 | 17 | 18 | 19 | Input: [1,2,3,4,5,null,7] 20 | Output: false 21 | Explanation: The node with value 7 isn't as far left as possible. 22 | 23 | Note: 24 | 25 | The tree will have between 1 and 100 nodes. -------------------------------------------------------------------------------- /Binarywatch/problem.txt: -------------------------------------------------------------------------------- 1 | A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). 2 | 3 | Each LED represents a zero or one, with the least significant bit on the right. 4 | 5 | 6 | For example, the above binary watch reads "3:25". 7 | 8 | Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent. 9 | 10 | Example: 11 | 12 | Input: n = 1 13 | Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] 14 | Note: 15 | The order of output does not matter. 16 | The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". 17 | The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02". 18 | -------------------------------------------------------------------------------- /longestarithmeticsequence/problems.txt: -------------------------------------------------------------------------------- 1 | Given an array A of integers, return the length of the longest arithmetic subsequence in A. 2 | 3 | Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1). 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: [3,6,9,12] 10 | Output: 4 11 | Explanation: 12 | The whole array is an arithmetic sequence with steps of length = 3. 13 | Example 2: 14 | 15 | Input: [9,4,7,2,10] 16 | Output: 3 17 | Explanation: 18 | The longest arithmetic subsequence is [4,7,10]. 19 | Example 3: 20 | 21 | Input: [20,1,15,3,10,5,8] 22 | Output: 4 23 | Explanation: 24 | The longest arithmetic subsequence is [20,15,10,5]. 25 | 26 | 27 | Note: 28 | 29 | 2 <= A.length <= 2000 30 | 0 <= A[i] <= 10000 -------------------------------------------------------------------------------- /Generate Parenthesis/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def getParenthesis(self, left, right, temp, output): 4 | if right < left: 5 | return 6 | if right == 0 and left == 0: 7 | output.append(''.join(temp)) 8 | return 9 | 10 | if left > 0: 11 | temp.append('(') 12 | self.getParenthesis(left-1, right, temp[:], output) 13 | temp.pop() 14 | 15 | if right > 0: 16 | temp.append(')') 17 | self.getParenthesis(left, right-1, temp[:], output) 18 | temp.pop() 19 | 20 | 21 | def generateParenthesis(self, n: int) -> List[str]: 22 | if n == 1: 23 | return ['()'] 24 | output = [] 25 | self.getParenthesis(n, n, [], output) 26 | return output 27 | 28 | -------------------------------------------------------------------------------- /stringToIntegar/atoi.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myAtoi(self, str: str) -> int: 3 | min_int, max_int = [-2147483648, 2147483647] 4 | # str = "+1" 5 | str = str.strip(" ") 6 | if not str: 7 | return 0 8 | sign = "" 9 | if str[0] == "-": 10 | sign = "-" 11 | str = str[1:len(str)] 12 | elif str[0] == "+": 13 | sign = "" 14 | str = str[1:len(str)] 15 | if not str or not str[0].isnumeric(): 16 | return 0 17 | num = "" 18 | for c in str: 19 | if c.isnumeric(): 20 | num += c 21 | continue 22 | break 23 | num = int(sign + num) 24 | num = max(num, min_int) 25 | num = min(num, max_int) 26 | return num 27 | 28 | 29 | -------------------------------------------------------------------------------- /decodeString/README.md: -------------------------------------------------------------------------------- 1 | # Decode String 2 | 3 | ## DESCRIPTION 4 | 5 | Given an encoded string, return its decoded string. 6 | 7 | The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. 8 | 9 | You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. 10 | 11 | Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. 12 | 13 | ### EXAMPLES 14 | 15 | ```BASH 16 | s = "3[a]2[bc]", return "aaabcbc". 17 | s = "3[a2[c]]", return "accaccacc". 18 | s = "2[abc]3[cd]ef", return "abcabccdcdcdef". 19 | ``` 20 | 21 | ## License 22 | [LEETCODE](https://leetcode.com/problems/decode-string/) -------------------------------------------------------------------------------- /constructTreeFromString/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def tree2str(self, t: TreeNode) -> str: 9 | 10 | 11 | 12 | out = [] 13 | def helper(t): 14 | if not t: 15 | return 16 | 17 | out.append(str(t.val)) 18 | if t.left or t.right: 19 | out.append('(') 20 | helper(t.left) 21 | out.append(')') 22 | if t.right: 23 | out.append('(') 24 | helper(t.right) 25 | out.append(')') 26 | 27 | helper(t) 28 | return ''.join(out) 29 | -------------------------------------------------------------------------------- /minStack/problem.txt: -------------------------------------------------------------------------------- 1 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 2 | 3 | push(x) -- Push element x onto stack. 4 | pop() -- Removes the element on top of the stack. 5 | top() -- Get the top element. 6 | getMin() -- Retrieve the minimum element in the stack. 7 | 8 | 9 | Example 1: 10 | 11 | Input 12 | ["MinStack","push","push","push","getMin","pop","top","getMin"] 13 | [[],[-2],[0],[-3],[],[],[],[]] 14 | 15 | Output 16 | [null,null,null,null,-3,null,0,-2] 17 | 18 | Explanation 19 | MinStack minStack = new MinStack(); 20 | minStack.push(-2); 21 | minStack.push(0); 22 | minStack.push(-3); 23 | minStack.getMin(); // return -3 24 | minStack.pop(); 25 | minStack.top(); // return 0 26 | minStack.getMin(); // return -2 27 | 28 | 29 | Constraints: 30 | 31 | Methods pop, top and getMin operations will always be called on non-empty stacks. 32 | -------------------------------------------------------------------------------- /kthlargestelement/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findKthLargest(self, nums: List[int], k: int) -> int: 3 | 4 | k = len(nums) - k 5 | 6 | def helper(arr, start, end): 7 | leader, follower = start, start 8 | targ = end - 1 9 | 10 | while leader < targ: 11 | if arr[leader] <= arr[targ]: 12 | arr[leader], arr[follower] = arr[follower], arr[leader] 13 | follower += 1 14 | leader += 1 15 | arr[targ], arr[follower] = arr[follower], arr[targ] 16 | if follower == k: 17 | return arr[k] 18 | elif k < follower: 19 | return helper(arr, start, follower) 20 | return helper(arr, follower+1, end) 21 | 22 | return helper(nums, 0, len(nums)) 23 | 24 | -------------------------------------------------------------------------------- /uniquepaths/problem.txt: -------------------------------------------------------------------------------- 1 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 2 | 3 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 4 | 5 | How many possible unique paths are there? 6 | 7 | 8 | Above is a 7 x 3 grid. How many possible unique paths are there? 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: m = 3, n = 2 15 | Output: 3 16 | Explanation: 17 | From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 18 | 1. Right -> Right -> Down 19 | 2. Right -> Down -> Right 20 | 3. Down -> Right -> Right 21 | Example 2: 22 | 23 | Input: m = 7, n = 3 24 | Output: 28 25 | 26 | 27 | Constraints: 28 | 29 | 1 <= m, n <= 100 30 | It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9. 31 | -------------------------------------------------------------------------------- /countandsay/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countAndSay(self, n: int) -> str: 3 | # n = 5 4 | if n == 1: 5 | return '1' 6 | 7 | say = '1' 8 | for i in range(n-1): 9 | curr = say[0] 10 | count = 0 11 | futSay = [] 12 | for j in range(len(say)): 13 | if say[j] == curr: 14 | count += 1 15 | else: 16 | futSay.append(str(count)) 17 | futSay.append(curr) 18 | curr = say[j] 19 | count = 1 20 | 21 | if j == (len(say)-1): 22 | futSay.append(str(count)) 23 | futSay.append(curr) 24 | say = ''.join(futSay) 25 | # print('for ', i, ' say is ', say) 26 | 27 | return say 28 | -------------------------------------------------------------------------------- /inordertraversal/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | 10 | def __stack(self, root, stack): 11 | while root: 12 | stack.append(root) 13 | root = root.left 14 | 15 | 16 | def inorderTraversal(self, root: TreeNode) -> List[int]: 17 | if not root: 18 | return [] 19 | stack = [] 20 | out = [] 21 | self.__stack(root, stack) 22 | while stack: 23 | node = stack.pop() 24 | out.append(node.val) 25 | if node.right: 26 | root = node.right 27 | self.__stack(root, stack) 28 | 29 | return out 30 | 31 | 32 | -------------------------------------------------------------------------------- /divideArrayInSetsOfKConsecutiveNumbers/problem.txt: -------------------------------------------------------------------------------- 1 | Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into sets of k consecutive numbers 2 | Return True if its possible otherwise return False. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: nums = [1,2,3,3,4,4,5,6], k = 4 9 | Output: true 10 | Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6]. 11 | Example 2: 12 | 13 | Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3 14 | Output: true 15 | Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11]. 16 | Example 3: 17 | 18 | Input: nums = [3,3,2,2,1,1], k = 3 19 | Output: true 20 | Example 4: 21 | 22 | Input: nums = [1,2,3,4], k = 3 23 | Output: false 24 | Explanation: Each array should be divided in subarrays of size 3. 25 | 26 | 27 | Constraints: 28 | 29 | 1 <= nums.length <= 10^5 30 | 1 <= nums[i] <= 10^9 31 | 1 <= k <= nums.length -------------------------------------------------------------------------------- /Two Sum/twoSum.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def twoSum(self, nums: List[int], target: int) -> List[int]: 4 | num_dict = {} 5 | count_dict = Counter(nums) 6 | for i in range(len(nums)): 7 | num_dict[nums[i]] = i 8 | second = 0 9 | first = 0 10 | found = False 11 | i1 = 0 12 | i2 = 0 13 | for k, v in num_dict.items(): 14 | if (target-k) in num_dict: 15 | if k == (target - k): 16 | if count_dict[k] > 1: 17 | i2 = num_dict[k] 18 | i1 = nums.index(k) 19 | break 20 | else: 21 | continue 22 | i1 = num_dict[k] 23 | i2 = num_dict[target-k] 24 | break 25 | return [i1, i2] 26 | 27 | -------------------------------------------------------------------------------- /merge2sortedlist/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 9 | head, point = None, None 10 | while l1 or l2: 11 | if not l2 or (l1 and l1.val <= l2.val): 12 | if not head: 13 | head = l1 14 | point = head 15 | else: 16 | point.next = l1 17 | point = point.next 18 | l1 = l1.next 19 | else: 20 | if not head: 21 | head = l2 22 | point = head 23 | else: 24 | point.next = l2 25 | point = point.next 26 | l2 = l2.next 27 | return head 28 | -------------------------------------------------------------------------------- /RangeSumOfBST/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: 9 | 10 | 11 | 12 | 13 | # out = 0 14 | 15 | def helper(root): 16 | # nonlocal out 17 | if not root: 18 | return 0 19 | out = 0 20 | if L<=root.val<=R: 21 | out = root.val 22 | # retur 23 | if root.val >= L: 24 | out += helper(root.left) 25 | 26 | if root.val <= R: 27 | out += helper(root.right) 28 | return out 29 | 30 | 31 | return helper(root) 32 | -------------------------------------------------------------------------------- /oneAwayEdit/oneAwayEdit.py: -------------------------------------------------------------------------------- 1 | def editReplace(str1, str2): 2 | editCount = 0 3 | for i in range(len(str1)): 4 | if str1[i] != str2[i]: 5 | editCount += 1 6 | if editCount < 2: 7 | return True 8 | return False 9 | 10 | def editInsert(str1, str2): 11 | ind1 = 0 12 | ind2 = 0 13 | editCount = 0 14 | while ind1 < len(str1) and ind2 < len(str2): 15 | if str1[ind1] != str2[ind2]: 16 | ind1 += 1 17 | editCount += 1 18 | continue 19 | ind1 += 1 20 | ind2 += 1 21 | if editCount < 2: 22 | return True 23 | return False 24 | 25 | 26 | 27 | def editType(str1, str2): 28 | str1len = len(str1) 29 | str2len = len(str2) 30 | if str1len == str2len: 31 | return editReplace(str1, str2) 32 | elif str1len == (str2len + 1): 33 | return editInsert(str1, str2) 34 | elif (str1len + 1) == str2len: 35 | return editInsert(str2, str1) 36 | return False 37 | 38 | 39 | 40 | 41 | 42 | editType("abba", "ab") -------------------------------------------------------------------------------- /Longest Palindromic Substring/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getMaxLength(self, arr, start, end): 3 | palin = "" 4 | while (start >= 0) and (end < len(arr)): 5 | if arr[start] != arr[end]: 6 | break 7 | if len(arr[start:end+1]) > len(palin): 8 | palin = arr[start:end+1] 9 | start -= 1 10 | end += 1 11 | return palin 12 | 13 | 14 | def longestPalindrome(self, s: str) -> str: 15 | maxArr = "" 16 | for i in range(len(s)): 17 | len1 = self.getMaxLength(s, i, i) 18 | len2 = self.getMaxLength(s, i, i+1) 19 | maxArr = max(len1, len2, maxArr, key=len) 20 | # maxArr = len1 if maxLen == len(len1) else len2 if maxLen == len(len2) else maxArr 21 | # if s[i] == 'a': 22 | # print("The first is {0} the second is {1}".format(len1, len2)) 23 | return maxArr 24 | -------------------------------------------------------------------------------- /flipEquivalentBinaryTree/problem.txt: -------------------------------------------------------------------------------- 1 | For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees. 2 | 3 | A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations. 4 | 5 | Given the roots of two binary trees root1 and root2, return true if the two trees are flip equivelent or false otherwise. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Flipped Trees Diagram 12 | Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7] 13 | Output: true 14 | Explanation: We flipped at nodes with values 1, 3, and 5. 15 | Example 2: 16 | 17 | Input: root1 = [], root2 = [] 18 | Output: true 19 | Example 3: 20 | 21 | Input: root1 = [], root2 = [1] 22 | Output: false 23 | Example 4: 24 | 25 | Input: root1 = [0,null,1], root2 = [] 26 | Output: false 27 | Example 5: 28 | 29 | Input: root1 = [0,null,1], root2 = [0,1] 30 | Output: true -------------------------------------------------------------------------------- /divideArrayInSetsOfKConsecutiveNumbers/solution.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def isPossibleDivide(self, nums: List[int], k: int) -> bool: 5 | n = len(nums) 6 | if n % k != 0: 7 | return False 8 | valsdict = Counter(nums) 9 | 10 | # print(valsdict) 11 | 12 | 13 | 14 | tots = 0 15 | nums.sort() 16 | print(nums) 17 | for i in range(n): 18 | val = nums[i] 19 | if valsdict[val-1] > 0 or valsdict[val] <= 0: 20 | continue 21 | count = 1 22 | valsdict[val] -= 1 23 | while valsdict[val+1] > 0 and count < k: 24 | val = val + 1 25 | valsdict[val] -= 1 26 | count += 1 27 | 28 | if count == k: 29 | tots += 1 30 | if tots * k == n: 31 | return True 32 | return False -------------------------------------------------------------------------------- /flipEquivalentBinaryTree/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool: 9 | 10 | 11 | 12 | 13 | def helper(root1, root2): 14 | 15 | if not root1 and not root2: 16 | return True 17 | 18 | if (not root1 and root2) or (not root2 and root1): 19 | return False 20 | 21 | if root1.val != root2.val: 22 | return False 23 | 24 | normal = helper(root1.left, root2.left) and helper(root1.right, root2.right) 25 | flipped = helper(root1.left, root2.right) and helper(root1.right, root2.left) 26 | 27 | return normal or flipped 28 | 29 | 30 | return helper(root1, root2) -------------------------------------------------------------------------------- /validBST/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | 10 | def __isValidBST(self, root, leftBound, rightBound): 11 | 12 | if not leftBound < root.val < rightBound: 13 | return False 14 | 15 | if not root.left and not root.right: 16 | return True 17 | if root.left: 18 | left = self.__isValidBST(root.left, leftBound, root.val) 19 | if not left: 20 | return False 21 | if root.right: 22 | right = self.__isValidBST(root.right, root.val, rightBound) 23 | if not right: 24 | return False 25 | 26 | return True 27 | 28 | 29 | 30 | def isValidBST(self, root: TreeNode) -> bool: 31 | if not root: 32 | return True 33 | return self.__isValidBST(root, float('-inf'), float('inf')) 34 | -------------------------------------------------------------------------------- /constructTreeFromString/problem.txt: -------------------------------------------------------------------------------- 1 | You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. 2 | 3 | The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree. 4 | 5 | Example 1: 6 | Input: Binary tree: [1,2,3,4] 7 | 1 8 | / \ 9 | 2 3 10 | / 11 | 4 12 | 13 | Output: "1(2(4))(3)" 14 | 15 | Explanation: Originallay it needs to be "1(2(4)())(3()())", 16 | but you need to omit all the unnecessary empty parenthesis pairs. 17 | And it will be "1(2(4))(3)". 18 | Example 2: 19 | Input: Binary tree: [1,2,3,null,4] 20 | 1 21 | / \ 22 | 2 3 23 | \ 24 | 4 25 | 26 | Output: "1(2()(4))(3)" 27 | 28 | Explanation: Almost the same as the first example, 29 | except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output. -------------------------------------------------------------------------------- /countandsay/problem.txt: -------------------------------------------------------------------------------- 1 | The count-and-say sequence is the sequence of integers with the first five terms as following: 2 | 3 | 1. 1 4 | 2. 11 5 | 3. 21 6 | 4. 1211 7 | 5. 111221 8 | 1 is read off as "one 1" or 11. 9 | 11 is read off as "two 1s" or 21. 10 | 21 is read off as "one 2, then one 1" or 1211. 11 | 12 | Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit. 13 | 14 | Note: Each term of the sequence of integers will be represented as a string. 15 | 16 | 17 | 18 | Example 1: 19 | 20 | Input: 1 21 | Output: "1" 22 | Explanation: This is the base case. 23 | Example 2: 24 | 25 | Input: 4 26 | Output: "1211" 27 | Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211". 28 | -------------------------------------------------------------------------------- /BinaryTreeCompleteness/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | from collections import deque 8 | class Solution: 9 | def isCompleteTree(self, root: TreeNode) -> bool: 10 | queue = deque() 11 | queue.append(root) 12 | isNone = False 13 | while queue: 14 | for i in range(len(queue)): 15 | node = queue.popleft() 16 | if isNone and node != '#': 17 | return False 18 | elif node == '#': 19 | isNone = True 20 | continue 21 | if node.left: 22 | queue.append(node.left) 23 | else: 24 | queue.append('#') 25 | if node.right: 26 | queue.append(node.right) 27 | else: 28 | queue.append('#') 29 | return True -------------------------------------------------------------------------------- /SearchInRotatedSortedArray/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bts(self, start, end, target, nums): 3 | mid = int((start + end) / 2) 4 | # print("start is {0} and end is {1} and mid is {2}".format(start, end, mid)) 5 | if nums[mid] == target: 6 | return mid 7 | if (end - start) <= 1: 8 | return -1 9 | if nums[start] < nums[mid]: 10 | if target >= nums[start] and target <= nums[mid]: 11 | return self.bts(start, mid, target, nums) 12 | else: 13 | return self.bts(mid, end, target, nums) 14 | else: 15 | if target >= nums[mid] and target <= nums[end - 1]: 16 | return self.bts(mid, end, target, nums) 17 | else: 18 | return self.bts(start, mid, target, nums) 19 | def search(self, nums: List[int], target: int) -> int: 20 | # nums = [1, 3] 21 | # target = 1 22 | if not nums: 23 | return -1 24 | return self.bts(0, len(nums), target, nums) 25 | 26 | 27 | -------------------------------------------------------------------------------- /minStack/solution.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | 3 | def __init__(self): 4 | """ 5 | initialize your data structure here. 6 | """ 7 | self.stack = [] 8 | self.min = [] 9 | 10 | def push(self, x: int) -> None: 11 | if not self.min: 12 | self.min.append(x) 13 | elif x <= self.min[-1]: 14 | self.min.append(x) 15 | self.stack.append(x) 16 | 17 | 18 | def pop(self) -> None: 19 | if not self.stack: 20 | return 21 | val = self.stack.pop() 22 | if val == self.min[-1]: 23 | self.min.pop() 24 | return val 25 | 26 | def top(self) -> int: 27 | if self.stack: 28 | return self.stack[-1] 29 | 30 | 31 | def getMin(self) -> int: 32 | if self.min: 33 | return self.min[-1] 34 | 35 | 36 | 37 | # Your MinStack object will be instantiated and called as such: 38 | # obj = MinStack() 39 | # obj.push(x) 40 | # obj.pop() 41 | # param_3 = obj.top() 42 | # param_4 = obj.getMin() 43 | -------------------------------------------------------------------------------- /maximumWidthOfBinaryTree/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def widthOfBinaryTree(self, root: TreeNode) -> int: 9 | 10 | g = {} 11 | # 12 | def helper(node, level, column): 13 | if not node: 14 | return 15 | 16 | if level in g: 17 | g[level].append(column) 18 | else: 19 | g[level] = [column] 20 | 21 | helper(node.left, level+1, column*2) 22 | helper(node.right, level+1, column*2 + 1) 23 | 24 | helper(root, 0, 0) 25 | out = 0 26 | for key in g: 27 | level = g[key] 28 | if len(level) == 1: 29 | out = max(out, 1) 30 | else: 31 | low, high = level[0], level[-1] 32 | out = max(out, high - low + 1) 33 | return out -------------------------------------------------------------------------------- /permutationsInString/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkInclusion(self, s1: str, s2: str) -> bool: 3 | if len(s1) > len(s2): 4 | return False 5 | g = {} 6 | for c in s1: 7 | g[c] = g.get(c,0) + 1 8 | 9 | 10 | count = 0 11 | start = end = 0 12 | n = len(s2) 13 | movedict = {} 14 | while end < n: 15 | # movedict[s2[end]] = movedict.get(s2[end], 0) + 1 16 | c = s2[end] 17 | if c in g: 18 | movedict[c] = movedict.get(c, 0) + 1 19 | if movedict[c] == g[c]: 20 | count += 1 21 | while count >= len(g): 22 | if (end - start + 1) == len(s1): 23 | return True 24 | c = s2[start] 25 | if c in movedict: 26 | movedict[c] -= 1 27 | if movedict[c] == (g[c] - 1): 28 | count -= 1 29 | start += 1 30 | end += 1 31 | return False 32 | 33 | -------------------------------------------------------------------------------- /insertdeletegetrandom/problem.txt: -------------------------------------------------------------------------------- 1 | Design a data structure that supports all following operations in average O(1) time. 2 | 3 | insert(val): Inserts an item val to the set if not already present. 4 | remove(val): Removes an item val from the set if present. 5 | getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned. 6 | Example: 7 | 8 | // Init an empty set. 9 | RandomizedSet randomSet = new RandomizedSet(); 10 | 11 | // Inserts 1 to the set. Returns true as 1 was inserted successfully. 12 | randomSet.insert(1); 13 | 14 | // Returns false as 2 does not exist in the set. 15 | randomSet.remove(2); 16 | 17 | // Inserts 2 to the set, returns true. Set now contains [1,2]. 18 | randomSet.insert(2); 19 | 20 | // getRandom should return either 1 or 2 randomly. 21 | randomSet.getRandom(); 22 | 23 | // Removes 1 from the set, returns true. Set now contains [2]. 24 | randomSet.remove(1); 25 | 26 | // 2 was already in the set, so return false. 27 | randomSet.insert(2); 28 | 29 | // Since 2 is the only number in the set, getRandom always return 2. 30 | randomSet.getRandom(); 31 | -------------------------------------------------------------------------------- /HandOfStraight/solution.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def isNStraightHand(self, hand: List[int], W: int) -> bool: 4 | n = len(hand) 5 | if n % W != 0: 6 | return False 7 | 8 | 9 | occurmap = Counter(hand) 10 | 11 | 12 | tots = 0 13 | hand.sort() 14 | # print('hnd is ', hand) 15 | for i in range(n): 16 | v = hand[i] 17 | if occurmap[v-1] > 0 or occurmap[v] <= 0: 18 | continue 19 | # print('first value is ', v) 20 | 21 | count = 1 22 | occurmap[v] -= 1 23 | while count < W and occurmap[v+1] > 0: 24 | count += 1 25 | occurmap[v+1] -= 1 26 | v = v+1 27 | # print(occurmap) 28 | # print('for ', v) 29 | # print('count is ', count) 30 | if count == W: 31 | tots += 1 32 | 33 | # print('tots is ', tots) 34 | if tots * W == n: 35 | return True 36 | return False 37 | -------------------------------------------------------------------------------- /decodeString/decodeString.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def decodeString(self, s: str) -> str: 3 | stack = [] 4 | for i in range(len(s)): 5 | stack.append(s[i]) 6 | if s[i] == "]": 7 | stack.pop(-1) 8 | popped = "" 9 | str1 = "" 10 | while popped != "[": 11 | popped = stack.pop(-1) 12 | str1 = popped + str1 13 | # multiplier = stack.pop(-1) 14 | multiplier = stack.pop(-1) 15 | while multiplier.isnumeric(): 16 | if stack: 17 | multiplier = stack.pop(-1) + multiplier 18 | continue 19 | break 20 | if not multiplier[0].isnumeric(): 21 | stack.append(multiplier[0]) 22 | multiplier = multiplier[1:len(multiplier)] 23 | decodeStr = int(multiplier) * str1[1:len(str1)] 24 | stack += list(decodeStr) 25 | return "".join(stack) 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /kthlargestelement/Longest common subsequence/problem.txt: -------------------------------------------------------------------------------- 1 | Given two strings text1 and text2, return the length of their longest common subsequence. 2 | 3 | A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings. 4 | 5 | 6 | 7 | If there is no common subsequence, return 0. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: text1 = "abcde", text2 = "ace" 14 | Output: 3 15 | Explanation: The longest common subsequence is "ace" and its length is 3. 16 | Example 2: 17 | 18 | Input: text1 = "abc", text2 = "abc" 19 | Output: 3 20 | Explanation: The longest common subsequence is "abc" and its length is 3. 21 | Example 3: 22 | 23 | Input: text1 = "abc", text2 = "def" 24 | Output: 0 25 | Explanation: There is no such common subsequence, so the result is 0. 26 | 27 | 28 | Constraints: 29 | 30 | 1 <= text1.length <= 1000 31 | 1 <= text2.length <= 1000 32 | The input strings consist of lowercase English characters only. 33 | Accepted -------------------------------------------------------------------------------- /subtreeOfAnotherTree/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: 9 | 10 | def checker(s, t): 11 | if (not s and t) or (not t and s): 12 | return False 13 | if not s and not t: 14 | return True 15 | if s.val != t.val: 16 | return False 17 | 18 | return checker(s.left, t.left) and checker(s.right, t.right) 19 | 20 | 21 | def helper(s, t): 22 | if (not s and t) or (not t and s): 23 | return False 24 | if not s and not t: 25 | return True 26 | 27 | if s.val == t.val: 28 | if checker(s, t): 29 | # print('s is {0} and t is {1}'.format(s.val, t.val)) 30 | return True 31 | return helper(s.left, t) or helper(s.right, t) 32 | return helper(s, t) 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /deleteNodesAndReturnForest/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]: 9 | 10 | 11 | todelete = set(to_delete) 12 | 13 | out = [] 14 | def helper(root): 15 | 16 | if not root: 17 | return 18 | 19 | left = helper(root.left) 20 | if not left: 21 | root.left = None 22 | right = helper(root.right) 23 | if not right: 24 | root.right = None 25 | 26 | 27 | if root.val in todelete: 28 | if left: 29 | out.append(left) 30 | if right: 31 | out.append(right) 32 | return None 33 | else: 34 | return root 35 | 36 | if helper(root): 37 | out.append(root) 38 | 39 | 40 | 41 | return out -------------------------------------------------------------------------------- /verifyAlienDIctionary/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAlienSorted(self, words: List[str], order: str) -> bool: 3 | 4 | def compare(lessword, largeword): 5 | startless, startlarge = 0, 0 6 | nless, nlarge = len(lessword), len(largeword) 7 | while startless < nless and startlarge < nlarge: 8 | cless, clarge = lessword[startless], largeword[startlarge] 9 | oless, olarge = d[cless], d[clarge] 10 | if olarge < oless: 11 | return False 12 | elif oless < olarge: 13 | return True 14 | startless += 1 15 | startlarge += 1 16 | if startless >= nless: 17 | return True 18 | return False 19 | 20 | 21 | d = {} 22 | norder = len(order) 23 | for i in range(norder): 24 | c = order[i] 25 | d[c] = i 26 | 27 | nwords = len(words) 28 | for i in range(1,nwords): 29 | lessword = words[i-1] 30 | largeword = words[i] 31 | if not compare(lessword, largeword): 32 | return False 33 | return True -------------------------------------------------------------------------------- /reorderroutetomakepathleadtozero/problem.txt: -------------------------------------------------------------------------------- 1 | There are n cities numbered from 0 to n-1 and n-1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. 2 | 3 | Roads are represented by connections where connections[i] = [a, b] represents a road from city a to b. 4 | 5 | This year, there will be a big event in the capital (city 0), and many people want to travel to this city. 6 | 7 | Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed. 8 | 9 | It's guaranteed that each city can reach the city 0 after reorder. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | 16 | 17 | Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]] 18 | Output: 3 19 | Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). 20 | Example 2: 21 | 22 | 23 | 24 | Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]] 25 | Output: 2 26 | Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). 27 | Example 3: 28 | 29 | Input: n = 3, connections = [[1,0],[2,0]] 30 | Output: 0 -------------------------------------------------------------------------------- /carfleet/problem.txt: -------------------------------------------------------------------------------- 1 | N cars are going to the same destination along a one lane road. The destination is target miles away. 2 | 3 | Each car i has a constant speed speed[i] (in miles per hour), and initial position position[i] miles towards the target along the road. 4 | 5 | A car can never pass another car ahead of it, but it can catch up to it, and drive bumper to bumper at the same speed. 6 | 7 | The distance between these two cars is ignored - they are assumed to have the same position. 8 | 9 | A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. 10 | 11 | If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. 12 | 13 | 14 | How many car fleets will arrive at the destination? 15 | 16 | 17 | 18 | Example 1: 19 | 20 | Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] 21 | Output: 3 22 | Explanation: 23 | The cars starting at 10 and 8 become a fleet, meeting each other at 12. 24 | The car starting at 0 doesn't catch up to any other car, so it is a fleet by itself. 25 | The cars starting at 5 and 3 become a fleet, meeting each other at 6. 26 | Note that no other cars meet these fleets before the destination, so the answer is 3. -------------------------------------------------------------------------------- /FindKClosestElements/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: 3 | 4 | 5 | n = len(arr) 6 | diff = float('inf') 7 | pivot = 0 8 | for i in range(n): 9 | v = arr[i] 10 | if abs(x-v) < diff: 11 | diff =abs(x-v) 12 | pivot = i 13 | # print('pivot is ', pivot) 14 | start = end = pivot 15 | out = [] 16 | count = 0 17 | while (start >= 0 or end < n) and count < k: 18 | print((start,end)) 19 | count += 1 20 | if start == end: 21 | out.append(arr[start]) 22 | start -= 1 23 | end += 1 24 | continue 25 | left = float('inf') 26 | if start >= 0: 27 | left = arr[start] 28 | right = float('inf') 29 | if end < n: 30 | right = arr[end] 31 | # print('left is ', abs(x-left)) 32 | # print('right is ', abs(x-right)) 33 | if abs(x-left) <= abs(x-right): 34 | out.append(left) 35 | start -= 1 36 | else: 37 | out.append(right) 38 | end += 1 39 | return sorted(out) 40 | 41 | 42 | -------------------------------------------------------------------------------- /verifyAlienDIctionary/problem.txt: -------------------------------------------------------------------------------- 1 | In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. 2 | 3 | Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" 10 | Output: true 11 | Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted. 12 | Example 2: 13 | 14 | Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" 15 | Output: false 16 | Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted. 17 | Example 3: 18 | 19 | Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" 20 | Output: false 21 | Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info). 22 | 23 | 24 | Constraints: 25 | 26 | 1 <= words.length <= 100 27 | 1 <= words[i].length <= 20 28 | order.length == 26 29 | All characters in words[i] and order are English lowercase letters. -------------------------------------------------------------------------------- /boatsToSavePeople/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numRescueBoats(self, people: List[int], limit: int) -> int: 3 | 4 | 5 | weightMap = {} 6 | numberOfBoats = 0 7 | for person in people: 8 | if person > limit: 9 | continue 10 | if person == limit: 11 | numberOfBoats += 1 12 | continue 13 | 14 | secondperson = limit - person 15 | if secondperson in weightMap and weightMap[secondperson] >= 1: 16 | numberOfBoats += 1 17 | weightMap[secondperson] -= 1 18 | else: 19 | weightMap[person] = weightMap.get(person, 0) + 1 20 | 21 | for person in people: 22 | if person in weightMap and weightMap[person] > 0: 23 | weightMap[person] -= 1 24 | numberOfBoats += 1 25 | return numberOfBoats 26 | 27 | 28 | 29 | # for person in people: 30 | # weightMap[person] = weightMap.get(person,0) + 1 31 | 32 | # numberOfBoats = 0 33 | 34 | # for person in people: 35 | # if people > limit: 36 | # continue 37 | # if people == limit: 38 | # numberOfBoats += 1 39 | # continue 40 | 41 | # secondperson = limit - person -------------------------------------------------------------------------------- /Binarywatch/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def readBinaryWatch(self, num: int) -> List[str]: 3 | 4 | 5 | res = set() 6 | def helper(minarr, hourarr, hour, minutes, total): 7 | if hour > 11 or minutes > 59: 8 | return 9 | 10 | if total == num: 11 | hour = str(hour) 12 | if minutes < 10: 13 | minutes = '0' + str(minutes) 14 | time = '{0}:{1}'.format(hour, minutes) 15 | res.add(time) 16 | return 17 | 18 | for i in range(len(hourarr)): 19 | if total < num and hourarr[i] == 0: 20 | hourarr[i] = 1 21 | hour += 2 ** i 22 | helper(minarr, hourarr, hour, minutes, total+1) 23 | hourarr[i] = 0 24 | hour -= 2 ** i 25 | 26 | 27 | 28 | for j in range(len(minarr)): 29 | if total < num and minarr[j] == 0: 30 | minarr[j] = 1 31 | minutes += 2 ** j 32 | helper(minarr, hourarr, hour, minutes, total+1) 33 | minutes -= 2 ** j 34 | minarr[j] = 0 35 | return 36 | 37 | 38 | 39 | helper([0,0,0,0,0,0], [0,0,0,0], 0, 0, 0) 40 | # print(len(res)) 41 | return list(res) 42 | -------------------------------------------------------------------------------- /maximumWidthOfBinaryTree/problem.txt: -------------------------------------------------------------------------------- 1 | Given a binary tree, write a function to get the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. 2 | 3 | The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation. 4 | 5 | It is guaranteed that the answer will in the range of 32-bit signed integer. 6 | 7 | Example 1: 8 | 9 | Input: 10 | 11 | 1 12 | / \ 13 | 3 2 14 | / \ \ 15 | 5 3 9 16 | 17 | Output: 4 18 | Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9). 19 | Example 2: 20 | 21 | Input: 22 | 23 | 1 24 | / 25 | 3 26 | / \ 27 | 5 3 28 | 29 | Output: 2 30 | Explanation: The maximum width existing in the third level with the length 2 (5,3). 31 | Example 3: 32 | 33 | Input: 34 | 35 | 1 36 | / \ 37 | 3 2 38 | / 39 | 5 40 | 41 | Output: 2 42 | Explanation: The maximum width existing in the second level with the length 2 (3,2). 43 | Example 4: 44 | 45 | Input: 46 | 47 | 1 48 | / \ 49 | 3 2 50 | / \ 51 | 5 9 52 | / \ 53 | 6 7 54 | Output: 8 55 | Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7). -------------------------------------------------------------------------------- /insertdeletegetrandom/solution.py: -------------------------------------------------------------------------------- 1 | class RandomizedSet: 2 | 3 | def __init__(self): 4 | """ 5 | Initialize your data structure here. 6 | """ 7 | self.map = {} 8 | self.list = [] 9 | 10 | def insert(self, val: int) -> bool: 11 | """ 12 | Inserts a value to the set. Returns true if the set did not already contain the specified element. 13 | """ 14 | if val in self.map: 15 | return False 16 | self.map[val] = len(self.list) 17 | self.list.append(val) 18 | return True 19 | 20 | 21 | def remove(self, val: int) -> bool: 22 | """ 23 | Removes a value from the set. Returns true if the set contained the specified element. 24 | """ 25 | if val not in self.map: 26 | return False 27 | self.map[self.list[-1]] = self.map[val] 28 | self.list[-1], self.list[self.map[val]] = self.list[self.map[val]], self.list[-1] 29 | self.list.pop() 30 | self.map.pop(val) 31 | return True 32 | 33 | 34 | def getRandom(self) -> int: 35 | """ 36 | Get a random element from the set. 37 | """ 38 | if not self.list: 39 | return 40 | return random.choice(self.list) 41 | 42 | 43 | # Your RandomizedSet object will be instantiated and called as such: 44 | # obj = RandomizedSet() 45 | # param_1 = obj.insert(val) 46 | # param_2 = obj.remove(val) 47 | # param_3 = obj.getRandom() 48 | -------------------------------------------------------------------------------- /reorderroutetomakepathleadtozero/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minReorder(self, n: int, connections: List[List[int]]) -> int: 3 | 4 | 5 | def helper(node): 6 | # print(node) 7 | nonlocal out 8 | if node not in g: 9 | return 10 | if g[node]['color'] == 'g': 11 | return 12 | 13 | g[node]['color'] = 'g' 14 | # out = 0 15 | fromchildren = g[node]['from'] 16 | n = len(fromchildren) 17 | for i in range(n): 18 | v = fromchildren[i] 19 | helper(v) 20 | 21 | tochildren = g[node]['to'] 22 | n = len(tochildren) 23 | for i in range(n): 24 | v = tochildren[i] 25 | if g[v]['color'] == 'r': 26 | helper(v) 27 | out += 1 28 | return 29 | 30 | g = {} 31 | out = 0 32 | for source, target in connections: 33 | if source not in g: 34 | g[source] = {'to': [], 'from': [], 'color' : 'r'} 35 | 36 | if target not in g: 37 | g[target] = {'to': [], 'from': [],'color' : 'r'} 38 | 39 | # print((source, target)) 40 | g[source]['to'].append(target) 41 | g[target]['from'].append(source) 42 | # print(g) 43 | # print(g) 44 | helper(0) 45 | return out 46 | 47 | 48 | -------------------------------------------------------------------------------- /N Queens/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def solveNQueens(self, n: int) -> List[List[str]]: 3 | 4 | 5 | out = [] 6 | rows, cols = [set() for i in range(n)], [set() for i in range(n)] 7 | diag1, diag2 = [set() for i in range(2*n-1)], [set() for i in range(2*n-1)] 8 | board = [['.' for j in range(n)] for i in range(n)] 9 | # print(board) 10 | 11 | def helper(r, c, count): 12 | # print('count ', count) 13 | if count == n: 14 | # print('count cuaght') 15 | out.append([''.join(board[i]) for i in range(n)]) 16 | # print(out[-1]) 17 | return 18 | if c == n: 19 | return helper(r+1, 0, count) 20 | if r == n: 21 | return 22 | if board[r][c] != 'Q' and 'Q' not in rows[r] and 'Q' not in cols[c] and 'Q' not in diag1[r+c] and 'Q' not in diag2[(r-c)+(n-1)]: 23 | board[r][c] = 'Q' 24 | rows[r].add('Q') 25 | cols[c].add('Q') 26 | diag1[r+c].add('Q') 27 | diag2[(r-c)+(n-1)].add('Q') 28 | 29 | helper(r, c+1, count+1) 30 | 31 | board[r][c] = '.' 32 | rows[r].remove('Q') 33 | cols[c].remove('Q') 34 | diag1[r+c].remove('Q') 35 | diag2[(r-c)+(n-1)].remove('Q') 36 | 37 | return helper(r, c+1, count) 38 | 39 | helper(0,0,0) 40 | return out 41 | 42 | 43 | -------------------------------------------------------------------------------- /findfirstandlastposition/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchLeftIndex(self, arr, target, start, end): 3 | mid = int((start + end) / 2) 4 | if (end - start) < 1: 5 | return -1 6 | # print("left mid is ", mid) 7 | if arr[mid] == target and ((mid -1) < 0 or arr[mid-1] != target): 8 | return mid 9 | 10 | if target > arr[mid]: 11 | # print("went here") 12 | return self.searchLeftIndex(arr, target, mid + 1, end) 13 | else: 14 | return self.searchLeftIndex(arr, target, start, mid) 15 | 16 | def searchRightIndex(self, arr, target, start, end): 17 | mid = int((start + end) / 2) 18 | # print("The arr is ", arr[start:end+1]) 19 | # print("The mid is ", mid) 20 | if (end - start) < 1: 21 | return -1 22 | if arr[mid] == target and ((mid + 1) >= len(arr) or arr[mid+1] != target): 23 | return mid 24 | 25 | if target < arr[mid]: 26 | return self.searchRightIndex(arr, target, start, mid) 27 | else: 28 | return self.searchRightIndex(arr, target, mid + 1, end) 29 | def searchRange(self, nums: List[int], target: int) -> List[int]: 30 | # nums = [2, 2] 31 | # target = 3 32 | if not nums: 33 | return [-1, -1] 34 | if len(nums) == 1 and target in nums: 35 | return [0, 0] 36 | left = self.searchLeftIndex(nums, target, 0, len(nums)) 37 | start = 0 38 | if left != -1: 39 | start = left 40 | right = self.searchRightIndex(nums, target, start, len(nums)) 41 | return [left, right] 42 | 43 | 44 | -------------------------------------------------------------------------------- /SerializeAndDeserializeBST/solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | 9 | 10 | 11 | 12 | 13 | class Codec: 14 | 15 | def insert(self, node, val): 16 | if val < node.val: 17 | if not node.left: 18 | node.left = TreeNode(val) 19 | return 20 | self.insert(node.left, val) 21 | elif val > node.val: 22 | if not node.right: 23 | node.right = TreeNode(val) 24 | return 25 | self.insert(node.right, val) 26 | 27 | def serial(self, root, basket): 28 | 29 | basket.append(root.val) 30 | if root.left: 31 | basket = self.serial(root.left, basket) 32 | if root.right: 33 | basket = self.serial(root.right, basket) 34 | return basket 35 | def serialize(self, root: TreeNode) -> str: 36 | """Encodes a tree to a single string. 37 | """ 38 | if not root: 39 | return [] 40 | 41 | temp = self.serial(root, []) 42 | # print('temp is ', temp) 43 | return temp 44 | 45 | 46 | def deserialize(self, data: str) -> TreeNode: 47 | """Decodes your encoded data to tree. 48 | """ 49 | # print('chee') 50 | 51 | if not data: 52 | return None 53 | # print(data) 54 | root = TreeNode(data[0]) 55 | n = len(data) 56 | for i in range(1, n): 57 | v = data[i] 58 | self.insert(root, v) 59 | return root 60 | 61 | # Your Codec object will be instantiated and called as such: 62 | # codec = Codec() 63 | # codec.deserialize(codec.serialize(root)) -------------------------------------------------------------------------------- /fractiontoreocurringdecimal/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fractionToDecimal(self, numerator: int, denominator: int) -> str: 3 | sign = -1 if (numerator * denominator) < 0 else 1 4 | numerator, denominator = abs(numerator), abs(denominator) 5 | res = numerator // denominator 6 | res = str(res) 7 | rem = numerator % denominator 8 | denom, rem = str(denominator), str(rem) 9 | afterDec = '' 10 | haveSeen = {} 11 | start = '' 12 | ind = 0 13 | haveSeen[rem] = len(rem) + 1 14 | while int(rem) != 0: 15 | tempRem = rem 16 | while len(tempRem) < len(denom): 17 | tempRem += '0' 18 | 19 | if int(tempRem) < int(denom) and len(rem) < len(denom): 20 | numb = str(0) 21 | rem = tempRem 22 | elif int(tempRem) < int(denom): 23 | tempRem += '0' 24 | numb = str(int(tempRem) // int(denom)) 25 | rem = str(int(tempRem) % int(denom)) 26 | else: 27 | numb = str(int(tempRem) // int(denom)) 28 | rem = str(int(tempRem) % int(denom)) 29 | 30 | if rem in haveSeen: 31 | i = haveSeen[rem] 32 | res += numb 33 | res = res[0:i] + '(' + res[i:] + ')' 34 | print('numb is ', rem) 35 | print('location is ', haveSeen[rem]) 36 | break 37 | 38 | if ind == 0: 39 | res += '.' 40 | ind = len(res) + 1 41 | haveSeen[rem] = ind 42 | res += numb 43 | ind += 1 44 | 45 | 46 | print('res is ', res) 47 | print('afterDec is ', afterDec) 48 | print('start is ', start) 49 | print('has seen is ', haveSeen) 50 | return res if sign == 1 else '-' + res 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /stringToIntegar/README.md: -------------------------------------------------------------------------------- 1 | # String to Integar (atoi) 2 | 3 | ## DESCRIPTION 4 | 5 | Implement atoi which converts a string to an integer. 6 | 7 | The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. 8 | 9 | The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. 10 | 11 | If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. 12 | 13 | If no valid conversion could be performed, a zero value is returned. 14 | 15 | Note: 16 | 17 | Only the space character ' ' is considered as whitespace character. 18 | Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-231, 231 - 1]. If the numerical value is out of the range of representable values, INT_MAX (231 - 1) or INT_MIN (-231) is returned. 19 | 20 | 21 | ### EXAMPLE 1 22 | 23 | ```BASH 24 | Input: "42" 25 | Output: 42 26 | Example 2: 27 | ``` 28 | ### EXAMPLE 2 29 | 30 | ```BASH 31 | Input: " -42" 32 | Output: -42 33 | Explanation: The first non-whitespace character is '-', which is the minus sign. 34 | Then take as many numerical digits as possible, which gets 42. 35 | ``` 36 | ### EXAMPLE 3 37 | 38 | ```BASH 39 | Input: "4193 with words" 40 | Output: 4193 41 | Explanation: Conversion stops at digit '3' as the next character is not a numerical digit. 42 | ``` 43 | 44 | ### EXAMPLE 4 45 | 46 | ```BASH 47 | Input: "words and 987" 48 | Output: 0 49 | Explanation: The first non-whitespace character is 'w', which is not a numerical 50 | digit or a +/- sign. Therefore no valid conversion could be performed. 51 | ``` 52 | ### EXAMPLE 5 53 | 54 | ```BASH 55 | Input: "-91283472332" 56 | Output: -2147483648 57 | Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. 58 | Thefore INT_MIN (-231) is returned. 59 | ``` 60 | 61 | 62 | ## License 63 | [LEETCODE](https://leetcode.com/problems/string-to-integer-atoi/) --------------------------------------------------------------------------------