diff --git a/.github/ISSUE_TEMPLATE/pyhtonalgorithms-issues.md b/.github/ISSUE_TEMPLATE/pyhtonalgorithms-issues.md deleted file mode 100644 index 2b5a20a..0000000 --- a/.github/ISSUE_TEMPLATE/pyhtonalgorithms-issues.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -name: PyhtonAlgorithms Issues -about: Template to commit an Issue -title: '' -labels: '' -assignees: '' - ---- - -### Subject of the issue -Describe your issue here. - -### Your environment -* version of angular-translate -* version of angular -* which browser and its version - -### Steps to reproduce -Tell us how to reproduce this issue. - -### Expected behaviour -Tell us what should happen - -### Actual behaviour -Tell us what happens instead diff --git a/.github/ISSUE_TEMPLATE/submit-a-leetcode-problem.md b/.github/ISSUE_TEMPLATE/submit-a-leetcode-problem.md index fa91559..8d05d3b 100644 --- a/.github/ISSUE_TEMPLATE/submit-a-leetcode-problem.md +++ b/.github/ISSUE_TEMPLATE/submit-a-leetcode-problem.md @@ -2,7 +2,7 @@ name: Submit a LeetCode Problem about: Use this Template to submit a new LeetCode Problem title: 00## - LeetCode Problem Title -labels: 'hacktoberfest, help wanted, good first issue' +labels: 'hacktoberfest' assignees: '' --- diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c0b781c..04b4a9a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,12 +4,18 @@ Please make sure your file is in the `LeetCode`-Folder and Named like this: `0001_TwoSum.py` -> 4-digit Number of the LeetCode Issue, Underscore, LeetCodeName -## Pull Requests +### Opening Issues +When you open an issue, please make sure the Problem is not already implemented (Look at Code/Leetcode for the Problemnumber). +Opened Issues by existing Problem will be closed & PR made to this Issue marked as **spam** +The Contributer who opened an issue will be assigned prefered to the issue. If there is no PR within about 7 Days the issue will be assigned to another Contributer. + +### Pull Requests Only Pull Requests **joined with an Issue** and matching the **naming-conventions** (See Folders and Files) will be merged! If there is no Issue joined in the PR your PR will be labeld as **spam** and closed. -If your code don't passes the Check on LeetCode.com your PR will be labeld as **"invalid"** and the Issue stays open for the next PR! +If your code don't passes the Check on LeetCode.com your PR will be labled as **"invalid"** and the Issue stays open for the next PR! +If your PR doesn' follow the Contributing Guidelines of this Repository it will be also marked as **spam** and closed! -## Which PR will be accepted? +## Which PR's will be accepted? * Ones you are assigned to * Your PR has to link the Issue * Your Solution must be correct - you can check ist on LeetCode (submit) if it works on different test-cases diff --git a/LeetCode/0003_Longest_Substring_Without_Repeating_Characters.py b/LeetCode/0003_Longest_Substring_Without_Repeating_Characters.py new file mode 100644 index 0000000..2a8162f --- /dev/null +++ b/LeetCode/0003_Longest_Substring_Without_Repeating_Characters.py @@ -0,0 +1,14 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + map_chars = {} + longest = 0 + j = 0 + + for i in range(0, len(s)): + if s[i] in map_chars.keys(): + j = max(j, map_chars[s[i]] + 1) + + longest = max(longest, i - j + 1) + map_chars[s[i]] = i + + return longest \ No newline at end of file diff --git a/LeetCode/0005_Longest_Palindromic_Substring.py b/LeetCode/0005_Longest_Palindromic_Substring.py new file mode 100644 index 0000000..62982d8 --- /dev/null +++ b/LeetCode/0005_Longest_Palindromic_Substring.py @@ -0,0 +1,38 @@ +''' +Problem:- + +Given a string s, find the longest palindromic substring in s. +You may assume that the maximum length of s is 1000. + +Example 1: + Input: "babad" + Output: "bab" + Note: "aba" is also a valid answer. + +''' + +class Solution: + def longestPalindrome(self, s: str) -> str: + res = "" + resLen = 0 + + for i in range(len(s)): + # odd length + l, r = i, i + while l >= 0 and r < len(s) and s[l] == s[r]: + if (r - l + 1) > resLen: + res = s[l:r + 1] + resLen = r - l + 1 + l -= 1 + r += 1 + + # even length + l, r = i, i + 1 + while l >= 0 and r < len(s) and s[l] == s[r]: + if (r - l + 1) > resLen: + res = s[l:r + 1] + resLen = r - l + 1 + l -= 1 + r += 1 + + return res \ No newline at end of file diff --git a/LeetCode/0008_String_to_Integer.py b/LeetCode/0008_String_to_Integer.py new file mode 100644 index 0000000..8364817 --- /dev/null +++ b/LeetCode/0008_String_to_Integer.py @@ -0,0 +1,26 @@ +class Solution: + def myAtoi(self, s: str) -> int: + INT_MAX = (1 << 31) - 1 + INT_MIN = -(1 << 31) + + ret = 0 + s = s.strip() + + if s == "": + return ret + + negate = -1 if s[0] == '-' else 1 + + if s[0] in ('+', '-'): + s = s[1::] + + for c in s: + if not '0' <= c <= '9': + break + + ret = ret * 10 + ord(c) - ord('0') + + ret *= negate + ret = min(max(ret, INT_MIN), INT_MAX) + + return ret \ No newline at end of file diff --git a/LeetCode/0009_Palindrom_Number.py b/LeetCode/0009_Palindrom_Number.py new file mode 100644 index 0000000..7bf7938 --- /dev/null +++ b/LeetCode/0009_Palindrom_Number.py @@ -0,0 +1,12 @@ +class Solution: + def isPalindrome(self, x: int) -> bool: + if x > 0 and x < 10: + return True + + copyNumber = x + newNumber = 0 + while copyNumber > 0: + newNumber = int(newNumber * 10 + (copyNumber % 10)) + copyNumber = int(copyNumber / 10) + + return newNumber == x \ No newline at end of file diff --git a/LeetCode/0010_Regular_Expression_Matching.py b/LeetCode/0010_Regular_Expression_Matching.py new file mode 100644 index 0000000..3f97e39 --- /dev/null +++ b/LeetCode/0010_Regular_Expression_Matching.py @@ -0,0 +1,20 @@ +class Solution: + def isMatch(self, s: str, p: str) -> bool: + string, pattern = [], [] + string[:0], pattern[:0] = s, p + string.insert(0, 0) + pattern.insert(0, 0) + s, p = len(string), len(pattern) + dp = [[False for _ in range(p)] for __ in range(s)] + dp[0][0] = True + for i in range(p): + if pattern[i] is '*' and dp[0][i-2]: dp[0][i] = True + for i in range(1, s): + for j in range(1, p): + if pattern[j] is string[i] or pattern[j] is '.': + dp[i][j] = dp[i-1][j-1] + elif pattern[j] is '*' and (pattern[j-1] is string[i] or pattern[j-1] is '.'): + dp[i][j] = dp[i][j-2] or dp[i-1][j] + elif pattern[j] is '*' and not (pattern[j-1] is string[i] or pattern[j-1] is '.'): + dp[i][j] = dp[i][j-2] + return dp[s-1][p-1] diff --git a/LeetCode/0011 - Container With Most Water.py b/LeetCode/0011 - Container With Most Water.py new file mode 100644 index 0000000..e432773 --- /dev/null +++ b/LeetCode/0011 - Container With Most Water.py @@ -0,0 +1,16 @@ +class Solution(object): + def maxArea(self, height): + i=0 + j=len(height)-1 + a=0 + b=0 + while ia: + a=b + return a \ No newline at end of file diff --git a/LeetCode/0013_Roman to Integer.py b/LeetCode/0013_Roman to Integer.py new file mode 100644 index 0000000..7ec9c38 --- /dev/null +++ b/LeetCode/0013_Roman to Integer.py @@ -0,0 +1,32 @@ +class Solution: + def romanToInt(self, s: str) -> int: + + symbolValDict = { + 'I':1, + 'V':5, + 'X':10, + 'L':50, + 'C':100, + 'D':500, + 'M':1000 + } + + + i = 0 + finalDigit = 0 + while(i= nextDigit: + finalDigit += firstDigit + i+=1 + else: + finalDigit += nextDigit - firstDigit + i+=2 + else: + finalDigit += firstDigit + i+=1 + + + return finalDigit \ No newline at end of file diff --git a/LeetCode/0017_Letter_Combinations_of_a_Phone_Number.py b/LeetCode/0017_Letter_Combinations_of_a_Phone_Number.py new file mode 100644 index 0000000..e44ffe4 --- /dev/null +++ b/LeetCode/0017_Letter_Combinations_of_a_Phone_Number.py @@ -0,0 +1,19 @@ +import itertools +from typing import List + +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + keyboard = { + '2': "abc", + '3': "def", + '4': "ghi", + '5': "jkl", + '6': "mno", + '7': "pqrs", + '8': "tuv", + '9': "wxyz", + } + + pressed = [keyboard[c] for c in digits] + + return [''.join(p) for p in itertools.product(*pressed) if p != ()] \ No newline at end of file diff --git a/LeetCode/0020_Valid_Parentheses.py b/LeetCode/0020_Valid_Parentheses.py new file mode 100644 index 0000000..e2e41c5 --- /dev/null +++ b/LeetCode/0020_Valid_Parentheses.py @@ -0,0 +1,16 @@ +class Solution: + def isValid(self, s: str) -> bool: + stack = [] + openbrackets = ('(', '[', '{') + matches = ('()', '[]', '{}') + + for c in s: + if c in openbrackets: + stack.append(c) + else: + if len(stack) < 1 or stack[-1] + c not in matches: + return False + + stack.pop() + + return len(stack) == 0 \ No newline at end of file diff --git a/LeetCode/0022_GenerateParenthesis.py b/LeetCode/0022_GenerateParenthesis.py new file mode 100644 index 0000000..0954aca --- /dev/null +++ b/LeetCode/0022_GenerateParenthesis.py @@ -0,0 +1,25 @@ +class Solution: + def generateParenthesis(self, n: int) -> List[str]: + def isValid(s: str) -> bool: + stk = [] + for b in s: + if b == '(': + stk.append(b) + else: + if stk and stk[-1] == '(': + stk.pop() + else: + return False + return stk == [] + + ans = [] + for mask in range(1<<(2*n)): + s = "" + for bit in range(2*n): + if mask & (1<2->3->4, you should return the list as 2->1->4->3. + +''' + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def swapPairs(self, head: ListNode) -> ListNode: + pre, pre.next = self, head + while pre.next and pre.next.next: + a = pre.next + b = a.next + pre.next, b.next, a.next = b, a, b.next + pre = a + return self.next + + diff --git a/LeetCode/0028_strStr.py b/LeetCode/0028_strStr.py new file mode 100644 index 0000000..5a9aa0e --- /dev/null +++ b/LeetCode/0028_strStr.py @@ -0,0 +1,22 @@ +class Solution(object): + def strStr(self, haystack, needle): + + i = 0 + j = 0 + m = len(needle) + n = len(haystack) + if m ==0: + return 0 + while i=m: + if haystack[i] == needle[j]: + temp = i + while j List[int]: + score = 0 + scores = list() + for pos in position: + matched = state.get(pos) + if not matched: + scores.append(score) + score = 0 + + else: + score = score + 2 + + scores.append(score) + + return scores + + def longestValidParentheses(self, s: str) -> int: + scores = [0] + state = dict() + position = list() + opened = list() + closed = list() + for p, paren in enumerate(s): + if paren == "(": + opened.append(p) + position.append(p) + state[p] = False + + elif paren == ")" and len(opened) > 0: + op = opened.pop() + state[op] = True + + else: + scores.extend(self._score(position, state)) + state = dict() + position = list() + opened = list() + closed = list() + + scores.extend(self._score(position, state)) + return max(scores) diff --git a/LeetCode/0036_Valid_Sudoku.py b/LeetCode/0036_Valid_Sudoku.py new file mode 100644 index 0000000..30da2b9 --- /dev/null +++ b/LeetCode/0036_Valid_Sudoku.py @@ -0,0 +1,27 @@ +class Solution: + def isValidSudoku(self, board: List[List[str]]) -> bool: + return self.isValidRow(board) and self.isValidCol(board) and self.isValidSquare(board) + + def isValidRow(self, board): + for row in board: + if not self.isValidUnit(row): + return False + return True + + def isValidCol(self, board): + for col in zip(*board): + if not self.isValidUnit(col): + return False + return True + + def isValidSquare(self, board): + for i in (0, 3, 6): + for j in (0, 3, 6): + square = [board[x][y] for x in range(i, i + 3) for y in range(j, j + 3)] + if not self.isValidUnit(square): + return False + return True + + def isValidUnit(self, unit): + array = [c for c in unit if c != '.'] + return len(set(array)) == len(array) \ No newline at end of file diff --git a/LeetCode/0037_Sudoku_Solver.py b/LeetCode/0037_Sudoku_Solver.py new file mode 100644 index 0000000..a4f7956 --- /dev/null +++ b/LeetCode/0037_Sudoku_Solver.py @@ -0,0 +1,42 @@ +from collections import defaultdict, deque + + +class Solution: + def solveSudoku(self, board: List[List[str]]) -> None: + rows = defaultdict(set) + cols = defaultdict(set) + subgrids = defaultdict(set) + empty_cells = deque() + for i in range(9): + for j in range(9): + if board[i][j] != '.': + rows[i].add(board[i][j]) + cols[j].add(board[i][j]) + subgrids[(i//3, j//3)].add(board[i][j]) + else: + empty_cells.append((i, j)) + + def dfs(): + if not empty_cells: + return True + + row, col = empty_cells[0] + subgrid = (row//3, col//3) + for digit in {"1", '2', '3', '4', '5', '6', '7', '8', '9'}: + if digit not in rows[row] and digit not in cols[col] and digit not in subgrids[subgrid]: + board[row][col] = digit + rows[row].add(digit) + cols[col].add(digit) + subgrids[subgrid].add(digit) + empty_cells.popleft() + if dfs(): + return True + + board[row][col] = '.' + rows[row].remove(digit) + cols[col].remove(digit) + subgrids[subgrid].remove(digit) + empty_cells.appendleft((row, col)) + return False + dfs() + return board diff --git a/LeetCode/0040_Combination_Sum_2.py b/LeetCode/0040_Combination_Sum_2.py new file mode 100644 index 0000000..757b547 --- /dev/null +++ b/LeetCode/0040_Combination_Sum_2.py @@ -0,0 +1,33 @@ +''' +Problem :- + +Given a collection of candidate numbers (candidates) and a target number (target), +find all unique combinations in candidates where the candidate numbers sums to target. + +- Each number in candidates may only be used once in the combination. + +Example:- + +Input: candidates = [10,1,2,7,6,1,5], target = 8, +A solution set is: +[ + [1, 7], + [1, 2, 5], + [2, 6], + [1, 1, 6] +] + +''' +class Solution: + def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: + candidates.sort() + table = [None] + [set() for i in range(target)] + for i in candidates: + if i > target: + break + for j in range(target - i, 0, -1): + table[i + j] |= {elt + (i,) for elt in table[j]} + table[i].add((i,)) + return map(list, table[target]) + + diff --git a/LeetCode/0042_Trapping_Rain_Water.py b/LeetCode/0042_Trapping_Rain_Water.py new file mode 100644 index 0000000..df2cc51 --- /dev/null +++ b/LeetCode/0042_Trapping_Rain_Water.py @@ -0,0 +1,24 @@ +class Solution: + def trap(self, height: List[int]) -> int: + n = len(height) + if n>0: + left = [0]*n + right = [0]*n + result = 0 + + # Fill left array + left[0] = height[0] + for i in range( 1, n): + left[i] = max(left[i-1], height[i]) + + # Fill right array + right[n-1] = height[n-1] + for i in range(n-2, -1, -1): + right[i] = max(right[i + 1], height[i]); + + for i in range(0, n): + result += min(left[i], right[i]) - height[i] + + return result + else: + return 0 \ No newline at end of file diff --git a/LeetCode/0043_Multiply Strings.py b/LeetCode/0043_Multiply Strings.py new file mode 100644 index 0000000..e6dd828 --- /dev/null +++ b/LeetCode/0043_Multiply Strings.py @@ -0,0 +1,7 @@ +class Solution(object): + def multiply(self, num1, num2): + a,b=eval(num1),eval(num2) + c=a*b + c=str(c) + return c + diff --git a/LeetCode/0044_Wildcard_Matching.py b/LeetCode/0044_Wildcard_Matching.py new file mode 100644 index 0000000..38e466a --- /dev/null +++ b/LeetCode/0044_Wildcard_Matching.py @@ -0,0 +1,19 @@ +class Solution: + def isMatch(self, s: str, p: str) -> bool: + #this is a dynamic programming solution fot this + matrix = [[False for x in range(len(p) + 1)] for x in range(len(s) + 1)] + matrix[0][0] = True + + for i in range(1,len(matrix[0])): + if p[i-1] == '*': + matrix[0][i] = matrix[0][i-1] + + for i in range(1, len(matrix)): + for j in range(1, len(matrix[0])): + if s[i - 1] == p[j - 1] or p[j - 1] == '?': + matrix[i][j] = matrix[i-1][j-1] + elif p[j-1] == '*': + matrix[i][j] = matrix[i][j-1] or matrix[i-1][j] + else: + matrix[i][j] = False + return matrix[len(s)][len(p)] diff --git a/LeetCode/0046_Permutations.py b/LeetCode/0046_Permutations.py new file mode 100644 index 0000000..4456739 --- /dev/null +++ b/LeetCode/0046_Permutations.py @@ -0,0 +1,12 @@ +class Solution: + def permutations(self, nums: List[int]): + if not nums: + yield [] + for num in nums: + remaining = list(nums) + remaining.remove(num) + for perm in self.permutations(remaining): + yield [num] + list(perm) + + def permute(self, nums: List[int]) -> List[List[int]]: + return list(self.permutations(nums)) diff --git a/LeetCode/0047_Permutations II.py b/LeetCode/0047_Permutations II.py new file mode 100644 index 0000000..1039f98 --- /dev/null +++ b/LeetCode/0047_Permutations II.py @@ -0,0 +1,19 @@ +class Solution: + def permuteUnique(self, nums: List[int]) -> List[List[int]]: + results = [] + def Combination(permutation, counter): + if len(permutation) == len(nums): + results.append(list(permutation)) + return + + for num in counter: + if counter[num] > 0: + permutation.append(num) + counter[num] -= 1 + Combination(permutation, counter) + permutation.pop() + counter[num] += 1 + + Combination([], Counter(nums)) + + return results \ No newline at end of file diff --git a/LeetCode/0051_N-Queen_1.py b/LeetCode/0051_N-Queen_1.py new file mode 100644 index 0000000..607be73 --- /dev/null +++ b/LeetCode/0051_N-Queen_1.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +""" +Created on Wed Oct 7 20:51:57 2020 + +@author: anjalisingh +""" + +class Solution(object): + def solveNQueens(self, n): + # i is column index + # left: left diagonal: \ level-i + # right: right diagonal: / level+i + self.col = [0]*n # not occupied column + self.left = [0]*(2*n-1) # number of left diagonal + self.right = [0]*(2*n-1) + board = [['.' for x in range(n)] for y in range(n)] + self.resultBoard = [] + self.backTrack(n, 0, board) + return self.resultBoard + + def backTrack(self, n, level, board): + if level == n: # finish + res = [] + for i in range(n): + res.append(''.join(board[i])) + self.resultBoard.append(res) + return + for i in range(n): # iterate every column + # if col, left, right are all not accupied, put a queue here + if not self.col[i] and not self.left[level-i] and not self.right[level+i]: + board[level][i] = 'Q' + self.col[i] = 1 + self.left[level-i] = 1 + self.right[level+i] = 1 # choose + self.backTrack(n, level+1, board) # explore + board[level][i] = '.' # un choose + self.col[i] = 0 + self.left[level-i] = 0 + self.right[level+i] = 0 + +# Queen = Solution() +# print(Queen.solveNQueens(4)) diff --git a/LeetCode/0053_Maximum_Subarray.py b/LeetCode/0053_Maximum_Subarray.py new file mode 100644 index 0000000..960a895 --- /dev/null +++ b/LeetCode/0053_Maximum_Subarray.py @@ -0,0 +1,9 @@ +class Solution(object): + def maxSubArray(self, nums: List[int]) -> int: + dp = [0]*len(nums) + dp[0] = nums[0] + max_num = nums[0] + for i in range(1, len(nums)): + dp[i] = max(dp[i-1]+nums[i], nums[i]) + if dp[i]>max_num: max_num = dp[i] + return max_num diff --git a/LeetCode/0054_Spiral_Matrix.py b/LeetCode/0054_Spiral_Matrix.py new file mode 100644 index 0000000..db75a62 --- /dev/null +++ b/LeetCode/0054_Spiral_Matrix.py @@ -0,0 +1,35 @@ +class Solution: + def spiralOrder(self, matrix): + if len(matrix)>0: + k, l = 0, 0 + m = len(matrix) + n = len(matrix[0]) + + l1 = [] + while (k < m and l < n): + + for i in range(l, n): + l1.append(matrix[k][i]) + + k += 1 + + for i in range(k, m): + l1.append(matrix[i][n - 1]) + n -= 1 + + if (k < m): + + for i in range(n - 1, (l - 1), -1): + l1.append(matrix[m - 1][i]) + + m -= 1 + + if (l < n): + for i in range(m - 1, k - 1, -1): + l1.append(matrix[i][l]) + + l += 1 + return l1 + + + \ No newline at end of file diff --git a/LeetCode/0055_jump_game.py b/LeetCode/0055_jump_game.py new file mode 100644 index 0000000..2b60469 --- /dev/null +++ b/LeetCode/0055_jump_game.py @@ -0,0 +1,12 @@ +from typing import List + + +class Solution: + def canJump(self, nums: List[int]) -> bool: + jump_length_left = 0 + for num in nums: + if jump_length_left == -1: + return False + jump_length_left = max(jump_length_left - 1, num - 1) + + return True diff --git a/LeetCode/0057_Insert_Interval.py b/LeetCode/0057_Insert_Interval.py new file mode 100644 index 0000000..325acb6 --- /dev/null +++ b/LeetCode/0057_Insert_Interval.py @@ -0,0 +1,20 @@ +class Solution: + def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: + result = [] + + for interval in intervals: + # the new interval is after the range of other interval, so we can leave the current interval baecause the new one does not overlap with it + if interval[1] < newInterval[0]: + result.append(interval) + # the new interval's range is before the other, so we can add the new interval and update it to the current one + elif interval[0] > newInterval[1]: + result.append(newInterval) + newInterval = interval + # the new interval is in the range of the other interval, we have an overlap, so we must choose the min for start and max for end of interval + elif interval[1] >= newInterval[0] or interval[0] <= newInterval[1]: + newInterval[0] = min(interval[0], newInterval[0]) + newInterval[1] = max(newInterval[1], interval[1]) + + + result.append(newInterval); + return result diff --git a/LeetCode/0058_Length_of_Last_Word.py b/LeetCode/0058_Length_of_Last_Word.py new file mode 100644 index 0000000..db53f9f --- /dev/null +++ b/LeetCode/0058_Length_of_Last_Word.py @@ -0,0 +1,6 @@ +class Solution: + def lengthOfLastWord(self, s: str) -> int: + try: + return len(s.split()[-1]) + except IndexError: + return 0 diff --git a/LeetCode/0059_Spiral_Matrix_II.py b/LeetCode/0059_Spiral_Matrix_II.py new file mode 100644 index 0000000..a1e5e80 --- /dev/null +++ b/LeetCode/0059_Spiral_Matrix_II.py @@ -0,0 +1,8 @@ +class Solution: + def generateMatrix(self, n: int) -> List[List[int]]: + res, lo = [[n*n]], n*n + while lo > 1: + lo, hi = lo - len(res), lo + #print('res:', res) + res = [[i for i in range(lo, hi)]] + [list(j) for j in zip(*res[::-1])] + return res diff --git a/LeetCode/0060 - Permutation_Sequence.py b/LeetCode/0060 - Permutation_Sequence.py new file mode 100644 index 0000000..d28e294 --- /dev/null +++ b/LeetCode/0060 - Permutation_Sequence.py @@ -0,0 +1,16 @@ +from itertools import permutations +class Solution: + data = [] + + def getPermutation(self, n: int, k: int) -> str: + self.data = [] + string = [] + for i in range(1, n+1): + string.append(str(i)) + string = list(permutations(string)) + temp = string[k-1] + string = [] + string.append("".join(temp)) + return string[0] + + diff --git a/LeetCode/0061_Rotate_List.py b/LeetCode/0061_Rotate_List.py new file mode 100644 index 0000000..c752eaf --- /dev/null +++ b/LeetCode/0061_Rotate_List.py @@ -0,0 +1,29 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def rotateRight(self, head: ListNode, k: int) -> ListNode: + + + if head == None or head.next == None: + return head + count = 1 + p = head + while p.next: + count+=1 + p=p.next + + rot = k%count + temp = head + p.next = head + for i in range(count-rot-1): + temp = temp.next + answer = temp.next + temp.next = None + + return answer + + \ No newline at end of file diff --git a/LeetCode/0062_Unique_Paths.py b/LeetCode/0062_Unique_Paths.py new file mode 100644 index 0000000..0b5dfff --- /dev/null +++ b/LeetCode/0062_Unique_Paths.py @@ -0,0 +1,3 @@ +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + return math.factorial(n+m-2)//(math.factorial(m-1)*math.factorial(n-1)) \ No newline at end of file diff --git a/LeetCode/0063_UniquePathsII.py b/LeetCode/0063_UniquePathsII.py new file mode 100644 index 0000000..3dbb6ef --- /dev/null +++ b/LeetCode/0063_UniquePathsII.py @@ -0,0 +1,22 @@ +class Solution: + def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: + n, m = len(obstacleGrid), len(obstacleGrid[0]) + + ways = [[0 for j in range(m)] for i in range(n)] + + for i in range(n): + if obstacleGrid[i][0] == 1: + break + ways[i][0] = 1 + + for j in range(m): + if obstacleGrid[0][j] == 1: + break + ways[0][j] = 1 + + for i in range(1, n): + for j in range(1, m): + if obstacleGrid[i][j] == 0: + ways[i][j] = ways[i - 1][j] + ways[i][j - 1] + + return ways[n - 1][m - 1] diff --git a/LeetCode/0064_Minimum_Path_Sum.py b/LeetCode/0064_Minimum_Path_Sum.py new file mode 100644 index 0000000..917b1ff --- /dev/null +++ b/LeetCode/0064_Minimum_Path_Sum.py @@ -0,0 +1,12 @@ +class Solution: + def minPathSum(self, grid: List[List[int]]) -> int: + rows=len(grid) + columns=len(grid[0]) + for i in range(1,columns): + grid[0][i]+=grid[0][i-1] + for j in range(1,rows): + grid[j][0]+=grid[j-1][0] + for k in range(1,rows): + for l in range(1,columns): + grid[k][l]+=min(grid[k][l-1],grid[k-1][l]) + return grid[-1][-1] diff --git a/LeetCode/0066_Plus_One.py b/LeetCode/0066_Plus_One.py new file mode 100644 index 0000000..22d1575 --- /dev/null +++ b/LeetCode/0066_Plus_One.py @@ -0,0 +1,19 @@ +# Problem name : Plus One +# Problem link : https://leetcode.com/problems/plus-one/ +# Contributor : Shreeraksha R Aithal + +class Solution: + def plusOne(self, digits: List[int]) -> List[int]: + n = len(digits) + i = -1 + carry = 1 + while i>=-n: + digits[i] = digits[i] + carry + carry = digits[i]//10 + digits[i] = digits[i]%10 + i = i-1 + + if carry > 0: + digits = [carry] + digits + + return digits \ No newline at end of file diff --git a/LeetCode/0069 _ Sqrt(x).py b/LeetCode/0069 _ Sqrt(x).py new file mode 100644 index 0000000..f71cd35 --- /dev/null +++ b/LeetCode/0069 _ Sqrt(x).py @@ -0,0 +1,17 @@ +class Solution(object): + def mySqrt(self, x): + if x<2: + return x + low = 0 + high = x + result=0 + while(low<=high): + mid = (low+high)//2 + if(mid*mid==x): + return mid + elif(mid*mid int: + return self.fib(n + 1) + + fibStore = {} + def fib(self, n: int) -> int: + if n in self.fibStore: + return self.fibStore[n] + + if n <= 2: + return 1 + + value = self.fib(n - 1) + self.fib(n - 2) + self.fibStore[n] = value + return value + + +print(Solution().climbStairs(30)) diff --git a/LeetCode/0072_Edit_Distance.py b/LeetCode/0072_Edit_Distance.py new file mode 100644 index 0000000..0a779cf --- /dev/null +++ b/LeetCode/0072_Edit_Distance.py @@ -0,0 +1,22 @@ +class Solution: + # @return an integer + def minDistance(self, word1, word2): + m=len(word1) + n=len(word2) + dp=[[0 for i in range(n+1)] for j in range(m+1)] + for i in range(m+1): + dp[i][0]=i + for j in range(n+1): + dp[0][j]=j + for i in range(1,m+1): + for j in range(1,n+1): + if word1[i-1]==word2[j-1]: + dp[i][j]=dp[i-1][j-1] + else: + dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+1) + return dp[m][n] + +test=Solution() +input1=str(input(“Enter a string1”)) +input2=str(input(“Enter a string2”)) +print(test.minDistance(input1,input2)) diff --git a/LeetCode/0073_Set Matrix Zeroes.py b/LeetCode/0073_Set Matrix Zeroes.py new file mode 100644 index 0000000..70cecee --- /dev/null +++ b/LeetCode/0073_Set Matrix Zeroes.py @@ -0,0 +1,65 @@ +# SOLUTIONS 1 + +class Solution(object): + def setZeroes(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: void Do not return anything, modify matrix in-place instead. + """ + R = len(matrix) + C = len(matrix[0]) + rows, cols = set(), set() + + # Essentially, we mark the rows and columns that are to be made zero + for i in range(R): + for j in range(C): + if matrix[i][j] == 0: + rows.add(i) + cols.add(j) + + # Iterate over the array once again and using the rows and cols sets, update the elements + for i in range(R): + for j in range(C): + if i in rows or j in cols: + matrix[i][j] = 0 + + +#SOLUTIONS 2 + +class Solution(object): + def setZeroes(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: void Do not return anything, modify matrix in-place instead. + """ + is_col = False + R = len(matrix) + C = len(matrix[0]) + for i in range(R): + # Since first cell for both first row and first column is the same i.e. matrix[0][0] + # We can use an additional variable for either the first row/column. + # For this solution we are using an additional variable for the first column + # and using matrix[0][0] for the first row. + if matrix[i][0] == 0: + is_col = True + for j in range(1, C): + # If an element is zero, we set the first element of the corresponding row and column to 0 + if matrix[i][j] == 0: + matrix[0][j] = 0 + matrix[i][0] = 0 + + # Iterate over the array once again and using the first row and first column, update the elements. + for i in range(1, R): + for j in range(1, C): + if not matrix[i][0] or not matrix[0][j]: + matrix[i][j] = 0 + + # See if the first row needs to be set to zero as well + if matrix[0][0] == 0: + for j in range(C): + matrix[0][j] = 0 + + # See if the first column needs to be set to zero as well + if is_col: + for i in range(R): + matrix[i][0] = 0 \ No newline at end of file diff --git a/LeetCode/0075_Sort_Colors.py b/LeetCode/0075_Sort_Colors.py new file mode 100644 index 0000000..0192268 --- /dev/null +++ b/LeetCode/0075_Sort_Colors.py @@ -0,0 +1,29 @@ +# Problem name : Sort Colors +# Problem link : https://leetcode.com/problems/sort-colors/ +# Contributor : Shreeraksha R Aithal + +class Solution: + def sortColors(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + + i = k = 0 + n = len(nums) + j = n-1 + while k < n and i < j: + if nums[k] == 0: + if k > i: + nums[i], nums[k] = nums[k], nums[i] + i += 1 + else: + k += 1 + elif nums[k] == 2: + if k < j: + nums[j], nums[k] = nums[k], nums[j] + j -= 1 + else: + k += 1 + else: + k += 1 + diff --git a/LeetCode/0076_Minimum_Window_Substring.py b/LeetCode/0076_Minimum_Window_Substring.py new file mode 100644 index 0000000..86cdf44 --- /dev/null +++ b/LeetCode/0076_Minimum_Window_Substring.py @@ -0,0 +1,31 @@ +from collections import defaultdict + +class Solution: + def minWindow(self, s: str, t: str) -> str: + char_frequency = defaultdict(lambda: 0) + for c in t: + char_frequency[c] += 1 + chars_matched = 0 + + start = 0 + res = "" + + for end in range(len(s)): + right_char = s[end] + if right_char in t: + char_frequency[right_char] -= 1 + if char_frequency[right_char] == 0: + chars_matched += 1 + + while start <= end and chars_matched == len(char_frequency): + if res == "" or end-start+1 < len(res): + res = s[start:end+1] + + left_char = s[start] + if left_char in t: + if char_frequency[left_char] == 0: + chars_matched -= 1 + char_frequency[left_char] += 1 + start += 1 + + return res diff --git a/LeetCode/0077_Combinations.py b/LeetCode/0077_Combinations.py new file mode 100644 index 0000000..387a6d2 --- /dev/null +++ b/LeetCode/0077_Combinations.py @@ -0,0 +1,38 @@ +class Solution: + def combine(self, n: int, k: int) -> List[List[int]]: + # Pretty much same as combination sums II, use index at most once per combo + + # create list from 1 to n + # for each i-th element, call helper function from [i+1:] + # from the helper function, if length of arr passed in == k + # append and return + # otherwise, keep going for i+1 in a for loop in the helper + # ^ after done, delete the last index(backtrack process) + + nums = [_ for _ in range(1,n+1)] + result = [] + combo = [] + n = len(nums) + + for i in range(n): + combo.append(nums[i]) + self.backtrack(nums[i+1:],combo, result, k) + combo = [] + + return result + + def backtrack(self, nums: List[int], combo: List[int], result: List[List[int]], k: int) -> None: + + if len(combo) == k: + result.append([_ for _ in combo]) + return + + n = len(nums) + + for i in range(n): + combo.append(nums[i]) + self.backtrack(nums[i+1:],combo,result,k) + # This is the backtrack process + del combo[-1] + + return \ No newline at end of file diff --git a/LeetCode/0078_Subsets.py b/LeetCode/0078_Subsets.py new file mode 100644 index 0000000..23fccc3 --- /dev/null +++ b/LeetCode/0078_Subsets.py @@ -0,0 +1,21 @@ +#using backtracking approach + +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + def backtrack(first = 0, curr = []): + # if the combination is done + if len(curr) == k: + output.append(curr[:]) + for i in range(first, n): + # add nums[i] into the current combination + curr.append(nums[i]) + # use next integers to complete the combination + backtrack(i + 1, curr) + # backtrack + curr.pop() + + output = [] + n = len(nums) + for k in range(n + 1): + backtrack() + return output diff --git a/LeetCode/0079_Word_Search.py b/LeetCode/0079_Word_Search.py new file mode 100644 index 0000000..82f56be --- /dev/null +++ b/LeetCode/0079_Word_Search.py @@ -0,0 +1,35 @@ +def exist(self, grid: List[List[str]], word: str) -> bool: + + seen = set() + + # Boundary checking + def inBound(row, col, grid): + return 0 <= row < len(grid) and 0 <= col < len(grid[0]) + + def dfs(grid, word, curr_i, row, col): + + if curr_i == len(word): + return True + + if not inBound(row, col,grid) or grid[row][col] != word[curr_i]: + return False + + seen.add((row, col)) + + # Explore possible paths + pos_paths = [(row, col + 1), (row, col - 1), (row + 1, col), (row - 1, col)] + for row_n, col_n in pos_paths: + if (row_n,col_n) not in seen: + if dfs(grid, word, curr_i + 1, row_n, col_n): + return True + + seen.remove((row,col)) + return False + + for row in range(len(grid)): + for col in range(len(grid[0])): + if grid[row][col] == word[0]: + if dfs(grid, word, 0, row, col): + return True + + return False \ No newline at end of file diff --git a/LeetCode/0082_Remove_Duplicates_from_Sorted_List_II.py b/LeetCode/0082_Remove_Duplicates_from_Sorted_List_II.py new file mode 100644 index 0000000..0590137 --- /dev/null +++ b/LeetCode/0082_Remove_Duplicates_from_Sorted_List_II.py @@ -0,0 +1,19 @@ +# Definition for singly-linked list. +#class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + if head is None: + return head + + while (head.next is not None) and (head.val == head.next.val): + while (head.next is not None) and (head.val == head.next.val): + head = head.next + head = head.next + if head is None: + return head + + head.next = self.deleteDuplicates(head.next) + return head \ No newline at end of file diff --git a/LeetCode/0083_Remove_Dupticates_from_Sorted_List.py b/LeetCode/0083_Remove_Dupticates_from_Sorted_List.py new file mode 100644 index 0000000..890fd10 --- /dev/null +++ b/LeetCode/0083_Remove_Dupticates_from_Sorted_List.py @@ -0,0 +1,19 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + if head==None: + return head + current= head.next + prev=head + while current!=None: + if current.val==prev.val: + prev.next=current.next + current=current.next + else: + current=current.next + prev=prev.next + return head \ No newline at end of file diff --git a/LeetCode/0086_Partition_List.py b/LeetCode/0086_Partition_List.py new file mode 100644 index 0000000..6248e3e --- /dev/null +++ b/LeetCode/0086_Partition_List.py @@ -0,0 +1,36 @@ +class Solution(object): + def partition(self, head, x): + """ + :type head: ListNode + :type x: int + :rtype: ListNode + """ + + # before and after are the two pointers used to create two list + # before_head and after_head are used to save the heads of the two lists. + # All of these are initialized with the dummy nodes created. + before = before_head = ListNode(0) + after = after_head = ListNode(0) + + while head: + # If the original list node is lesser than the given x, + # assign it to the before list. + if head.val < x: + before.next = head + before = before.next + else: + # If the original list node is greater or equal to the given x, + # assign it to the after list. + after.next = head + after = after.next + + # move ahead in the original list + head = head.next + + # Last node of "after" list would also be ending node of the reformed list + after.next = None + # Once all the nodes are correctly assigned to the two lists, + # combine them to form a single list which would be returned. + before.next = after_head.next + + return before_head.next diff --git a/LeetCode/0088_Merge_Sorted_Array.py b/LeetCode/0088_Merge_Sorted_Array.py new file mode 100644 index 0000000..902755b --- /dev/null +++ b/LeetCode/0088_Merge_Sorted_Array.py @@ -0,0 +1,8 @@ +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + for x in nums2: + for y in range(len(nums1)): + if nums1[y]==0: + nums1[y]+=x + break + nums1.sort() diff --git a/LeetCode/0089_Gray_code.py b/LeetCode/0089_Gray_code.py new file mode 100644 index 0000000..ac696d1 --- /dev/null +++ b/LeetCode/0089_Gray_code.py @@ -0,0 +1,11 @@ +def gray(a): + return ((a)^(a>>1)) + +class Solution: + def grayCode(self, n: int) -> List[int]: + ans=[] + for i in range(pow(2,n)): + ans.append(gray(i)) + return ans + + diff --git a/LeetCode/0091_Decode_Ways.py b/LeetCode/0091_Decode_Ways.py new file mode 100644 index 0000000..e5d83ff --- /dev/null +++ b/LeetCode/0091_Decode_Ways.py @@ -0,0 +1,20 @@ +class Solution: + def numDecodings(self, s: str) -> int: + def in_range(n): + if n[0] == '0': + return False + to_int = int(n) + if to_int <= 26 and to_int > 0: + return True + return False + + N = len(s) + a, b = 1, 1 + if N == 0 or s[0] == '0': + return 0 + + for i in range(1, N): + extra = a if in_range(s[i-1:i+1]) else 0 + c = extra + (b if in_range(s[i]) else 0) + a, b = b, c + return b diff --git a/LeetCode/0093_Restore_IP_address.py b/LeetCode/0093_Restore_IP_address.py new file mode 100644 index 0000000..0f2630e --- /dev/null +++ b/LeetCode/0093_Restore_IP_address.py @@ -0,0 +1,53 @@ +class Solution: + + def restoreIpAddresses(self, s: str) -> list: + + return self.convert(s) + + def convert(self,s): + + sz = len(s) + + # Check for string size + if sz > 12: + return [] + snew = s + l = [] + + # Generating different combinations. + for i in range(1, sz - 2): + for j in range(i + 1, sz - 1): + for k in range(j + 1, sz): + snew = snew[:k] + "." + snew[k:] + snew = snew[:j] + "." + snew[j:] + snew = snew[:i] + "." + snew[i:] + + # Check for the validity of combination + if self.is_valid(snew): + l.append(snew) + + snew = s + + return l + + + + + def is_valid(self,ip): + + # Splitting by "." + ip = ip.split(".") + + # Checking for the corner cases + for i in ip: + if (len(i) > 3 or int(i) < 0 or + int(i) > 255): + return False + if len(i) > 1 and int(i) == 0: + return False + if (len(i) > 1 and int(i) != 0 and + i[0] == '0'): + return False + + return True + \ No newline at end of file diff --git a/LeetCode/0098_Validate_Binary_Search_Tree.py b/LeetCode/0098_Validate_Binary_Search_Tree.py new file mode 100644 index 0000000..35253cc --- /dev/null +++ b/LeetCode/0098_Validate_Binary_Search_Tree.py @@ -0,0 +1,16 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right + +class Solution: + def isValidBST(self, root: TreeNode, sm=[], gt=[]) -> bool: + if root is None: + return True + + if any([root.val <= x for x in sm]) or any([root.val >= x for x in gt]): + return False + + return (root.left is None or self.isValidBST(root.left, sm, gt + [root.val])) and (root.right is None or self.isValidBST(root.right, sm + [root.val], gt)) diff --git a/LeetCode/0100_Same_Tree.py b/LeetCode/0100_Same_Tree.py new file mode 100644 index 0000000..68c723f --- /dev/null +++ b/LeetCode/0100_Same_Tree.py @@ -0,0 +1,20 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def isSameTree(self, p, q): + if(p is None and q is None): + return True + + if(p==None or q==None): + return False + + if(p.val!=q.val): + return False + + else: + return self.isSameTree( p.right, q.right) and self.isSameTree( p.left, q.left) + \ No newline at end of file diff --git a/LeetCode/0102_Binary_Tree_Level_Order_Traversal.py b/LeetCode/0102_Binary_Tree_Level_Order_Traversal.py new file mode 100644 index 0000000..05fe397 --- /dev/null +++ b/LeetCode/0102_Binary_Tree_Level_Order_Traversal.py @@ -0,0 +1,56 @@ +""" +Level Order Traversal - BFS + +A Tree Algorithm where the nodes in a tree are visited in a level by level fashion. +i.e Nodes at each level are processed before moving on to the next. + +Steps + 1. For every node, add to a queue. + 2. Process the node and pop from the front of the queue. + 3. Add its left and right child to the queue. + +Time complexity is O(N) since we visit every node at least once. N is the number of nodes in the tree. +Space complexity is O(N) since we make use of a queue data structure having a maximum of size N. + + +Sample Binary Tree: + + 8 + / \ + 3 10 + / \ \ + 1 6 14 + +Level-Order Traversal of this binary tree results in: +output = [[8], [3,10], [1,6,14]] +""" + +# Code implementation +def levelOrder(self, root: TreeNode) -> List[List[int]]: + import collections + output = [] + queue = collections.deque([root]) + + if root == None: + return [] + + while queue: + num_of_nodes = len(queue) + curr_level = [] + + for node in range(num_of_nodes): + curr_node = queue.popleft() + curr_level.append(curr_node.val) + + if curr_node.left: + queue.append(curr_node.left) + + if curr_node.right: + queue.append(curr_node.right) + + output.append(curr_level) + + + + return output + \ No newline at end of file diff --git a/LeetCode/0104_Maximum_Depth_of_Binary_Tree.py b/LeetCode/0104_Maximum_Depth_of_Binary_Tree.py new file mode 100644 index 0000000..0d0a184 --- /dev/null +++ b/LeetCode/0104_Maximum_Depth_of_Binary_Tree.py @@ -0,0 +1,12 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if root==None: + return 0 + else: + return max(self.maxDepth(root.left),self.maxDepth(root.right))+1 diff --git a/LeetCode/0111_Minimum_Depth_of_Binary_Tree.py b/LeetCode/0111_Minimum_Depth_of_Binary_Tree.py new file mode 100644 index 0000000..680208c --- /dev/null +++ b/LeetCode/0111_Minimum_Depth_of_Binary_Tree.py @@ -0,0 +1,15 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def minDepth(self, root: TreeNode) -> int: + if not root: + return 0 + if not root.left or not root.right: + return max(self.minDepth(root.left), self.minDepth(root.right)) + 1 + else: + return min(self.minDepth(root.left), self.minDepth(root.right)) + 1 diff --git a/LeetCode/0112_Path_Sum.py b/LeetCode/0112_Path_Sum.py new file mode 100644 index 0000000..b2faa86 --- /dev/null +++ b/LeetCode/0112_Path_Sum.py @@ -0,0 +1,14 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right + +class Solution: + def hasPathSum(self, root: TreeNode, sum: int) -> bool: + if not root: + return False + if not root.left and not root.right: + return root.val == sum + return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val) \ No newline at end of file diff --git a/LeetCode/0118_pascal_triangle.py b/LeetCode/0118_pascal_triangle.py new file mode 100644 index 0000000..ccd4440 --- /dev/null +++ b/LeetCode/0118_pascal_triangle.py @@ -0,0 +1,9 @@ +class Solution: + def generate(self, numRows: int) -> List[List[int]]: + if numRows==0: + return [] + triangle=[[1]] + for row in range(numRows-1): + triangle.append([1]+[triangle[-1][i]+triangle[-1][i+1] for i in range(row)]+[1]) + return triangle + \ No newline at end of file diff --git a/LeetCode/0121_Best_Time_to_Buy_and_Sell_Stock.py b/LeetCode/0121_Best_Time_to_Buy_and_Sell_Stock.py new file mode 100644 index 0000000..bd751d4 --- /dev/null +++ b/LeetCode/0121_Best_Time_to_Buy_and_Sell_Stock.py @@ -0,0 +1,11 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + if len(prices) == 0: + return 0 + profit = 0 + mincost = prices[0] + + for i in range(1, len(prices)): + profit = max(profit, prices[i] - mincost) + mincost = min(mincost, prices[i]) + return profit \ No newline at end of file diff --git a/LeetCode/0125_Valid_Palindrome.py b/LeetCode/0125_Valid_Palindrome.py new file mode 100644 index 0000000..acffcdd --- /dev/null +++ b/LeetCode/0125_Valid_Palindrome.py @@ -0,0 +1,18 @@ +class Solution: + def isPalindrome(self, s: str) -> bool: + alphnum = "" + #Extract only alphanumeric characters from the given string + for i in s: + #Check whether the character is a lowercase letter or a number + if ord(i)>=ord('a') and ord(i)<=ord('z') or ord(i)>=ord("0") and ord(i)<=ord("9"): + alphnum+=i + #Check whether the character is an uppercase letter. + #If yes,convert to lower case + elif ord(i)>=ord('A') and ord(i)<=ord('Z'): + i = chr(32+ord(i)) + alphnum+=i + #Reverse the alphanumeric string and check whether it is a palindrome + rev= alphnum[::-1] + result= rev==alphnum + return result + \ No newline at end of file diff --git a/LeetCode/0126_Word_Ladder_II.py b/LeetCode/0126_Word_Ladder_II.py new file mode 100644 index 0000000..c00115a --- /dev/null +++ b/LeetCode/0126_Word_Ladder_II.py @@ -0,0 +1,26 @@ +class Solution: + def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: + + from collections import defaultdict + + wordList = set(wordList) + list1 = [] + layer = {} + layer[beginWord] = [[beginWord]] + + while layer: + newlayer = defaultdict(list) + for a in layer: + if a == endWord: + list1.extend(b for b in layer[a]) + else: + for i in range(len(a)): + for j in 'abcdefghijklmnopqrstuvwxyz': + new1 = a[:i]+j+a[i+1:] + if new1 in wordList: + newlayer[new1]+=[k+[new1] for k in layer[a]] + + wordList -= set(newlayer.keys()) + layer = newlayer + + return list1 \ No newline at end of file diff --git a/LeetCode/0134_Gas_Station.py b/LeetCode/0134_Gas_Station.py new file mode 100644 index 0000000..161388d --- /dev/null +++ b/LeetCode/0134_Gas_Station.py @@ -0,0 +1,41 @@ +""" +134. Gas Station Problem + +Problem:- +There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. +You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). +You begin the journey with an empty tank at one of the gas stations. +Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. + +Input:- gas = [1,2,3,4,5], gas is the array consisting of the gas can get at i th stop + cost= [3,4,5,1,2], cost is the array consisting of the cost to travel from i to i+1 index + +Output:- 3, we have to return the index from where we can start journey and traverse all stops in clockwise manner + +Time complexity :- O(N) where N is the number is the size of array(stops) +Space complexity:- O(1) + +""" + +class Solution: + def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: + # total_fuel variable is maintained to check if path is possible or not if sum(gas) < sum(cost) return -1 + n = len(gas) + curr_fuel = 0 + total_fuel = 0 + start_idx = 0 + + for i in range(n): + curr_fuel += gas[i]-cost[i] + total_fuel += gas[i]-cost[i] + # at any index if fuel becomes less than 0 then we have to choose new starting index + if curr_fuel < 0: + # start_idx will be i+1 because at i th index out curr_fuel became < 0 + # so we start from any index between start_idx and i there will be no valid start_idx + start_idx = i+1 + # reset the curr_fuel to 0 as we have chose new start_idx + curr_fuel = 0 + # at last check if start_idx is less than n and total_fuel is not less than 0 return start_idx else -1 + return start_idx if start_idx < n and total_fuel>=0 else -1 + + diff --git a/LeetCode/0141_Linked_List_Cycle.py b/LeetCode/0141_Linked_List_Cycle.py new file mode 100644 index 0000000..c26485b --- /dev/null +++ b/LeetCode/0141_Linked_List_Cycle.py @@ -0,0 +1,39 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + ''' + Solution using Floyd's cycle-finding algorithm (tortoise and hare) + ''' + + def hasCycle(self, head: ListNode) -> bool: + if not head or not head.next: + return False + + fast = slow = head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + # If there is a cycle, fast will inevitably be on the same node as + # slow. + if fast is slow: + return True + return False + + +class SolutionO1: + ''' + Solution to follow up. Disregards contents of each ListNode. + ''' + + def hasCycle(self, head: ListNode) -> bool: + while head: + if head.val is None: + return True + head.val = None + head = head.next + return False diff --git a/LeetCode/0169_Majority_Element.py b/LeetCode/0169_Majority_Element.py new file mode 100644 index 0000000..dec71e1 --- /dev/null +++ b/LeetCode/0169_Majority_Element.py @@ -0,0 +1,28 @@ +# this class will give us a solution +class Solution: + + # the function to find the majority element + def majorityElement(self, arr): + """ + finds the majority element in the arr + :param arr: List[int] a list with elements + :return: int , the majority element + """ + + # a dictionary of numbers we have seen + seen_numbers = {} + + if len(arr) <= 2: + return arr[0] + + # goes through the list of numbers and count the appearance amount + for num in arr: + # adds it to the dictionary + if num not in seen_numbers: + seen_numbers[num] = 1 + else: + if (seen_numbers[num] + 1) >= (len(arr) / 2): + return num + else: + # adds one to the counter + seen_numbers[num] += 1 diff --git a/LeetCode/0189_Rotate_Array.py b/LeetCode/0189_Rotate_Array.py new file mode 100644 index 0000000..b72eef1 --- /dev/null +++ b/LeetCode/0189_Rotate_Array.py @@ -0,0 +1,6 @@ +class Solution: + def rotate(self, nums: List[int], k: int) -> None: + for i in range(k): + lastValue = nums.pop() + nums.insert(0, lastValue) + return nums \ No newline at end of file diff --git a/LeetCode/0190_Reverse_bits.py b/LeetCode/0190_Reverse_bits.py new file mode 100644 index 0000000..cfd8a99 --- /dev/null +++ b/LeetCode/0190_Reverse_bits.py @@ -0,0 +1,5 @@ +class Solution: + def reverseBits(self, n: int) -> int: + + s='{0:032b}'.format(n)[::-1] + return int(s,2) \ No newline at end of file diff --git a/LeetCode/0191_Number_of_1_bits.py b/LeetCode/0191_Number_of_1_bits.py new file mode 100644 index 0000000..8454fa0 --- /dev/null +++ b/LeetCode/0191_Number_of_1_bits.py @@ -0,0 +1,4 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + + return '{0:b}'.format(n).count('1') \ No newline at end of file diff --git a/LeetCode/0198_House_Robber.py b/LeetCode/0198_House_Robber.py new file mode 100644 index 0000000..097b5e6 --- /dev/null +++ b/LeetCode/0198_House_Robber.py @@ -0,0 +1,20 @@ +def rob(self, nums: List[int]) -> int: + length = len(nums) + if length == 0: + return 0 + dp = [0] * len(nums) + dp[0] = nums[0] + for i in range(1,length): + if i==1: + dp[i] = max(dp[0],nums[i]) + elif i==2: + dp[i] = dp[0]+nums[i] + else: + dp[i] = max(dp[i-2],dp[i-3]) + nums[i] + return max(dp[length-1],dp[length-2]) + +''' +n = len(nums) +Time complexity = O(n) +Space complexity = O(n) +''' \ No newline at end of file diff --git a/LeetCode/0200_Number_of_Islands.py b/LeetCode/0200_Number_of_Islands.py new file mode 100644 index 0000000..a297048 --- /dev/null +++ b/LeetCode/0200_Number_of_Islands.py @@ -0,0 +1,26 @@ +class Solution(object): + def numIslands(self, grid): + """ + :type grid: List[List[str]] + :rtype: int + """ + cnt = 0 + + for i in range(len(grid)): + for j in range(len(grid[i])): + if grid[i][j] == "1": + cnt += 1 + self.removeIsland(grid, i, j) + return cnt + + # recursive function for replacing adjacent "1"s + def removeIsland(self, grid, i, j): + if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]): + return + if grid[i][j] == "0": + return + grid[i][j] = "0" + self.removeIsland(grid, i+1, j) + self.removeIsland(grid, i-1, j) + self.removeIsland(grid, i, j+1) + self.removeIsland(grid, i, j-1) diff --git a/LeetCode/0206_Reverse_Linked_List.py b/LeetCode/0206_Reverse_Linked_List.py new file mode 100644 index 0000000..a659b0c --- /dev/null +++ b/LeetCode/0206_Reverse_Linked_List.py @@ -0,0 +1,15 @@ +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution(object): + def reverseList(self, head, auxNode=None): #recursive mode + if(head==None): + return auxNode + else: + return self.reverseList(head.next, ListNode(head.val, auxNode)) + """ + :type head: ListNode + :rtype: ListNode + """ \ No newline at end of file diff --git a/LeetCode/0213_House_robber2.py b/LeetCode/0213_House_robber2.py new file mode 100644 index 0000000..c5a93f9 --- /dev/null +++ b/LeetCode/0213_House_robber2.py @@ -0,0 +1,55 @@ +""" +213. House Robber II +You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. +Given a list of non-negative integers nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. +Input: nums = [2,3,2] +Output: 3 +Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. + +This problem is solved using Dynamic Programming +Time Complexity:- O(N) +Space Complexity: O(N) , we need to make 2 DP arrays so it takes O(2N) space + +""" +class Solution: + def rob(self, nums: List[int]) -> int: + n = len( nums ) + # base conditions + # if there is no element in array + if n==0: + return 0 + # if there is only one element in array return the element + if n==1: + return nums[0] + # if there are 2 elements then return the max value out of both as we can't choose adjacent values together + if n==2: + return max(nums[0],nums[1]) + + + def max_profit(dp): + """ + This function finds the max profit by robbing the adjacent houses using DP + Input:- DP array of size n-1 + Output:- Max profit from that DP array + """ + len_dp = len( dp ) + dp[1] = max( dp[0], dp[1] ) + for k in range( 2, len_dp ): + dp[k] = max( dp[k - 1], dp[k] + dp[k - 2] ) + + return dp[-1] + + """ + We exclude the last element in first case then find max profit + we exculde the first element in second case then find max profit + we can't take both first and last element as they are adjacent + as last house is connected to first house + """ + # find the profit excluding the last house + dp_excludingLastElement = nums[:n - 1] + profit1 = max_profit(dp_excludingLastElement) + # find the profit using the first house + dp_excludingFirstElement = nums[1:n] + profit2 = max_profit(dp_excludingFirstElement) + # return the max profit out of both the possibilites + return max( profit1, profit2 ) \ No newline at end of file diff --git a/LeetCode/0215_Kth_Largest_Element_In_An_Array.py b/LeetCode/0215_Kth_Largest_Element_In_An_Array.py new file mode 100644 index 0000000..f9994b4 --- /dev/null +++ b/LeetCode/0215_Kth_Largest_Element_In_An_Array.py @@ -0,0 +1,6 @@ +import heapq +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + heapq.heapify(nums) + res = heapq.nlargest(k,nums) + return res[len(res)-1] \ No newline at end of file diff --git a/LeetCode/0231_Power_Of_Two.py b/LeetCode/0231_Power_Of_Two.py new file mode 100644 index 0000000..e9304e4 --- /dev/null +++ b/LeetCode/0231_Power_Of_Two.py @@ -0,0 +1,3 @@ +class Solution: + def isPowerOfTwo(self, x: int) -> bool: + return (x != 0) and ((x & (x - 1)) == 0); \ No newline at end of file diff --git a/LeetCode/0233_Number_of_Digit_One.py b/LeetCode/0233_Number_of_Digit_One.py new file mode 100644 index 0000000..7dbcec4 --- /dev/null +++ b/LeetCode/0233_Number_of_Digit_One.py @@ -0,0 +1,18 @@ +# Denote the number of 1 less than or equal to a given number +# Eg) +# Input: 13 +# Output: 6 +# Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. + +class Solution(object): + def countDigitOne(self, n): + number = 0 + i = 1 + while(i <= n): + divider = i * 10 + number += (int(n / divider) * i + + min(max(n % divider -i + + 1, 0), i)) + i *= 10 + + return number \ No newline at end of file diff --git a/LeetCode/0242_Valid_anagrams.py b/LeetCode/0242_Valid_anagrams.py new file mode 100644 index 0000000..35a1d99 --- /dev/null +++ b/LeetCode/0242_Valid_anagrams.py @@ -0,0 +1,4 @@ +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + + return (sorted(s) == sorted(t)) \ No newline at end of file diff --git a/LeetCode/0257_Binary_Tree_Paths.py b/LeetCode/0257_Binary_Tree_Paths.py new file mode 100644 index 0000000..9dad911 --- /dev/null +++ b/LeetCode/0257_Binary_Tree_Paths.py @@ -0,0 +1,24 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def __init__(self): + self.listOfPaths = [] #this list will save all paths and return + + def binaryTreePaths(self, root: TreeNode, path="") -> List[str]: + if(root==None): + return [] #nothing to return (it's a empty node) ... + + path += " " + str(root.val)#actual node value becomes a 'element route' + + if(root.left==None and root.right==None): + self.listOfPaths.append(path[1:].replace(" ", "->"))#question output format + + else: + self.binaryTreePaths(root.left, path) #scan by route in left node + self.binaryTreePaths(root.right, path)#scan by route in right node + return self.listOfPaths #return all paths + diff --git a/LeetCode/0258_Add_Digits.py b/LeetCode/0258_Add_Digits.py new file mode 100644 index 0000000..8f0800c --- /dev/null +++ b/LeetCode/0258_Add_Digits.py @@ -0,0 +1,5 @@ +class Solution: + def addDigits(self, num: int) -> int: + if num < 10: return num + if num % 9 == 0: return 9 + return num % 9 diff --git a/LeetCode/0268_Missing_Number.py b/LeetCode/0268_Missing_Number.py new file mode 100644 index 0000000..843b6dd --- /dev/null +++ b/LeetCode/0268_Missing_Number.py @@ -0,0 +1,16 @@ +class Solution: + def computeXOR(self,n:int) -> int: + if n%4==0: + return n + elif n%4==1: + return 1 + elif n%4==2: + return n+1 + else: + return 0 + def missingNumber(self, nums: List[int]) -> int: + all_xor = self.computeXOR(len(nums)) + current_xor = 0 + for i in nums: + current_xor^=i + return(all_xor^current_xor) \ No newline at end of file diff --git a/LeetCode/0274_H_Index.py b/LeetCode/0274_H_Index.py new file mode 100644 index 0000000..086042b --- /dev/null +++ b/LeetCode/0274_H_Index.py @@ -0,0 +1,11 @@ +class Solution: + def hIndex(self, citations: List[int]) -> int: + citations.sort() + n = len(citations) + if n==0: + return 0 + if set(citations) == {0}: + return 0 + for i in range(n): + if n-i<=citations[i]: + return n-i \ No newline at end of file diff --git a/LeetCode/0278_First_Bad_Version.py b/LeetCode/0278_First_Bad_Version.py new file mode 100644 index 0000000..08c2ef1 --- /dev/null +++ b/LeetCode/0278_First_Bad_Version.py @@ -0,0 +1,22 @@ +# The isBadVersion API is already defined for you. +# @param version, an integer +# @return an integer +# def isBadVersion(version): + +class Solution: + def firstBadVersion(self, n): + """ + :type n: int + :rtype: int + """ + l, r, ans = 1, n, -1 + while l <= r: + mid = (l + r) // 2 + if isBadVersion(mid): + ans = mid + r = mid - 1 + else: + l = mid + 1 + + return ans + \ No newline at end of file diff --git a/LeetCode/0279-PerfectSquares.py b/LeetCode/0279-PerfectSquares.py new file mode 100644 index 0000000..b94fca3 --- /dev/null +++ b/LeetCode/0279-PerfectSquares.py @@ -0,0 +1,15 @@ +class Solution(object): + def numSquares(self, n): + queue = collections.deque([(0, 0)]) + visited = set() + while queue: + val, dis = queue.popleft() + if val == n: + return dis + for i in range(1, n+1): + j = val + i*i + if j > n: + break + if j not in visited: + visited.add(j) + queue.append((j, dis+1)) \ No newline at end of file diff --git a/LeetCode/0283_Move_Zeroes.py b/LeetCode/0283_Move_Zeroes.py new file mode 100644 index 0000000..e445f63 --- /dev/null +++ b/LeetCode/0283_Move_Zeroes.py @@ -0,0 +1,12 @@ +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + pos = 0 + for i in range(len(nums)): + if nums[i]!= 0: + if pos!=i: + nums[pos], nums[i] = nums[i], nums[pos] + pos += 1 + diff --git a/LeetCode/0299_Bulls_and_Cows.py b/LeetCode/0299_Bulls_and_Cows.py new file mode 100644 index 0000000..f1253ad --- /dev/null +++ b/LeetCode/0299_Bulls_and_Cows.py @@ -0,0 +1,18 @@ +from collections import Counter +class Solution: + def getHint(self, secret: str, guess: str) -> str: + n = len(secret) + matched = [] + bulls = cows = 0 + for i in range(n): + if secret[i] == guess[i]: + bulls += 1 + + a = Counter(secret) + b = Counter(guess) + + for i in set(secret): + cows += min(a[i], b[i]) + + ans = str(bulls) + "A" + str(cows - bulls) + "B" + return ans \ No newline at end of file diff --git a/LeetCode/0337_House_Robber_III.py b/LeetCode/0337_House_Robber_III.py new file mode 100644 index 0000000..1198458 --- /dev/null +++ b/LeetCode/0337_House_Robber_III.py @@ -0,0 +1,75 @@ +''' +337. House Robber III +The thief has found himself a new place for his thievery again. +There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. +After a tour, the smart thief realized that "all houses in this place forms a binary tree". +It will automatically contact the police if two directly-linked houses were broken into on the same night. +Determine the maximum amount of money the thief can rob tonight without alerting the police. +Example 1: + Input: [3,2,3,null,3,null,1] + 3 + / \ + 2 3 + \ \ + 3 1 + +Output: 7 + Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. + +Time Complexity:- O(N) +Space Complexity:- O(N), as we are using dictionary to memoize the solution +''' + +def rob(self, root: TreeNode) -> int: + # this dp dictionary will help us reduce the time complexity by memoizing the solutions + dp = {} + + # this function will return the max profit that we can get + def rob_helper(root): + # base cases + if(root is None): + return 0 + # if we have the value for root in dp that we means we have calculated the value + # previously so we can simply return the saved value + if(root in dp.keys()): + return dp[root] + ''' + In this problem our constraints are:- + 1. If we add/rob the profit of parent then we can't add/rob profit of children + as the police will be alerted + 2. If we don't rob the parent then we can rob its child nodes + + Example:- + + lvl 1 3 + / \ + lvl 2 2 3 + \ \ + lvl 3 3 1 + In this if we add the profit for 3 then we can't add 2 and 3 from level 2 but add 3 and 1 from level 3 + If we add 2 and 3 from level 2 then we can't add profit from level 1 and 3 + Therefore, in a nutshell WE CAN'T ADD THE PROFIT OF 2 ADJACENT LEVEL/HOUSES + + ''' + + # It is the total profit if we exclude the parent and add the left and right child + profit1 = rob_helper(root.left) + rob_helper(root.right) + + # In this case we left child nodes and added the profit for parent node + profit2 = root.val + # As we robbed the parent node so we can't rob children + # but we can rob children of left and right child of parent + + # If root.left has left and right children then add there profit + if(root.left is not None): + profit2 += rob_helper(root.left.left) + rob_helper(root.left.right) + # If root.right has left and right children then add there profit + if(root.right is not None): + profit2 += rob_helper(root.right.left) + rob_helper(root.right.right) + + # save the max value in DP to memoize the solution + dp[root] = max(profit1, profit2) + + return dp[root] + + return rob_helper(root) diff --git a/LeetCode/0343_Integer_Break.py b/LeetCode/0343_Integer_Break.py new file mode 100644 index 0000000..6835228 --- /dev/null +++ b/LeetCode/0343_Integer_Break.py @@ -0,0 +1,17 @@ +class Solution: + def integerBreak(self, n: int) -> int: + if n < 3: + return 1 + if n == 3: + return 2 + mylist = [1, 2, 3] + for i in range(4, n+1): + temp = [i] + for j in range((i+1)//2): + temp.append(mylist[j]*mylist[-j-1]) + mylist.append(max(temp)) + print(mylist, temp) + return max(mylist) + +solution = Solution() +print(solution.integerBreak(n =4)) \ No newline at end of file diff --git a/LeetCode/0347_Top_K_Frequent_Elements.py b/LeetCode/0347_Top_K_Frequent_Elements.py new file mode 100644 index 0000000..9a828d1 --- /dev/null +++ b/LeetCode/0347_Top_K_Frequent_Elements.py @@ -0,0 +1,57 @@ +from collections import Counter +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + count = Counter(nums) + unique = list(count.keys()) + + def partition(left, right, pivot_index) -> int: + pivot_frequency = count[unique[pivot_index]] + # 1. move pivot to end + unique[pivot_index], unique[right] = unique[right], unique[pivot_index] + + # 2. move all less frequent elements to the left + store_index = left + for i in range(left, right): + if count[unique[i]] < pivot_frequency: + unique[store_index], unique[i] = unique[i], unique[store_index] + store_index += 1 + + # 3. move pivot to its final place + unique[right], unique[store_index] = unique[store_index], unique[right] + + return store_index + + def quickselect(left, right, k_smallest) -> None: + """ + Sort a list within left..right till kth less frequent element + takes its place. + """ + # base case: the list contains only one element + if left == right: + return + + # select a random pivot_index + pivot_index = random.randint(left, right) + + # find the pivot position in a sorted list + pivot_index = partition(left, right, pivot_index) + + # if the pivot is in its final sorted position + if k_smallest == pivot_index: + return + # go left + elif k_smallest < pivot_index: + quickselect(left, pivot_index - 1, k_smallest) + # go right + else: + quickselect(pivot_index + 1, right, k_smallest) + + n = len(unique) + # kth top frequent element is (n - k)th less frequent. + # Do a partial sort: from less frequent to the most frequent, till + # (n - k)th less frequent element takes its place (n - k) in a sorted array. + # All element on the left are less frequent. + # All the elements on the right are more frequent. + quickselect(0, n - 1, n - k) + # Return top k frequent elements + return unique[n - k:] diff --git a/LeetCode/0367_ValidPerfectSquare.py b/LeetCode/0367_ValidPerfectSquare.py new file mode 100644 index 0000000..d6c025b --- /dev/null +++ b/LeetCode/0367_ValidPerfectSquare.py @@ -0,0 +1,15 @@ +class Solution(object): + def isPerfectSquare(self, num): + """ + :type num: int + :rtype: bool + """ + + i = 1 + sum_odds = 0 + while sum_odds < num: + sum_odds += i + if sum_odds == num: + return True + i += 2 + return False \ No newline at end of file diff --git a/LeetCode/0368_Largest_Divisible_Subset.py b/LeetCode/0368_Largest_Divisible_Subset.py new file mode 100644 index 0000000..ea55aeb --- /dev/null +++ b/LeetCode/0368_Largest_Divisible_Subset.py @@ -0,0 +1,27 @@ +class Solution: + def largestDivisibleSubset(self, nums: List[int]) -> List[int]: + if len(nums) < 2: + return nums + #creating a monotonic sequence of list + nums.sort() + #creating a DP list to keep track of how many preceeding elements can divide ith element + dp = [1]*len(nums) + max_ind = 0 + #dp pass using the following condition + for i in range(1, len(nums)): + for j in range(i): + if nums[i]%nums[j] == 0: + dp[i] = max(dp[i], dp[j] + 1) + if dp[max_ind] < dp[i]: + max_ind = i + res = [] + res.append(nums[max_ind]) + prev = nums[max_ind] + #reconstructing the sequence by iterating backwards + for i in range(max_ind - 1, -1, -1): + if dp[i] > 0 and dp[max_ind]-1 == dp[i] and prev%nums[i] == 0: + res.append(nums[i]) + prev = nums[i] + max_ind = i + res.reverse() + return res \ No newline at end of file diff --git a/LeetCode/0374_Guess_Number_Higher_or_Lower b/LeetCode/0374_Guess_Number_Higher_or_Lower new file mode 100644 index 0000000..5d6917d --- /dev/null +++ b/LeetCode/0374_Guess_Number_Higher_or_Lower @@ -0,0 +1,11 @@ +class Solution: + def guessNumber(self, n: int) -> int: + l, r = 0, n + while l <= r: + m = (l + r)//2 + if guess(m) == 0: return m + elif guess(m) == -1: + r = m - 1 + else: + l = m + 1 + return l diff --git a/LeetCode/0383_RansomNote.py b/LeetCode/0383_RansomNote.py new file mode 100644 index 0000000..4eb197b --- /dev/null +++ b/LeetCode/0383_RansomNote.py @@ -0,0 +1,6 @@ +class Solution: + def canConstruct(self, ransomNote: str, magazine: str) -> bool: + return all( + ransomNote.count(letter) <= magazine.count(letter) + for letter in set(ransomNote) + ) diff --git a/LeetCode/0412_Fizz Buzz.py b/LeetCode/0412_Fizz Buzz.py new file mode 100644 index 0000000..fe6d00b --- /dev/null +++ b/LeetCode/0412_Fizz Buzz.py @@ -0,0 +1,4 @@ +class Solution(object): + def fizzBuzz(self, n): + return [str(i) * (i % 3 != 0 and i % 5 != 0) + "Fizz" * (i % 3 == 0) + "Buzz" * (i % 5 == 0) + for i in range(1, n + 1)] diff --git a/LeetCode/0414_Third_Maximum_Number.py b/LeetCode/0414_Third_Maximum_Number.py new file mode 100644 index 0000000..fdf1d00 --- /dev/null +++ b/LeetCode/0414_Third_Maximum_Number.py @@ -0,0 +1,7 @@ +class Solution: + def thirdMax(self, nums: List[int]) -> int: + nums_set = sorted(set(nums), reverse=True) + if len(nums_set) >= 3: + return nums_set[2] + else: + return nums_set[0] diff --git a/LeetCode/0443_String_Compression.py b/LeetCode/0443_String_Compression.py new file mode 100644 index 0000000..609ce2a --- /dev/null +++ b/LeetCode/0443_String_Compression.py @@ -0,0 +1,16 @@ +class Solution: + def compress(self, chars: List[str]) -> int: + read = 0 + while read < len(chars) - 1: + count = 1 + read_next = read + 1 + while read < len(chars) - 1 and chars[read_next] == chars[read]: + del chars[read_next] + count += 1 + if count > 1: + for char in str(count): + chars.insert(read_next, char) + read_next += 1 + read = read_next + return len(chars) + diff --git a/LeetCode/0448-Find-All-Numbers-Disappeared-in-an-Array.py b/LeetCode/0448-Find-All-Numbers-Disappeared-in-an-Array.py new file mode 100644 index 0000000..ba1f630 --- /dev/null +++ b/LeetCode/0448-Find-All-Numbers-Disappeared-in-an-Array.py @@ -0,0 +1,12 @@ +class Solution: + def findDisappearedNumbers(self, nums: List[int]) -> List[int]: + List=[] + for i in range(len(nums)): + val= abs(nums[i])-1 + if(nums[val]>0): + nums[val]=-nums[val] + for i in range(len(nums)): + if(nums[i]>0): + List.append(i+1) + return List + diff --git a/LeetCode/0483_Smallest_Good_Base.py b/LeetCode/0483_Smallest_Good_Base.py new file mode 100644 index 0000000..11fcd12 --- /dev/null +++ b/LeetCode/0483_Smallest_Good_Base.py @@ -0,0 +1,33 @@ +import math + +class Solution(object): + def smallestGoodBase(self, n): + """ + :type n: str + :rtype: str + """ + n = int(n) + + for length in range(64, 2, -1): + l = 2 + r = int(math.sqrt(n) + 1) + + def sum(mid): + res = 0 + for i in range(length - 1, -1, -1): + res += mid ** i + if res > n: + return res + return res + + while l < r - 1: + mid = (l + r) // 2 + if sum(mid) <= n: + l = mid + else: + r = mid + + if sum(l) == n: + return str(l) + + return str(n - 1) diff --git a/LeetCode/0500_Keyboard_Row.py b/LeetCode/0500_Keyboard_Row.py new file mode 100644 index 0000000..40fb9c8 --- /dev/null +++ b/LeetCode/0500_Keyboard_Row.py @@ -0,0 +1,6 @@ +class Solution: + + def findWords(self, words: List[str]) -> List[str]: + rows = ["qwertyuiop", "asdfghjkl", "zxcvbnm"] + is_in_row = lambda word, row: all(letter in row for letter in set(word.lower())) + return [word for word in words if any(is_in_row(word, row) for row in rows)] diff --git a/LeetCode/0532_K_diff_Pairs_in_an_Array.py b/LeetCode/0532_K_diff_Pairs_in_an_Array.py new file mode 100644 index 0000000..1e96cc0 --- /dev/null +++ b/LeetCode/0532_K_diff_Pairs_in_an_Array.py @@ -0,0 +1,14 @@ +from collections import Counter +class Solution: + def findPairs(self, nums: List[int], k: int) -> int: + ans = 0 + c = Counter(nums) + if k == 0: + for val in c.values(): + if val > 1: + ans += 1 + return ans + for i in c.keys(): + if i + k in c.keys(): + ans += 1 + return ans diff --git a/LeetCode/0537_Complex_Number_Multiplication.py b/LeetCode/0537_Complex_Number_Multiplication.py new file mode 100644 index 0000000..33aebbd --- /dev/null +++ b/LeetCode/0537_Complex_Number_Multiplication.py @@ -0,0 +1,18 @@ + +class Solution: + def complexNumberMultiply(self, a: str, b: str) -> str: + x = a.split('+') + x[1] = x[1][:-1] + + y = b.split("+") + y[1] = y[1][:-1] + + a_real = int(x[0]) + a_img = int(x[1]) + + + b_real = int(y[0]) + b_img = int(y[1]) + return str(a_real * b_real - a_img * b_img) + "+" + str(a_real * b_img + a_img * b_real) + "i"; + + diff --git a/LeetCode/0561_Array_Partition_I.py b/LeetCode/0561_Array_Partition_I.py new file mode 100644 index 0000000..1743f89 --- /dev/null +++ b/LeetCode/0561_Array_Partition_I.py @@ -0,0 +1,3 @@ +class Solution: + def arrayPairSum(self, nums: List[int]) -> int: + return sum(sorted(nums)[::2]) \ No newline at end of file diff --git a/LeetCode/0567_Permutations_in_String.py b/LeetCode/0567_Permutations_in_String.py new file mode 100644 index 0000000..c8c03fb --- /dev/null +++ b/LeetCode/0567_Permutations_in_String.py @@ -0,0 +1,12 @@ +#Sliding Window Approach +from collections import Counter +class Solution: + def checkInclusion(self, s1, s2): + d1, d2 = Counter(s1), Counter(s2[:len(s1)]) + for start in range(len(s1), len(s2)): + if d1 == d2: return True + d2[s2[start]] += 1 + d2[s2[start-len(s1)]] -= 1 + if d2[s2[start-len(s1)]] == 0: + del d2[s2[start-len(s1)]] + return d1 == d2 \ No newline at end of file diff --git a/LeetCode/0647_Palindromic_Substrings.py b/LeetCode/0647_Palindromic_Substrings.py new file mode 100644 index 0000000..d1f8b9e --- /dev/null +++ b/LeetCode/0647_Palindromic_Substrings.py @@ -0,0 +1,21 @@ +class Solution: + def countSubstrings(self, s: str) -> int: + N = len(s) + # declaring a DP matrix of size nxn + dp = [[0 for i in range(N)] for j in range(N)] + # looping through substring of every size and checking whether it is a valid substring + for l in range(N): + for i in range(N-l): + if l == 0: + dp[i][i] = 1 + continue + if s[i] == s[i+l]: + if l == 1: + dp[i][i+l] = 1 + elif dp[i+1][i+l-1] == 1: + dp[i][i+l] = 1 + count = 0 + for i in range(N): + for j in range(N): + count+=dp[i][j] + return count \ No newline at end of file diff --git a/LeetCode/0701_Insert_into_a_Binary_Search_Tree.py b/LeetCode/0701_Insert_into_a_Binary_Search_Tree.py new file mode 100644 index 0000000..0ddd84f --- /dev/null +++ b/LeetCode/0701_Insert_into_a_Binary_Search_Tree.py @@ -0,0 +1,34 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right + +def solve(r,k): + x = TreeNode(k) + ans = r + if(not r): + return x + while(r and (r.left or r.right) ): + if(r.val < k): + if(r.right): + r = r.right + else: + r.right = x + return ans + else: + if(r.left): + r = r.left + else: + r.left = x + return ans + if(r.val < k): + r.right = x + else: + r.left = x + return ans + +class Solution: + def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: + return solve(root,val) diff --git a/LeetCode/0728_Self_Dividing_Numbers.py b/LeetCode/0728_Self_Dividing_Numbers.py new file mode 100644 index 0000000..af5a2f0 --- /dev/null +++ b/LeetCode/0728_Self_Dividing_Numbers.py @@ -0,0 +1,10 @@ +class Solution: + def selfDividingNumbers(self, left: int, right: int) -> List[int]: + result = [] + for i in range(left, right+1): + for char in str(i): + if int(char)==0 or i % int(char)!=0: + break + else: + result.append(i) + return result \ No newline at end of file diff --git a/LeetCode/0741_CherryPickup.py b/LeetCode/0741_CherryPickup.py new file mode 100644 index 0000000..79cca13 --- /dev/null +++ b/LeetCode/0741_CherryPickup.py @@ -0,0 +1,14 @@ +class Solution: + def cherryPickup(self, grid: List[List[int]]) -> int: + n = len(grid) + + @lru_cache(None) + def fn(t, i, ii): + """Return maximum cherries collected at kth step when two robots are at ith and iith row""" + j, jj = t - i, t - ii #columns + if not (0 <= i < n and 0 <= j < n) or t < i or grid[ i][ j] == -1: return -inf #robot 1 not at proper location + if not (0 <= ii < n and 0 <= jj < n) or t < ii or grid[ii][jj] == -1: return -inf #robot 2 not at proper location + if t == 0: return grid[0][0] #starting from 0,0 + return grid[i][j] + (i != ii)*grid[ii][jj] + max(fn(t-1, x, y) for x in (i-1, i) for y in (ii-1, ii)) + + return max(0, fn(2*n-2, n-1, n-1)) \ No newline at end of file diff --git a/LeetCode/0746_Min_Cost_Climbing_Stairs.py b/LeetCode/0746_Min_Cost_Climbing_Stairs.py new file mode 100644 index 0000000..30ffd1b --- /dev/null +++ b/LeetCode/0746_Min_Cost_Climbing_Stairs.py @@ -0,0 +1,16 @@ +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + l=len(cost) + + if l<=2: + return 0 + a=[0]*l + a[0]=cost[0] + a[1]=cost[1] + for i in range(2,l): + a[i]=min(a[i-1],a[i-2])+cost[i] + return min(a[l-1],a[l-2]) + + + + \ No newline at end of file diff --git a/LeetCode/0771_Jewels_and_Stones.py b/LeetCode/0771_Jewels_and_Stones.py new file mode 100644 index 0000000..f635dcc --- /dev/null +++ b/LeetCode/0771_Jewels_and_Stones.py @@ -0,0 +1,8 @@ +class Solution: + def numJewelsInStones(self, J: str, S: str) -> int: + stones = Counter(S) + count = 0 + for j in J: + if stones and j in stones: + count += stones[j] + return count diff --git a/LeetCode/0777_Swap_Adjacent_in_LR String.py b/LeetCode/0777_Swap_Adjacent_in_LR String.py new file mode 100644 index 0000000..628bc38 --- /dev/null +++ b/LeetCode/0777_Swap_Adjacent_in_LR String.py @@ -0,0 +1,15 @@ +# L can move left util L meets R. And R can move right util R meets L !! X is something that does not really need attention + +class Solution: + def canTransform(self, start: str, end: str) -> bool: + + if start.replace('X', '') != end.replace('X', ''): + return False + + m = collections.Counter() + for s, e in zip(start, end): + m[s] += 1 + m[e] -= 1 + if m['L'] > 0 or m['R'] < 0: + return False + return True \ No newline at end of file diff --git a/LeetCode/0832_Flipping_an_Image.py b/LeetCode/0832_Flipping_an_Image.py new file mode 100644 index 0000000..cfbe118 --- /dev/null +++ b/LeetCode/0832_Flipping_an_Image.py @@ -0,0 +1,11 @@ +class Solution: + def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: + for row in A: + for i in range(int((len(row) + 1) / 2)): + """ + In Python, the shortcut row[~i] = row[-i-1] = row[len(row) - 1 - i] + helps us find the i-th value of the row, counting from the right. + """ + row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1 + return A + \ No newline at end of file diff --git a/LeetCode/0888_Fair_Candy_Swap.py b/LeetCode/0888_Fair_Candy_Swap.py new file mode 100644 index 0000000..b165ac3 --- /dev/null +++ b/LeetCode/0888_Fair_Candy_Swap.py @@ -0,0 +1,9 @@ +class Solution: + def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]: + total_a = sum(A) + total_b = sum(B) + set_b = set(B) + for candy in A: + swap_item = candy + (total_b - total_a) / 2 + if swap_item in set_b: + return [candy, candy + (total_b - total_a) / 2] \ No newline at end of file diff --git a/LeetCode/0933_Number_of_Recent_Calls.py b/LeetCode/0933_Number_of_Recent_Calls.py new file mode 100644 index 0000000..fe0ac67 --- /dev/null +++ b/LeetCode/0933_Number_of_Recent_Calls.py @@ -0,0 +1,10 @@ +class RecentCounter: + + def __init__(self): + self.p = [] + + def ping(self, t: int) -> int: + self.p.append(t) + while self.p[0] < t - 3000: + self.p.pop(0) + return len(self.p) \ No newline at end of file diff --git a/LeetCode/0938_Range_Sum_of_BST.py b/LeetCode/0938_Range_Sum_of_BST.py new file mode 100644 index 0000000..3db83d4 --- /dev/null +++ b/LeetCode/0938_Range_Sum_of_BST.py @@ -0,0 +1,15 @@ +class Solution: + def __init__(self): + self.ans = 0 + + def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: + def dfs(node): + if node: + if L <= node.val <= R: + self.ans += node.val + if L < node.val: + dfs(node.left) + if node.val < R: + dfs(node.right) + dfs(root) + return self.ans diff --git a/LeetCode/0973_ K_Closest_Points_to_Origin.py b/LeetCode/0973_ K_Closest_Points_to_Origin.py new file mode 100644 index 0000000..445b56f --- /dev/null +++ b/LeetCode/0973_ K_Closest_Points_to_Origin.py @@ -0,0 +1,28 @@ +from heapq import heappop, heappush +from typing import List, Tuple + + +class Solution: + def closest_points(self, points: List[Tuple[float, float]], k: int) -> List[Tuple[float, float]]: + """ + Finds the K points closest to the origin. + + The implementation pushes the points on a Heap with their key being the distance to the origin, then removes K elements from the heap. + I chose to go with a more verbose implementation to show how it can be done, but alternatively one could do: + + >>> from heapq import nsmallest + ... nsmallest(k, points, key=self.distance) + """ + + heap = [] + for point in points: + heappush(heap, (self.distance(point), point)) + + return [heappop(heap)[1] for _ in range(k)] + + def distance(self, point: Tuple[float, float]) -> float: + """ + Pythagorean formula to get the distance to the origin. + """ + + return (point[0] ** 2 + point[1] ** 2) ** 0.5 diff --git a/LeetCode/1009_Complement_of_base_10_integer.py b/LeetCode/1009_Complement_of_base_10_integer.py new file mode 100644 index 0000000..6ec5c64 --- /dev/null +++ b/LeetCode/1009_Complement_of_base_10_integer.py @@ -0,0 +1,11 @@ +class Solution: + def bitwiseComplement(self, N: int) -> int: + binary = bin(N)[2:] + ans = ['0'] * len(binary) + for i in range(len(binary)): + if binary[i] == '0': + ans[i] = '1' + else: + ans[i] = '0' + return int(''.join(ans), 2) + diff --git a/LeetCode/1018_Binary_Tree_Prefix_Divisible_By_5.py b/LeetCode/1018_Binary_Tree_Prefix_Divisible_By_5.py new file mode 100644 index 0000000..41d97ee --- /dev/null +++ b/LeetCode/1018_Binary_Tree_Prefix_Divisible_By_5.py @@ -0,0 +1,12 @@ +class Solution(object): + def prefixesDivBy5(self, A): + """ + :type A: List[int] + :rtype: List[bool] + """ + prev = 0 + for i in range(len(A)): + prev = 2 * prev + A[i] + A[i] = prev % 5 == 0 + return A + diff --git a/LeetCode/1023_Camelcase_Matching.py b/LeetCode/1023_Camelcase_Matching.py new file mode 100644 index 0000000..479cc5b --- /dev/null +++ b/LeetCode/1023_Camelcase_Matching.py @@ -0,0 +1,35 @@ +import re + +class Solution: + def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: + p = re.findall('[A-Z][^A-Z]*', pattern) + result = [] + + for x in queries: + y = re.findall('[A-Z][^A-Z]*', x) + if len(p) != len(y): + result.append(False) + + else: + q = [] + + for i in range(len(p)): + t = 'false' + pi = p[i] + c = len(pi) + ct = 0 + + for j in y[i]: + if j == pi[ct]: + ct += 1 + if ct == c: + t = 'true' + break + q.append(t) + + k = True + if "false" in q: + k = False + + result.append(k) + return result diff --git a/LeetCode/1046_Last Stone Weight.py b/LeetCode/1046_Last Stone Weight.py new file mode 100644 index 0000000..9a955e4 --- /dev/null +++ b/LeetCode/1046_Last Stone Weight.py @@ -0,0 +1,26 @@ +import bisect +class Solution: + def lastStoneWeight(self, stones: List[int]) -> int: + stones.sort() + + l=len(stones) + while l>1: + + if stones[l-1]==stones[l-2]: + stones.pop() + stones.pop() + l=l-2 + else: + x=stones[l-1]-stones[l-2] + + stones.pop() + stones.pop() + bisect.insort(stones,x) + l-=1 + try: + return stones[0] + except: + return 0 + + + \ No newline at end of file diff --git a/LeetCode/1053_Previous_Permutation_With_One_Swap.py b/LeetCode/1053_Previous_Permutation_With_One_Swap.py new file mode 100644 index 0000000..6241c10 --- /dev/null +++ b/LeetCode/1053_Previous_Permutation_With_One_Swap.py @@ -0,0 +1,21 @@ +class Solution: + def prevPermOpt1(self, A: List[int]) -> List[int]: + a_length = len(A) + largest_left_index = 0 + largest_left = A[0] + for i in range(2, a_length + 1): + i *= -1 + if A[i] > A[i + 1]: + largest_left_index = i + largest_left = A[i] + break + + largest_right_index = 0 + largest_right = 0 + for i in range(a_length + largest_left_index + 1, a_length): + if A[i] > largest_right and A[i] < largest_left: + largest_right_index = i + largest_right = A[i] + + A[largest_left_index], A[largest_right_index] = A[largest_right_index], A[largest_left_index] + return A diff --git a/LeetCode/1103_Distributing_Candies_to_people.py b/LeetCode/1103_Distributing_Candies_to_people.py new file mode 100644 index 0000000..bc3b8cf --- /dev/null +++ b/LeetCode/1103_Distributing_Candies_to_people.py @@ -0,0 +1,23 @@ +def distributeCandies(self, candies: int, num_people: int) -> List[int]: + sum1, rounds, temp = sum(range(1, num_people + 1)), 0, candies + # 1. get the number of rounds that will go through the array + while temp > 0: + temp -= sum1 + rounds * num_people ** 2 + rounds += 1 + rounds -= 1 + result = [0] * num_people + # 2. add up the number until right before the final round + if rounds > 0: + for i in range(1, num_people + 1): + result[i - 1] = (2 * i + (rounds - 1) * num_people) * rounds // 2 + candies -= result[i - 1] + base_num = num_people * rounds + # 3. add the final round of numbers + for i in range(1, num_people + 1): + if candies <= base_num + i: + result[i - 1] += candies + break + else: + result[i - 1] += base_num + i + candies -= base_num + i + return result \ No newline at end of file diff --git a/LeetCode/1108_Defanging_an_IP_Address.py b/LeetCode/1108_Defanging_an_IP_Address.py new file mode 100644 index 0000000..bdd37a7 --- /dev/null +++ b/LeetCode/1108_Defanging_an_IP_Address.py @@ -0,0 +1,3 @@ +class Solution: + def defangIPaddr(self, address: str) -> str: + return(address.replace('.','[.]')) diff --git a/LeetCode/1137_N_th_Tribonacci_Number.py b/LeetCode/1137_N_th_Tribonacci_Number.py new file mode 100644 index 0000000..8c01a86 --- /dev/null +++ b/LeetCode/1137_N_th_Tribonacci_Number.py @@ -0,0 +1,14 @@ +class Solution: + def tribonacci(self, n: int) -> int: + a, b, c = 0, 1, 1 + if n == 0: + return 0 + elif n == 1 or n == 2: + return 1 + else: + for _ in range(n - 2): + temp = a + b + c + a = b + b = c + c = temp + return temp diff --git a/LeetCode/1160_FindWordsThatCanBeFormedByCharacters.py b/LeetCode/1160_FindWordsThatCanBeFormedByCharacters.py new file mode 100644 index 0000000..f45bab0 --- /dev/null +++ b/LeetCode/1160_FindWordsThatCanBeFormedByCharacters.py @@ -0,0 +1,23 @@ +class Solution: + def countCharacters(self, words: List[str], chars: str) -> int: + charBins = {char:chars.count(char) for char in chars} + goodWords = [] + + for word in words: + if (len(word) > len(chars)): + continue + + if not set(word).issubset(chars): + continue + + letterBins = {letter:word.count(letter) for letter in word} + + goodWord = True + for letter in letterBins: + if letterBins[letter] > charBins[letter]: + goodWord = False + + if (goodWord): + goodWords.append(word) + + return sum(len(word) for word in goodWords) diff --git a/LeetCode/1189_Maximum_Number_of_Balloons.py b/LeetCode/1189_Maximum_Number_of_Balloons.py new file mode 100644 index 0000000..805eaf3 --- /dev/null +++ b/LeetCode/1189_Maximum_Number_of_Balloons.py @@ -0,0 +1,12 @@ +class Solution(object): + def maxNumberOfBalloons(self, text) -> int: + """ + :type text: str + :rtype: int + """ + a_count = text.count("b") + b_count = text.count("a") + l_count = text.count("l") / 2 + o_count = text.count("o") / 2 + n_count = text.count("n") + return int(min([a_count,b_count,l_count,o_count,n_count])) \ No newline at end of file diff --git a/LeetCode/1221_Split_ a_String_in_Balanced_Strings.py b/LeetCode/1221_Split_ a_String_in_Balanced_Strings.py new file mode 100644 index 0000000..676979f --- /dev/null +++ b/LeetCode/1221_Split_ a_String_in_Balanced_Strings.py @@ -0,0 +1,13 @@ +class Solution: + def balancedStringSplit(self, s: str) -> int: + r= 0 + l = 0 + count = 0 + for i in range(len(s)): + if s[i] == "R": + r += 1 + else: + l += 1 + if r == l: + count += 1 + return count diff --git a/LeetCode/1227_Airplane_Seat_Assignment_Probability.py b/LeetCode/1227_Airplane_Seat_Assignment_Probability.py new file mode 100644 index 0000000..b0164c4 --- /dev/null +++ b/LeetCode/1227_Airplane_Seat_Assignment_Probability.py @@ -0,0 +1,6 @@ +class Solution: + def nthPersonGetsNthSeat(self, n: int) -> float: + if n == 1: + return 1.0 + else: + return 0.5 \ No newline at end of file diff --git a/LeetCode/1249_Minimum_Remove_to_Make_Valid_Parentheses.py b/LeetCode/1249_Minimum_Remove_to_Make_Valid_Parentheses.py new file mode 100644 index 0000000..b53b968 --- /dev/null +++ b/LeetCode/1249_Minimum_Remove_to_Make_Valid_Parentheses.py @@ -0,0 +1,28 @@ +class Solution: + def minRemoveToMakeValid(self, s: str) -> str: + + stackparen = [] + stackindex = [] + result = '' + result1 = '' + i = 0 + j = 0 + + while i <= len(s) - 1: + if s[i] == ')' and len(stackparen) == 0: + i += 1 + continue + if s[i] == '(': + stackparen.append(s[i]) + stackindex.append(j) + if s[i] == ')' and len(stackparen) > 0: + stackparen.pop() + stackindex.pop() + result += s[i] + j += 1 + i += 1 + + for j, i in enumerate(result): + if j not in stackindex: + result1 += result[j] + return result1 diff --git a/LeetCode/1250_Check_If_It_Is_a_Good_Array.py b/LeetCode/1250_Check_If_It_Is_a_Good_Array.py new file mode 100644 index 0000000..0673d1c --- /dev/null +++ b/LeetCode/1250_Check_If_It_Is_a_Good_Array.py @@ -0,0 +1,15 @@ +class Solution(object): + def isGoodArray(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + def gcd(a, b): + if a == 0: + return b + if a > b: + return gcd(b, a) + return gcd(b % a, a) + + return reduce(gcd, nums) == 1 + diff --git a/LeetCode/1288_Remove_Covered_Intervals.py b/LeetCode/1288_Remove_Covered_Intervals.py new file mode 100644 index 0000000..143dc05 --- /dev/null +++ b/LeetCode/1288_Remove_Covered_Intervals.py @@ -0,0 +1,11 @@ +class Solution: + def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: + intervals.sort(key=lambda x: (x[0], -x[1])) + inside = 0 + right = -1 + for i, j in intervals: + if j <= right: + inside += 1 + else: + right = j + return len(intervals) - inside diff --git a/LeetCode/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts.py b/LeetCode/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts.py new file mode 100644 index 0000000..3f8c607 --- /dev/null +++ b/LeetCode/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts.py @@ -0,0 +1,10 @@ +class Solution: + def generateTheString(self, n: int) -> str: + ans=[] + if n%2==0: + ans=['x' for i in range(n-1)] + ans.append('y') + else: + ans=['x' for i in range(n)] + return ans + \ No newline at end of file diff --git a/LeetCode/1380_Lucky_Numbers_in_a_Matrix.py b/LeetCode/1380_Lucky_Numbers_in_a_Matrix.py new file mode 100644 index 0000000..44570a6 --- /dev/null +++ b/LeetCode/1380_Lucky_Numbers_in_a_Matrix.py @@ -0,0 +1,8 @@ +class Solution: + def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: + min_n = {min(rows) for rows in matrix} + max_n = {max(columns) for columns in zip(*matrix)} + + return list(min_n & max_n) + + \ No newline at end of file diff --git a/LeetCode/1402_Reducing_Dishes.py b/LeetCode/1402_Reducing_Dishes.py new file mode 100644 index 0000000..1f2c012 --- /dev/null +++ b/LeetCode/1402_Reducing_Dishes.py @@ -0,0 +1,11 @@ +class Solution: + def maxSatisfaction(self, satisfaction: List[int]) -> int: + + satisfaction.sort(reverse=True) + ans = cur_sum = 0 + for ele in satisfaction: + cur_sum += ele + if cur_sum >= 0: + ans += cur_sum + + return ans; \ No newline at end of file diff --git a/LeetCode/1431_Kids_With_the_Greatest_Number_of_Candies.py b/LeetCode/1431_Kids_With_the_Greatest_Number_of_Candies.py new file mode 100644 index 0000000..c6b81b6 --- /dev/null +++ b/LeetCode/1431_Kids_With_the_Greatest_Number_of_Candies.py @@ -0,0 +1,11 @@ +class Solution: + def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: + m=max(candies) + t=m-extraCandies + output=[] + for i in candies: + if i List[str]: + res = [] + j = 0 + for i in range(1,n+1): + res.append("Push") + if i == target[j]: + j += 1 + else: + res.append("Pop") + if j == len(target): + break + return res \ No newline at end of file diff --git a/LeetCode/1460_Make_Two_Arrays_Equal_by_Reversing_Sub_Arrays.py b/LeetCode/1460_Make_Two_Arrays_Equal_by_Reversing_Sub_Arrays.py new file mode 100644 index 0000000..831907b --- /dev/null +++ b/LeetCode/1460_Make_Two_Arrays_Equal_by_Reversing_Sub_Arrays.py @@ -0,0 +1,5 @@ +from collections import Counter + +class Solution: + def canBeEqual(self, target: List[int], arr: List[int]) -> bool: + return Counter(target) == Counter(arr) \ No newline at end of file diff --git a/LeetCode/1464_Maximum_Product_Of_Two_Elements_In_An_Array.py b/LeetCode/1464_Maximum_Product_Of_Two_Elements_In_An_Array.py new file mode 100644 index 0000000..c1fcb8f --- /dev/null +++ b/LeetCode/1464_Maximum_Product_Of_Two_Elements_In_An_Array.py @@ -0,0 +1,4 @@ +class Solution: + def maxProduct(self, nums: List[int]) -> int: + nums.sort() + return (nums[-1]-1) * (nums[-2]-1) \ No newline at end of file diff --git a/LeetCode/1499_Max_Value_of_Equation.py b/LeetCode/1499_Max_Value_of_Equation.py new file mode 100644 index 0000000..4c1f330 --- /dev/null +++ b/LeetCode/1499_Max_Value_of_Equation.py @@ -0,0 +1,23 @@ +class Solution(object): + def findMaxValueOfEquation(self, points, k): + """ + :type points: List[List[int]] + :type k: int + :rtype: int + """ + ans = None + + d = deque() + for x, y in points: + while len(d) > 0 and d[0][0] < x - k: + d.popleft() + + if len(d) != 0: + ans = max(ans, x + y + d[0][1] - d[0][0]) + + while (len(d) != 0) and d[-1][1] - d[-1][0] < y - x: + d.pop() + + d.append((x, y)) + + return ans diff --git a/LeetCode/1512_Number_of_Good_Pairs.py b/LeetCode/1512_Number_of_Good_Pairs.py new file mode 100644 index 0000000..f0eafe2 --- /dev/null +++ b/LeetCode/1512_Number_of_Good_Pairs.py @@ -0,0 +1,8 @@ +class Solution: + def numIdenticalPairs(self, nums: List[int]) -> int: + ans = 0 + for i in range(0, len(nums)): + for j in range(0, len(nums)): + if(nums[i] == nums[j] and i < j): + ans += 1 + return ans \ No newline at end of file diff --git a/LeetCode/1559_Detect_Cycles_In_2D_Grid.py b/LeetCode/1559_Detect_Cycles_In_2D_Grid.py new file mode 100644 index 0000000..92985e3 --- /dev/null +++ b/LeetCode/1559_Detect_Cycles_In_2D_Grid.py @@ -0,0 +1,55 @@ +class Solution: + def __init__(self): + self.directionX = [-1,0,1,0] + self.directionY = [0,1,0,-1] + def isValid(self, x, y, N, M): + if x < N and x >= 0 and y < M and y >= 0: + return True + return False + + def isCycle(self, x, y, arr, visited, parentX, parentY): + # Mark the current vertex as visited + visited[x][y] = True + N, M = len(arr), len(arr[0]) + + for k in range(4): + newX = x + self.directionX[k] + newY = y + self.directionY[k] + if self.isValid(newX, newY, N, M) and arr[newX][newY] == arr[x][y] and not (parentX == newX and parentY == newY): + if visited[newX][newY]: + return True + else: + + check = self.isCycle(newX, newY, arr, visited, x,y) + if check: + return True + return False + + def containsCycle(self, grid: List[List[str]]) -> bool: + N, M = len(grid), len(grid[0]) + # Initially all the cells are unvisited + visited = [[False] * M for _ in range(N)] + + # Variable to store the result + cycle = False + + # As there is no fixed position of the cycle + # we have to loop through all the elements + for i in range(N): + if cycle == True: + break + + for j in range(M): + ## Taking (-1, -1) as source node's parent + if visited[i][j] == False: + cycle = self.isCycle(i, j, grid, visited, -1, -1) + + if cycle == True: + break + + return cycle + + + + + \ No newline at end of file diff --git a/LeetCode/1582_SpecialPositionsInABinaryMatrix.py b/LeetCode/1582_SpecialPositionsInABinaryMatrix.py new file mode 100644 index 0000000..221aab6 --- /dev/null +++ b/LeetCode/1582_SpecialPositionsInABinaryMatrix.py @@ -0,0 +1,22 @@ +class Solution(object): + def numSpecial(self, mat): + """ + :type mat: List[List[int]] + :rtype: int + """ + numSpecial = 0 + + for a in range(len(mat)): + for b in range(len(mat[a])): + if mat[a][b] == 1: + valid = True + for c in range(len(mat[a])): + if mat[a][c] != 0 and c != b: + valid = False + if valid: + for d in range(len(mat)): + if mat[d][b] != 0 and d != a: + valid = False + if valid: + numSpecial+=1 + return numSpecial \ No newline at end of file diff --git a/LeetCode/1592_Rearrange_Spaces_Between_Words.py b/LeetCode/1592_Rearrange_Spaces_Between_Words.py new file mode 100644 index 0000000..cca6c53 --- /dev/null +++ b/LeetCode/1592_Rearrange_Spaces_Between_Words.py @@ -0,0 +1,9 @@ +class Solution: + def reorderSpaces(self, text: str) -> str: + words = text.split() + space_cnt = text.count(' ') + + if len(words) == 1: + return words[0] + ' ' * space_cnt + else: + return (' '* (space_cnt // (len(words)-1))).join(words)+ ' ' * (space_cnt % (len(words)-1)) \ No newline at end of file diff --git a/LeetCode/1603_Design_Parking_System.py b/LeetCode/1603_Design_Parking_System.py new file mode 100644 index 0000000..cbba789 --- /dev/null +++ b/LeetCode/1603_Design_Parking_System.py @@ -0,0 +1,11 @@ +class ParkingSystem: + + def __init__(self, big: int, medium: int, small: int): + self._limits = [big, medium, small] + + + def addCar(self, carType: int) -> bool: + self._limits[carType - 1] -= 1 + if self._limits[carType - 1] < 0: + return False + return True diff --git a/LeetCode/1605_Find_Valid_Matrix_Given_Row_and_Column_Sums.py b/LeetCode/1605_Find_Valid_Matrix_Given_Row_and_Column_Sums.py new file mode 100644 index 0000000..5631572 --- /dev/null +++ b/LeetCode/1605_Find_Valid_Matrix_Given_Row_and_Column_Sums.py @@ -0,0 +1,13 @@ +class Solution: + def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: + m = len(rowSum) + n = len(colSum) + matrix = [[0]*n for i in range(m)] + print(matrix) + for i in range(m): + for j in range(n): + matrix[i][j] = min(rowSum[i],colSum[j]) + rowSum[i] -= matrix[i][j] + colSum[j] -= matrix[i][j] + return matrix + \ No newline at end of file diff --git a/LeetCode/1611_Minimum_One_Bit_Operations_to_Make_Integers_Zero.py b/LeetCode/1611_Minimum_One_Bit_Operations_to_Make_Integers_Zero.py new file mode 100644 index 0000000..e8fd5d5 --- /dev/null +++ b/LeetCode/1611_Minimum_One_Bit_Operations_to_Make_Integers_Zero.py @@ -0,0 +1,7 @@ +class Solution: + def minimumOneBitOperations(self, n: int) -> int: + b = list(bin(n)[2:]) + temp = len(b) + for i in range(1, temp): + b[i] = str(int(b[i]) ^ int(b[i-1])) + return int(''.join(b), 2) diff --git a/LeetCode/237_Delete_Node_in_a_Linked_List.py b/LeetCode/237_Delete_Node_in_a_Linked_List.py new file mode 100644 index 0000000..f9bbb08 --- /dev/null +++ b/LeetCode/237_Delete_Node_in_a_Linked_List.py @@ -0,0 +1,14 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def deleteNode(self, node): + """ + :type node: ListNode + :rtype: void Do not return anything, modify node in-place instead. + """ + node.val = node.next.val + node.next = node.next.next diff --git a/README.md b/README.md index 73f586e..46f4b1a 100644 --- a/README.md +++ b/README.md @@ -33,10 +33,19 @@ To contribute make sure the Algorithm isn't commited yet! Make sure to add the n Please make sure your file is in the `LeetCode`-Folder and Named like this: `0001_TwoSum.py` -> 4-digit Number of the LeetCode Issue, Underscore, LeetCodeName +### Opening Issues +When you open an issue, please make sure the Problem is not already implemented (Look at Code/Leetcode for the Problemnumber). +Opened Issues by existing Problem will be closed & PR made to this Issue marked as **spam** +The Contributer who opened an issue will be assigned prefered to the issue. If there is no PR within about 7 Days the issue will be assigned to another Contributer. + ### Pull Requests Only Pull Requests **joined with an Issue** and matching the **naming-conventions** (See Folders and Files) will be merged! If there is no Issue joined in the PR your PR will be labeld as **spam** and closed. If your code don't passes the Check on LeetCode.com your PR will be labeld as **"invalid"** and the Issue stays open for the next PR! +If your PR doesn' follow the Contributing Guidelines of this Repository it will be also marked as **spam** and closed! + +### Spam Users +Users who spam this Repo with PRs/Issues that does not align the Contribution Guidelines will be **blocked**. ## Getting Started * Fork this repository (Click the Form button, top right of this page) @@ -67,6 +76,17 @@ git push origin branch-name ## Which PR will be accepted? * Ones you are assigned to * Your PR has to link the Issue -* Your Solution must be correct - you can check ist on LeetCode (submit) if it works on different test-cases +* Your Solution must be correct - you can check first on LeetCode (submit) if it works on different test-cases + +## Which PRs will be NOT accepted? +* Ones you are NOT assigned to +* Your PR is NOT linked to the Issue you are linked to +* Your Solution is not correct +* Your PR contains more than the .py file +* PRs that "correct" Typos or spam files with comments +* PRs that "correct" Coding Styles - Please accept that everybody has a different style + +## Hacktoberfest +During October there come pretty much PRs and Issues - Please be patient because of my fulltime job I cannot be online 24/7 - I do my best to work through your PRs as soon as possible. __Thank You!__