Skip to content

Commit

Permalink
some solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
userr2232 committed Jul 27, 2021
1 parent 7c5cd69 commit 9bef399
Show file tree
Hide file tree
Showing 58 changed files with 1,651 additions and 0 deletions.
18 changes: 18 additions & 0 deletions LeetCode/ 10.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution:
def isMatch(self, s: str, p: str) -> bool:
memo = dict()
ns, np = len(s), len(p)
def DP(i, j):
nonlocal s, p, ns, np
if j >= np: return i >= ns
val = memo.get((i, j))
if val is not None:
return val
left_match = i < ns and p[j] in {s[i], '.'}
if j <= np - 2 and p[j+1] == '*':
res = memo[(i, j)] = left_match and DP(i+1, j) or DP(i, j+2)
return res
else:
res = memo[(i, j)] = left_match and DP(i+1, j+1)
return res
return DP(0, 0)
16 changes: 16 additions & 0 deletions LeetCode/124.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Solution {
public:
int maxx = -1e9;
int max_gain(TreeNode* current) {
if(!current) return 0;
auto left_max = max(max_gain(current->left), 0);
auto right_max = max(max_gain(current->right), 0);
maxx = max(maxx, current->val + left_max + right_max);
return current->val + max(left_max, right_max);
}

int maxPathSum(TreeNode* root) {
max_gain(root);
return maxx;
}
};
31 changes: 31 additions & 0 deletions LeetCode/1249.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution {
public:
string minRemoveToMakeValid(string s) {
stack<int> st;
set<int> valid;
int i = 0;
for(char c : s) {
if(c == '(') st.push(i++);
else if(c == ')') {
if(!st.empty()) {
auto x = st.top();
st.pop();
valid.insert(x);
valid.insert(i);
}
i++;
}
}
i = 0;
string answer = "";
for(char c : s) {
if(c == ')' || c == '(') {
if(valid.count(i++))
answer += c;
}
else
answer += c;
}
return answer;
}
};
12 changes: 12 additions & 0 deletions LeetCode/125.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution:
def isPalindrome(self, s: str) -> bool:
i, j = 0, len(s) - 1
while i < j:
while i < j and not s[i].isalnum():
i += 1
while i < j and not s[j].isalnum():
j -= 1
if s[i].lower() != s[j].lower(): return False
i += 1
j -= 1
return True
49 changes: 49 additions & 0 deletions LeetCode/1270.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
class SparseVector:
def __init__(self, nums: List[int]):
self.l = []
c = 0
for x in nums:
if x:
if c:
self.l.append(str(c))
c = 0
self.l.append(x)
else:
c += 1
if c:
self.l.append(str(c))

def update_val(self, l, i):
new_value = int(l[i]) - 1
if new_value == 0:
i += 1
else:
l[i] = str(new_value)
return i

# Return the dotProduct of two sparse vectors
def dotProduct(self, vec: 'SparseVector') -> int:
answer = i = j = 0
while True:
if i == len(self.l) or j == len(vec.l):
return answer
if type(self.l[i]).__name__ == "int" and type(vec.l[j]).__name__ == "int":
answer += self.l[i] * vec.l[j]
i += 1
j += 1
else:
if type(self.l[i]).__name__ == "str" and type(vec.l[j]).__name__ == "str":
i = self.update_val(self.l, i)
j = self.update_val(vec.l, j)
elif type(self.l[i]).__name__ == "str":
j += 1
i = self.update_val(self.l, i)
else:
i += 1
j = self.update_val(vec.l, j)


# Your SparseVector object will be instantiated and called as such:
# v1 = SparseVector(nums1)
# v2 = SparseVector(nums2)
# ans = v1.dotProduct(v2)
43 changes: 43 additions & 0 deletions LeetCode/140.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class Solution:
def DP(self, i, j):
self.called.add((i, j))
if i > j: return
if self.s[i:j] in self.better_dict:
self.starts_with[i].add((i,j))
for m in range(i, j):
if (i, m) not in self.called:
self.DP(i, m)
if (m, j) not in self.called:
self.DP(m, j)

def add_answer(self, l):
res = []
for tup in l:
res.append(self.s[tup[0]:tup[1]])
self.answer.append(' '.join(res))

def DFS(self, current, l):
_, end = current
l.append(current)
if end == self.n:
self.add_answer(l)
return
for neighbor in self.starts_with[end]:
before = l[:]
self.DFS(neighbor, l)
l = before
self.visited.add(current)

def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
self.better_dict = set(wordDict)
self.s = s
self.called = set()
self.starts_with = defaultdict(set)
self.n = len(s)
self.DP(0, self.n)
self.visited = set()
print(self.starts_with)
self.answer = []
for tup in self.starts_with[0]:
self.DFS(tup, [])
return self.answer
28 changes: 28 additions & 0 deletions LeetCode/1428.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution:
def check_col(self, col):
for x in col:
if x == 1: return True
return False

