├── README.md └── leetcode ├── 01-two-sum.py ├── 1004-max-consecutive-ones-III.py ├── 125-valid-palindrome.py ├── 13-roman-to-integer.py ├── 14-longest-common-prefix.py ├── 1413-minimum-value-to-get-positive-step-by-step-sum.py ├── 1426-counting-elements.py ├── 1480-running-sum-of-1d-array.py ├── 151-reverse-words-in-a-string.py ├── 167-two-sum-II-input-array-is-sorted.py ├── 1768-merge-strings-alternately.py ├── 1832-check-if-sentence-is-pangram.py ├── 1941-check-if-all-characters-have-equal-number-of-occurrences.py ├── 20-valid-parentheses.py ├── 2090-k-radius-subarray-averages.py ├── 21-merge-two-sorted-lists.py ├── 217-contains-duplicate.py ├── 2248-intersection-of-multiple-arrays.py ├── 2270-number-of-ways-to-split-array.py ├── 2351-first-letter-to-appear-twice.py ├── 242-valid-anagram.py ├── 26-remove-duplicates-from-sorted-array.py ├── 268-missing-number.py ├── 27-remove-element.py ├── 278-first-bad-version.py ├── 28-find-index-of-first-occurrence-in-string.py ├── 283-move-zeroes.py ├── 344-reverse-string.py ├── 35-search-insert-position.py ├── 392-is-subsequence.py ├── 557-reverse-words-in-a-string-III.py ├── 643-maximum-average-subarray-I.py ├── 66-plus-one.py ├── 69-sqrt-x.py ├── 704-binary-search.py ├── 713-subarray-product-less-than-k.py ├── 724-find-pivot-index.py ├── 88-merge-sorted-array.py ├── 917-reverse-only-letters.py └── 977-squares-of-a-sorted-array.py /README.md: -------------------------------------------------------------------------------- 1 | # Solving Problems with Python 2 | Solving problems from LeetCode using Python language. 3 | 4 | ## Problems Solved 5 | 6 | ### LeetCode 7 | 8 | - [01 - Two Sum](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/01-two-sum.py) 9 | - [13 - Roman to Integer](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/13-roman-to-integer.py) 10 | - [14 - Longest Common Prefix](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/14-longest-common-prefix.py) 11 | - [20 - Valid Parentheses](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/20-valid-parentheses.py) 12 | - [21 - Merge Two Sorted Lists](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/21-merge-two-sorted-lists.py) 13 | - [26 - Remove Duplicates from Sorted Array](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/26-remove-duplicates-from-sorted-array.py) 14 | - [27 - Remove Element](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/27-remove-element.py) 15 | - [28 - Find the Index of the First Occurrence in a String](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/28-find-index-of-first-occurrence-in-string.py) 16 | - [35 - Search Insert Position](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/35-search-insert-position.py) 17 | - [66 - Plus One](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/66-plus-one.py) 18 | - [69 - Sqrt(x)](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/69-sqrt-x.py) 19 | - [88 - Merge Sorted Array](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/88-merge-sorted-array.py) 20 | - [125 - Valid Palindrome](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/125-valid-palindrome.py) 21 | - [151 - Reverse Words in a String](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/151-reverse-words-in-a-string.py) 22 | - [167 - Two Sum II - Input Array Is Sorted](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/167-two-sum-II-input-array-is-sorted.py) 23 | - [217 - Contains Duplicate](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/217-contains-duplicate.py) 24 | - [242 - Valid Anagram](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/242-valid-anagram.py) 25 | - [268 - Missing Number](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/268-missing-number.py) 26 | - [278 - First Bad Version](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/278-first-bad-version.py) 27 | - [283 - Move Zeroes](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/283-move-zeroes.py) 28 | - [344 - Reverse String](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/344-reverse-string.py) 29 | - [392 - Is Subsequence](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/392-is-subsequence.py) 30 | - [557 - Reverse Words in a String III](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/557-reverse-words-in-a-string-III.py) 31 | - [643 - Maximum Average Subarray I](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/643-maximum-average-subarray-I.py) 32 | - [704 - Binary Search](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/704-binary-search.py) 33 | - [713 - Subarray Product Less Than K](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/713-subarray-product-less-than-k.py) 34 | - [724 - Find Pivot Index](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/724-find-pivot-index.py) 35 | - [917 - Reverse Only Letters](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/917-reverse-only-letters.py) 36 | - [977 - Squares of a Sorted Array](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/977-squares-of-a-sorted-array.py) 37 | - [1004 - Max Consecutive Ones III](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/1004-max-consecutive-ones-III.py) 38 | - [1413 - Minimum Value to Get Positive Step by Step Sum](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/1413-minimum-value-to-get-positive-step-by-step-sum.py) 39 | - [1426 - Counting Elements](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/1426-counting-elements.py) 40 | - [1480 - Running Sum of 1D Array](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/1480-running-sum-of-1d-array.py) 41 | - [1768 - Merge Strings Alternately](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/1768-merge-strings-alternately.py) 42 | - [1832 - Check if the Sentence Is Pangram](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/1832-check-if-sentence-is-pangram.py) 43 | - [1941 - Check if All Characters Have Equal Number of Occurrences](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/1941-check-if-all-characters-have-equal-number-of-occurrences.py) 44 | - [2090 - K Radius Subarray Averages](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/2090-k-radius-subarray-averages.py) 45 | - [2248 - Intersection of Multiple Arrays](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/2248-intersection-of-multiple-arrays.py) 46 | - [2270 - Number of Ways to Split Array](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/2270-number-of-ways-to-split-array.py) 47 | - [2351 - First Letter to Appear Twice](https://github.com/giovannamoeller/solving-problems-python/blob/main/leetcode/2351-first-letter-to-appear-twice.py) -------------------------------------------------------------------------------- /leetcode/01-two-sum.py: -------------------------------------------------------------------------------- 1 | def twoSum(nums, target: int): 2 | hashMap = {} 3 | for i in range(len(nums)): 4 | valueToBeFound = target - nums[i] 5 | if valueToBeFound in hashMap: 6 | return [hashMap[valueToBeFound], i] 7 | hashMap[nums[i]] = i 8 | 9 | print(twoSum([2, 7, 11, 15], 9)) 10 | print(twoSum([3, 2, 4], 6)) 11 | print(twoSum([3, 3], 6)) -------------------------------------------------------------------------------- /leetcode/1004-max-consecutive-ones-III.py: -------------------------------------------------------------------------------- 1 | def longestOnes(nums, k): 2 | left = curr = ans = 0 3 | 4 | for right in range(len(nums)): 5 | if nums[right] == 0: curr += 1 6 | 7 | while curr > k: 8 | if nums[left] == 0: 9 | curr -= 1 10 | left += 1 11 | 12 | ans = max(ans, right - left + 1) 13 | 14 | return ans 15 | 16 | print(longestOnes([1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], 2)) 17 | print(longestOnes([0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1], 3)) -------------------------------------------------------------------------------- /leetcode/125-valid-palindrome.py: -------------------------------------------------------------------------------- 1 | def isPalindrome(s): 2 | 3 | nonAlphabetical = ['@', ' ', ',', '.', ':', ';', '!', '#', '$', '%', '_', '"', "'", '\\', '/', '-', '{', '}', '(', ')','[', ']', '?', '`'] 4 | 5 | for x in nonAlphabetical: 6 | s = s.replace(x, '') 7 | s = s.lower() 8 | 9 | l = 0 10 | r = len(s) - 1 11 | 12 | while r > l: 13 | if s[l] != s[r]: return False 14 | r -= 1 15 | l += 1 16 | 17 | return True 18 | 19 | print(isPalindrome("A man, a plan, a canal: Panama")) 20 | print(isPalindrome("race a car")) -------------------------------------------------------------------------------- /leetcode/13-roman-to-integer.py: -------------------------------------------------------------------------------- 1 | def romanToInt(s): 2 | romanHash = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } 3 | especialInstances = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900 } 4 | count = 0 5 | 6 | for instance in especialInstances: 7 | if instance in s: 8 | count += especialInstances[instance] 9 | s = s.replace(instance, "") 10 | 11 | for char in s: 12 | count += romanHash[char] 13 | 14 | return count 15 | 16 | print(romanToInt('III')) 17 | print(romanToInt('LVIII')) 18 | print(romanToInt('MCMXCIV')) 19 | -------------------------------------------------------------------------------- /leetcode/14-longest-common-prefix.py: -------------------------------------------------------------------------------- 1 | def longestCommonPrefix(strs): 2 | if len(strs) == 0: return "" 3 | prefix = strs[0] 4 | 5 | for i in range(1, len(strs)): 6 | while strs[i].find(prefix) != 0: 7 | prefix = prefix[:-1] 8 | 9 | return prefix 10 | 11 | print(longestCommonPrefix(['flower', 'flow', 'flight'])) 12 | print(longestCommonPrefix(['reflower', 'flow', 'flight'])) 13 | print(longestCommonPrefix(['dog', 'racecar', 'car'])) 14 | print(longestCommonPrefix(['c', 'acc', 'ccc'])) -------------------------------------------------------------------------------- /leetcode/1413-minimum-value-to-get-positive-step-by-step-sum.py: -------------------------------------------------------------------------------- 1 | def minStartValue(nums): 2 | prefix = [nums[0]] 3 | j = ans = 0 4 | 5 | for i in range(1, len(nums)): 6 | prefix.append(nums[i] + prefix[j]) 7 | j += 1 8 | 9 | for i in range(len(prefix)): 10 | if prefix[i] < ans: 11 | ans = prefix[i] 12 | 13 | return 1 - (ans) 14 | 15 | print(minStartValue([-3, 2, -3, 4, 2])) 16 | print(minStartValue([1, 2])) 17 | print(minStartValue([1, -2, -3])) -------------------------------------------------------------------------------- /leetcode/1426-counting-elements.py: -------------------------------------------------------------------------------- 1 | def countElements(arr): 2 | seen = set(arr) 3 | count = 0 4 | for number in arr: 5 | if number + 1 in seen: count += 1 6 | return count 7 | 8 | print(countElements([1, 2, 3])) 9 | print(countElements([1, 1, 3, 3, 5, 5, 7, 7])) -------------------------------------------------------------------------------- /leetcode/1480-running-sum-of-1d-array.py: -------------------------------------------------------------------------------- 1 | def runningSum(nums): 2 | prefix = [nums[0]] 3 | j = 0 4 | 5 | for i in range(1, len(nums)): 6 | prefix.append(nums[i] + prefix[j]) 7 | j += 1 8 | 9 | return prefix 10 | 11 | print(runningSum([1, 1, 1, 1, 1])) 12 | print(runningSum([1, 2, 3, 4])) 13 | print(runningSum([3, 1, 2, 10, 1])) -------------------------------------------------------------------------------- /leetcode/151-reverse-words-in-a-string.py: -------------------------------------------------------------------------------- 1 | def reverseWords(s): 2 | words = s.split(' ') 3 | for i in range(len(words) - 1, -1, -1): 4 | if words[i] == '': 5 | words.pop(i) 6 | left = 0 7 | right = len(words) - 1 8 | while right > left: 9 | aux = words[right] 10 | words[right] = words[left] 11 | words[left] = aux 12 | left += 1 13 | right -= 1 14 | 15 | return ' '.join(words) 16 | 17 | print(reverseWords("the sky is blue")) 18 | print(reverseWords(" hello world ")) 19 | print(reverseWords("a good example")) -------------------------------------------------------------------------------- /leetcode/167-two-sum-II-input-array-is-sorted.py: -------------------------------------------------------------------------------- 1 | def twoSum(numbers, target): 2 | l = 0 3 | r = len(numbers) - 1 4 | 5 | while r > l: 6 | if numbers[r] + numbers[l] > target: r -= 1 7 | elif numbers[r] + numbers[l] < target: l += 1 8 | else: return [l + 1, r + 1] 9 | 10 | print(twoSum([2, 7, 11, 15], 9)) 11 | print(twoSum([2, 3, 4], 6)) 12 | print(twoSum([-1, 0], -1)) -------------------------------------------------------------------------------- /leetcode/1768-merge-strings-alternately.py: -------------------------------------------------------------------------------- 1 | def mergeAlternately(word1, word2): 2 | mergedStrs = '' 3 | i = j = 0 4 | 5 | while i < len(word1) and j < len(word2): 6 | mergedStrs += word1[i] 7 | mergedStrs += word2[j] 8 | i += 1 9 | j += 1 10 | 11 | while i < len(word1): 12 | mergedStrs += word1[i] 13 | i += 1 14 | 15 | while j < len(word2): 16 | mergedStrs += word2[j] 17 | j += 1 18 | 19 | return mergedStrs 20 | 21 | print(mergeAlternately('abc', 'pqr')) 22 | print(mergeAlternately('ab', 'pqrs')) 23 | -------------------------------------------------------------------------------- /leetcode/1832-check-if-sentence-is-pangram.py: -------------------------------------------------------------------------------- 1 | def checkIfPangram(sentence): 2 | seen = set(sentence) 3 | return len(seen) == 26 4 | 5 | print(checkIfPangram('thequickbrownfoxjumpsoverthelazydog')) 6 | print(checkIfPangram('leetcode')) 7 | -------------------------------------------------------------------------------- /leetcode/1941-check-if-all-characters-have-equal-number-of-occurrences.py: -------------------------------------------------------------------------------- 1 | def areOccurrencesEqual(s): 2 | hash = {} 3 | for c in s: 4 | if not c in hash: hash[c] = 1 5 | else: hash[c] += 1 6 | return len(set(hash.values())) == 1 7 | 8 | print(areOccurrencesEqual('abacbc')) 9 | print(areOccurrencesEqual('aaabb')) -------------------------------------------------------------------------------- /leetcode/20-valid-parentheses.py: -------------------------------------------------------------------------------- 1 | def isValid(s): 2 | stack = [] 3 | openClosingHash = { 4 | ')': '(', 5 | '}': '{', 6 | ']': '[' 7 | } 8 | 9 | for char in s: 10 | if char in openClosingHash: 11 | if len(stack) != 0 and stack[-1] == openClosingHash[char]: 12 | stack.pop() 13 | else: 14 | return False 15 | else: 16 | stack.append(char) 17 | 18 | return len(stack) == 0 19 | 20 | print(isValid('()')) 21 | print(isValid("()[]{}")) 22 | print(isValid('(]')) 23 | print(isValid('(][')) 24 | print(isValid('(][)')) -------------------------------------------------------------------------------- /leetcode/2090-k-radius-subarray-averages.py: -------------------------------------------------------------------------------- 1 | import math 2 | #floor 3 | 4 | def getAverages(nums, k): 5 | prefix = [nums[0]] 6 | avgs = [] 7 | j = 0 8 | 9 | for i in range(1, len(nums)): 10 | prefix.append(nums[i] + prefix[j]) 11 | j += 1 12 | 13 | for i in range(len(nums)): 14 | if i < k or len(nums) - i <= k: 15 | avgs.append(-1) 16 | else: 17 | sum = prefix[i + k] - prefix[i - k] + nums[i - k] 18 | length = i + k - (i - k) + 1 19 | avgs.append(math.floor(sum / length)) 20 | 21 | return avgs 22 | 23 | print(getAverages([7, 4, 3, 9, 1, 8, 5, 2, 6], 3)) 24 | print(getAverages([8], 1000)) 25 | -------------------------------------------------------------------------------- /leetcode/21-merge-two-sorted-lists.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val = 0, next = None): 3 | self.val = val 4 | self.next = next 5 | 6 | def mergeTwoLists(list1, list2): 7 | head = sortedList = ListNode() 8 | 9 | while list1 and list2: 10 | if list1.val < list2.val: 11 | sortedList.next = list1 12 | list1 = list1.next 13 | else: 14 | sortedList.next = list2 15 | list2 = list2.next 16 | sortedList = sortedList.next 17 | 18 | if list1: 19 | sortedList.next = list1 20 | if list2: 21 | sortedList.next = list2 22 | 23 | # while head: 24 | #print(head.val, end=' ') 25 | #head = head.next 26 | 27 | return head.next 28 | 29 | list01 = ListNode(1) 30 | list01.next = ListNode(2) 31 | list01.next.next = ListNode(4) 32 | 33 | list02 = ListNode(1) 34 | list02.next = ListNode(3) 35 | list02.next.next = ListNode(4) 36 | 37 | print(mergeTwoLists(list01, list02)) -------------------------------------------------------------------------------- /leetcode/217-contains-duplicate.py: -------------------------------------------------------------------------------- 1 | def containsDuplicate(nums): 2 | hashNums = {} 3 | for i in range(len(nums)): 4 | if nums[i] in hashNums: 5 | return True 6 | hashNums[nums[i]] = i 7 | return False 8 | 9 | print(containsDuplicate([1, 2, 3, 1])) 10 | print(containsDuplicate([1, 2, 3, 4])) 11 | print(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2])) -------------------------------------------------------------------------------- /leetcode/2248-intersection-of-multiple-arrays.py: -------------------------------------------------------------------------------- 1 | def intersection(nums): 2 | hashMap = {} 3 | ans = [] 4 | for list in nums: 5 | for x in list: 6 | if x in hashMap: hashMap[x] += 1 7 | else: hashMap[x] = 1 8 | 9 | for key in hashMap: 10 | if hashMap[key] == len(nums): ans.append(key) 11 | 12 | return sorted(ans) 13 | 14 | print(intersection([[3,1,2,4,5],[1,2,3,4],[3,4,5,6]])) 15 | print(intersection([[1,2,3],[4,5,6]])) -------------------------------------------------------------------------------- /leetcode/2270-number-of-ways-to-split-array.py: -------------------------------------------------------------------------------- 1 | def waysToSplitArray(nums): 2 | left_section = ans = 0 3 | total = sum(nums) 4 | 5 | for i in range(len(nums) - 1): 6 | left_section += nums[i] 7 | right_section = total - left_section 8 | if left_section >= right_section: 9 | ans += 1 10 | 11 | return ans 12 | 13 | print(waysToSplitArray([10, 4, -8, 7])) -------------------------------------------------------------------------------- /leetcode/2351-first-letter-to-appear-twice.py: -------------------------------------------------------------------------------- 1 | def repeatedCharacter(s): 2 | charSet = set() 3 | 4 | for c in s: 5 | if c in charSet: return c 6 | charSet.add(c) 7 | 8 | print(repeatedCharacter('abccbaacz')) 9 | print(repeatedCharacter('abcdd')) -------------------------------------------------------------------------------- /leetcode/242-valid-anagram.py: -------------------------------------------------------------------------------- 1 | def isAnagram(s, t): 2 | hashMap = {} 3 | 4 | if len(s) != len(t): return False 5 | 6 | for char in s: 7 | if char in hashMap: hashMap[char] += 1 8 | else: hashMap[char] = 1 9 | 10 | for char in t: 11 | if char not in hashMap or hashMap[char] == 0: 12 | return False 13 | else: 14 | hashMap[char] -= 1 15 | return True 16 | 17 | print(isAnagram('anagram', 'nagaram')) 18 | print(isAnagram('rat', 'car')) 19 | print(isAnagram('a', 'ab')) 20 | print(isAnagram('aacc', 'ccac')) -------------------------------------------------------------------------------- /leetcode/26-remove-duplicates-from-sorted-array.py: -------------------------------------------------------------------------------- 1 | def removeDuplicates(nums): 2 | k = 1 3 | for i in range(1, len(nums)): 4 | if nums[i] != nums[i - 1]: 5 | nums[k] = nums[i] 6 | k += 1 7 | return k 8 | 9 | print(removeDuplicates([1, 1, 2])) 10 | print(removeDuplicates([1, 1, 2, 3, 4, 4, 4])) -------------------------------------------------------------------------------- /leetcode/268-missing-number.py: -------------------------------------------------------------------------------- 1 | def missingNumber(nums): 2 | n = len(nums) 3 | seen = set(nums) 4 | 5 | for i in range(n + 1): 6 | if not i in seen: return i 7 | 8 | print(missingNumber([3, 0, 1])) 9 | print(missingNumber([0, 1])) 10 | print(missingNumber([9, 6, 4, 2, 3, 5, 7, 0, 1])) -------------------------------------------------------------------------------- /leetcode/27-remove-element.py: -------------------------------------------------------------------------------- 1 | def removeElement(nums, val): 2 | k = 0 3 | for i in range(len(nums)): 4 | if nums[i] != val: 5 | nums[k] = nums[i] 6 | k += 1 7 | return k 8 | 9 | print(removeElement([3, 2, 2, 3], 3)) 10 | print(removeElement([0, 1, 2, 2, 3, 0, 4, 2], 2)) -------------------------------------------------------------------------------- /leetcode/278-first-bad-version.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def isBadVersion(n, bad = 4): 4 | return n >= bad 5 | 6 | def firstBadVersion(n): 7 | s = 1 8 | e = n 9 | while e >= s: 10 | m = math.floor((e + s) / 2) 11 | if isBadVersion(m) == True and isBadVersion(m - 1) == False: return m 12 | elif isBadVersion(m) == False: s = m + 1 13 | else: e = m 14 | return -1 15 | 16 | print(firstBadVersion(5)) 17 | print(firstBadVersion(1)) 18 | print(firstBadVersion(3)) -------------------------------------------------------------------------------- /leetcode/28-find-index-of-first-occurrence-in-string.py: -------------------------------------------------------------------------------- 1 | def strStr(haystack, needle): 2 | #return haystack.find(needle) 3 | if len(needle) > len(haystack): 4 | return -1 5 | 6 | j = 0 7 | 8 | while j < len(haystack): 9 | if haystack[j:len(needle) + j] == needle: 10 | return j 11 | j += 1 12 | 13 | return -1 14 | 15 | print(strStr("mississippi", "issi")) 16 | print(strStr("leetcode", "leeto")) 17 | print(strStr("leetcode", "co")) 18 | print(strStr("aaaaa", "bba")) 19 | print(strStr("aaa", "aaaa")) 20 | print(strStr("mississipi", "issipi")) 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /leetcode/283-move-zeroes.py: -------------------------------------------------------------------------------- 1 | def moveZeroes(nums): 2 | i = j = 0 3 | while i < len(nums) and j < len(nums): 4 | if nums[i] == 0: 5 | i += 1 6 | else: 7 | aux = nums[i] 8 | nums[i] = nums[j] 9 | nums[j] = aux 10 | j += 1 11 | i += 1 12 | print(nums) 13 | 14 | moveZeroes([0, 1, 0, 3, 12]) 15 | moveZeroes([0]) -------------------------------------------------------------------------------- /leetcode/344-reverse-string.py: -------------------------------------------------------------------------------- 1 | def reverseString(s): 2 | l = 0 3 | r = len(s) - 1 4 | 5 | while r > l: 6 | aux = s[r] 7 | s[r] = s[l] 8 | s[l] = aux 9 | r -= 1 10 | l += 1 11 | 12 | return s 13 | 14 | print(reverseString(["h","e","l","l","o"])) 15 | print(reverseString(["H","a","n","n","a","h"])) -------------------------------------------------------------------------------- /leetcode/35-search-insert-position.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def searchInsert(nums, target): 4 | s = 0 5 | e = len(nums) - 1 6 | while e >= s: 7 | m = math.floor((e + s) / 2) 8 | if nums[m] > target: e = m - 1 9 | elif nums[m] < target: s = m + 1 10 | else: return m 11 | return e + 1 12 | 13 | print(searchInsert([1, 3, 5, 6], 5)) 14 | print(searchInsert([1, 3, 5, 6], 2)) 15 | print(searchInsert([1, 3, 5, 6], 7)) -------------------------------------------------------------------------------- /leetcode/392-is-subsequence.py: -------------------------------------------------------------------------------- 1 | def isSubsequence(s, t): 2 | if len(s) > len(t): return False 3 | i = j = 0 4 | while i < len(s) and j < len(t): 5 | if s[i] == t[j]: 6 | i += 1 7 | j += 1 8 | 9 | return i == len(s) 10 | 11 | 12 | print(isSubsequence('abc', 'ahbgdc')) 13 | print(isSubsequence('axc', 'ahbgdc')) -------------------------------------------------------------------------------- /leetcode/557-reverse-words-in-a-string-III.py: -------------------------------------------------------------------------------- 1 | def reverseWords(s): 2 | #return " ".join([x[::-1] for x in s.split()]) 3 | charArr = [] 4 | for char in s: 5 | charArr.append(char) 6 | left = right = 0 7 | for i in range(len(charArr)): 8 | if charArr[i] == ' ' or i == len(charArr) - 1: 9 | right = i - 1 if charArr[i] == ' ' else i 10 | while right > left: 11 | aux = charArr[left] 12 | charArr[left] = charArr[right] 13 | charArr[right] = aux 14 | right -= 1 15 | left += 1 16 | left = i + 1 17 | return ''.join(charArr) 18 | 19 | print(reverseWords("Let's take LeetCode contest")) 20 | print(reverseWords("God Ding")) -------------------------------------------------------------------------------- /leetcode/643-maximum-average-subarray-I.py: -------------------------------------------------------------------------------- 1 | def findMaxAverage(nums, k): 2 | curr = ans = 0 3 | 4 | for i in range(k): 5 | curr += nums[i] 6 | 7 | ans = curr 8 | 9 | for i in range(k, len(nums)): 10 | curr += nums[i] - nums[i - k] 11 | ans = max(ans, curr) 12 | 13 | return ans / k 14 | 15 | print(findMaxAverage([1, 12, -5, -6, 50, 3], 4)) 16 | print(findMaxAverage([5], 1)) -------------------------------------------------------------------------------- /leetcode/66-plus-one.py: -------------------------------------------------------------------------------- 1 | def plusOne(digits): 2 | for i in range(len(digits) - 1, -1, -1): 3 | if digits[i] < 9: 4 | digits[i] += 1 5 | return digits 6 | digits[i] = 0 7 | 8 | return [1] + digits 9 | 10 | print(plusOne([1, 2, 3])) 11 | print(plusOne([1, 2, 9])) 12 | print(plusOne([4, 3, 2, 1])) 13 | print(plusOne([9])) 14 | print(plusOne([9, 9])) 15 | print(plusOne([2, 9])) -------------------------------------------------------------------------------- /leetcode/69-sqrt-x.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def mySqrt(x): 4 | start = 0 5 | end = x 6 | res = 0 7 | while end >= start: 8 | mid = math.ceil((start + end) / 2) 9 | if (mid * mid) > x: 10 | end = mid - 1 11 | elif (mid * mid) < x: 12 | start = mid + 1 13 | res = mid 14 | else: return mid 15 | return res 16 | 17 | print(mySqrt(4)) 18 | print(mySqrt(8)) 19 | print(mySqrt(9)) 20 | print(mySqrt(10)) 21 | print(mySqrt(36)) 22 | print(mySqrt(2147395599)) -------------------------------------------------------------------------------- /leetcode/704-binary-search.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def search(nums, target): 4 | s = 0 5 | e = len(nums) - 1 6 | while e >= s: 7 | m = math.floor((s + e) / 2) 8 | if nums[m] > target: 9 | e = m - 1 10 | elif nums[m] < target: 11 | s = m + 1 12 | else: return m 13 | return -1 14 | 15 | print(search([-1, 0, 3, 5, 9, 12], 9)) 16 | print(search([-1, 0, 3, 5, 9, 12], 2)) -------------------------------------------------------------------------------- /leetcode/713-subarray-product-less-than-k.py: -------------------------------------------------------------------------------- 1 | def numSubarrayProductLessThanK(nums, k): 2 | if k <= 1: return 0 3 | 4 | left = ans = 0 5 | curr = 1 6 | 7 | for right in range(len(nums)): 8 | curr *= nums[right] 9 | while curr >= k: 10 | curr /= nums[left] 11 | left += 1 12 | ans += right - left + 1 13 | 14 | return ans 15 | 16 | print(numSubarrayProductLessThanK([10, 5, 2, 6], 100)) -------------------------------------------------------------------------------- /leetcode/724-find-pivot-index.py: -------------------------------------------------------------------------------- 1 | def pivotIndex(nums): 2 | left = 0 3 | right = sum(nums) 4 | for i in range(len(nums)): 5 | right -= nums[i] 6 | if left == right: return i 7 | left += nums[i] 8 | return -1 9 | 10 | print(pivotIndex([1, 7, 3, 6, 5, 6])) 11 | print(pivotIndex([1, 2, 3])) 12 | print(pivotIndex([2, 1, -1])) -------------------------------------------------------------------------------- /leetcode/88-merge-sorted-array.py: -------------------------------------------------------------------------------- 1 | def merge(nums1, m, nums2, n): 2 | i = m - 1 3 | j = n - 1 4 | k = m + n - 1 5 | 6 | while i >= 0 and j >= 0: 7 | if nums1[i] > nums2[j]: 8 | nums1[k] = nums1[i] 9 | i -= 1 10 | else: 11 | nums1[k] = nums2[j] 12 | j -= 1 13 | k -= 1 14 | 15 | while j >= 0: 16 | nums1[k] = nums2[j] 17 | j -= 1 18 | k -= 1 19 | 20 | while i >= 0: 21 | nums1[k] = nums1[i] 22 | i -= 1 23 | k -= 1 24 | 25 | print(nums1) 26 | 27 | merge([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3) 28 | merge([4, 5, 6, 0, 0, 0], 3, [1, 2, 3], 3) 29 | merge([1], 1, [], 0) 30 | merge([0], 0, [1], 1) 31 | -------------------------------------------------------------------------------- /leetcode/917-reverse-only-letters.py: -------------------------------------------------------------------------------- 1 | def isCharacterValid(char): 2 | return (ord(char) >= 65 and ord(char) <= 90) or (ord(char) >= 97 and ord(char) <= 122) 3 | 4 | def reverseOnlyLetters(s): 5 | charArr = [] 6 | 7 | for char in s: 8 | charArr.append(char) 9 | 10 | left = 0 11 | right = len(charArr) - 1 12 | 13 | while right > left: 14 | if not isCharacterValid(charArr[left]): 15 | left += 1 16 | continue 17 | if not isCharacterValid(charArr[right]): 18 | right -= 1 19 | continue 20 | aux = charArr[left] 21 | charArr[left] = charArr[right] 22 | charArr[right] = aux 23 | left += 1 24 | right -= 1 25 | 26 | return ''.join(charArr) 27 | 28 | print(reverseOnlyLetters("ab-cd")) 29 | print(reverseOnlyLetters("a-bC-dEf-ghIj")) 30 | print(reverseOnlyLetters("Test1ng-Leet=code-Q!")) -------------------------------------------------------------------------------- /leetcode/977-squares-of-a-sorted-array.py: -------------------------------------------------------------------------------- 1 | def sortedSquares(nums): 2 | l = 0 3 | r = k = len(nums) - 1 4 | ans = [0] * (k + 1) 5 | 6 | while r >= l: 7 | if nums[l] * nums[l] > nums[r] * nums[r]: 8 | ans[k] = (nums[l] * nums[l]) 9 | l += 1 10 | else: 11 | ans[k] = (nums[r] * nums[r]) 12 | r -= 1 13 | k -= 1 14 | 15 | return ans #ans[::-1] 16 | 17 | print(sortedSquares([-4, -1, 0, 3, 10])) 18 | print(sortedSquares([-7, -3, 2, 3, 11])) --------------------------------------------------------------------------------