def find_min_col(self):
mn, mx = 0, self.n_cols - 1
col = None
idx = (mn + mx) // 2
col = self.get_col(idx)
while mn < mx:
if self.check_col(col):
mx = idx
else:
mn = idx + 1
idx = (mn + mx) // 2
col = self.get_col(idx)
if self.check_col(col): return idx
else: return -1

def get_col(self, idx):
return [ self.bin.get(i, idx) for i in range(self.n_rows) ]

def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
self.bin = binaryMatrix
self.n_rows, self.n_cols = binaryMatrix.dimensions()
return self.find_min_col()
13 changes: 13 additions & 0 deletions LeetCode/1539.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class Solution {
public:
int findKthPositive(vector<int>& arr, int k) {
int missing{0}, missing_counter{0};
int n = arr.size();
for(int i = 0; i < n; ++i) {
missing_counter += arr[i] - ++missing;
missing = arr[i];
if(missing_counter >= k) return missing - (missing_counter - k) - 1;
}
return missing + k - missing_counter;
}
};
36 changes: 36 additions & 0 deletions LeetCode/158.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution:
def __init__(self):
self.prev_read = []

def read(self, buf: List[str], n: int) -> int:
chars_current_read = 0
buf_idx = 0
while n >= 0:
n_prev_read = len(self.prev_read)
if n_prev_read:
if n > n_prev_read:
chars_current_read += n_prev_read
buf[buf_idx:buf_idx+n_prev_read] = self.prev_read
self.prev_read = []
buf_idx += n_prev_read
n -= n_prev_read
elif n == n_prev_read:
chars_current_read += n_prev_read
buf[buf_idx:buf_idx+n_prev_read] = self.prev_read
self.prev_read = []
return chars_current_read
else:
# n < n_prev_read
chars_current_read += n
buf[buf_idx:buf_idx+n] = self.prev_read[:n]
self.prev_read = self.prev_read[n:]
return chars_current_read
else:
self.prev_read = [None]*4
n_read = read4(self.prev_read)
self.prev_read = self.prev_read[:n_read]
if n_read == 0:
break

return chars_current_read

15 changes: 15 additions & 0 deletions LeetCode/1650.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class Solution:
def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
root = p
while root.parent:
root = root.parent
def dfs_helper(cur, p, q):
if not cur: return None
if cur == p or cur == q: return cur
left = dfs_helper(cur.left, p, q)
right = dfs_helper(cur.right, p, q)
if left and right: return cur
if not left and not right: return None
return left if left else right

return dfs_helper(root, p, q)
20 changes: 20 additions & 0 deletions LeetCode/173.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class BSTIterator:

def __init__(self, root: TreeNode):
self.stack = []
self.left_most(root)

def left_most(self, root):
while root:
self.stack.append(root)
root = root.left

def next(self) -> int:
if self.stack:
current = self.stack[-1]
self.stack = self.stack[:-1]
self.left_most(current.right)
return current.val

def hasNext(self) -> bool:
return len(self.stack) > 0
27 changes: 27 additions & 0 deletions LeetCode/199.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
queue<pair<TreeNode*, int>> q;
if(!root) return vector<int>(0);
q.push({root, 0});
vector<int> answer;
while(!q.empty()) {
auto [cur, cur_level] = q.front();
q.pop();
if(!cur) continue;
if(cur->left) q.push({cur->left, cur_level+1});
if(cur->right) q.push({cur->right, cur_level+1});
if(!q.empty()) {
auto [next, next_level] = q.front();
if(next_level > cur_level) {
answer.push_back(cur->val);
}
else continue;
}
else {
answer.push_back(cur->val);
}
}
return answer;
}
};
31 changes: 31 additions & 0 deletions LeetCode/211.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class WordDictionary:

def __init__(self):
"""
Initialize your data structure here.
"""
self.trie = {}


def addWord(self, word: str) -> None:
current = self.trie
for c in word:
if c not in current:
current[c] = {}
current = current[c]
current['$'] = True

def search(self, word: str) -> bool:
def dfs_helper(current, word):
for i, c in enumerate(word):
if c not in current:
if c == '.':
for child in current:
if child != '$' and dfs_helper(current[child], word[i+1:]):
return True
return False
else:
current = current[c]
return '$' in current

return dfs_helper(self.trie, word)
7 changes: 7 additions & 0 deletions LeetCode/215.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
nth_element(nums.begin(), nums.end() - k, nums.end());
return *(nums.end() - k);
}
};
12 changes: 12 additions & 0 deletions LeetCode/236.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return nullptr;
if(root == p || root == q) return root;
auto left = lowestCommonAncestor(root->left, p, q);
auto right = lowestCommonAncestor(root->right, p, q);
if(left != nullptr and right != nullptr) return root;
if(left == nullptr and right == nullptr) return nullptr;
return left == nullptr ? right : left;
}
};
Loading

0 comments on commit 9bef399

Please sign in to comment.