Skip to content

Commit

Permalink
new problems added
Browse files Browse the repository at this point in the history
  • Loading branch information
ankitpriyarup committed Oct 9, 2020
1 parent bf14d0e commit 5b0cb15
Show file tree
Hide file tree
Showing 8 changed files with 628 additions and 26 deletions.
127 changes: 127 additions & 0 deletions dynamic-programming.md
Original file line number Diff line number Diff line change
Expand Up @@ -1497,7 +1497,31 @@ int longestValidParentheses(string s)
}
return ans;
}
```

### [Minimum Swaps To Make Sequences Increasing](https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/)
```c++
vector<vector<int>> dp;
int solve(vector<int> &A, vector<int> &B, int cur = 0, bool rev = false)
{
if (cur == A.size()) return 0;
if (dp[cur][rev] != -1) return dp[cur][rev];

int p1 = (cur == 0) ? INT_MIN : A[cur-1], p2 = A[cur];
int q1 = (cur == 0) ? INT_MIN : B[cur-1], q2 = B[cur];
if (rev) swap(p1, q1);

int res = INT_MAX;
if (p1 < p2 && q1 < q2) res = min(res, solve(A, B, cur+1, false));
if (p1 < q2 && q1 < p2) res = min(res, 1+solve(A, B, cur+1, true));

return dp[cur][rev] = res;
}
int minSwap(vector<int>& A, vector<int>& B)
{
dp = vector<vector<int>>(A.size(), vector<int>(2, -1));
return solve(A, B);
}
```
### Word Break
Expand Down Expand Up @@ -1740,6 +1764,73 @@ int maxProfit(vector<int>& prices, int fee)
}
```
### House Robber
- https://leetcode.com/problems/house-robber/
- https://leetcode.com/problems/house-robber-ii/
- https://leetcode.com/problems/house-robber-iii/
```c++
// Variant - I (No adjacent house to rob allowed)
class Solution {
public:
vector<int> dp;
int solve(vector<int> &nums, int cur = 0)
{
if (cur >= nums.size()) return 0;
if (dp[cur] != -1) return dp[cur];
return dp[cur] = max(solve(nums, cur+1), nums[cur] + solve(nums, cur+2));
}
int rob(vector<int>& nums)
{
dp = vector<int> (nums.size(), -1);
return solve(nums);
}
};
// Variant - II (Array is cyclic)
class Solution {
public:
vector<int> dp;
int solve(vector<int> &nums, int l, const int r)
{
if (l >= r) return 0;
if (dp[l] != -1) return dp[l];
return dp[l] = max(solve(nums, l+1, r), nums[l] + solve(nums, l+2, r));
}
int rob(vector<int>& nums)
{
if (nums.size() == 1) return nums[0];
if (nums.size() == 2) return max(nums[0], nums[1]);
dp = vector<int> (nums.size(), -1);
int x = solve(nums, 0, nums.size()-1);
dp = vector<int> (nums.size(), -1);
int y = solve(nums, 1, nums.size());
return max(x, y);
}
};
// Variant - III (Now it's a binary tree)
class Solution {
public:
unordered_map<TreeNode*, int> dp;
int solve(TreeNode* root)
{
if (!root) return 0;
if (dp.find(root) != dp.end()) return dp[root];
int res = root->val;
if (root->left) res += solve(root->left->left) + solve(root->left->right);
if (root->right) res += solve(root->right->left) + solve(root->right->right);
res = max(res, solve(root->left) + solve(root->right));
return dp[root] = res;
}
int rob(TreeNode* root)
{
return solve(root);
}
};
```

### Weighted Job Scheduling Problem

Given jobs along with their weights we need to choose such that we get max weight out of it.
Expand Down Expand Up @@ -1826,6 +1917,42 @@ bool isMatch(string s, string p)

```
### [Different Ways to Add Paranthesis](https://leetcode.com/problems/different-ways-to-add-parentheses/)
```c++
unordered_map<string, vector<int>> dp;
vector<int> solve(string input)
{
if (dp.find(input) != dp.end()) return dp[input];
vector<int> res;
for (int i = 0; i < input.size(); ++i)
{
char ch = input[i];
if (ch == '+' || ch == '-' || ch == '*')
{
for (const int a : diffWaysToCompute(input.substr(0, i)))
{
for (const int b : diffWaysToCompute(input.substr(i+1)))
{
if (ch == '+') res.push_back(a + b);
else if (ch == '-') res.push_back(a - b);
else if (ch == '*') res.push_back(a * b);
}
}
}
}
// if input string contains only number
if (res.empty()) res.push_back(stoi(input));
return dp[input] = res;
}
vector<int> diffWaysToCompute(string input)
{
dp.clear();
return solve(input);
}
```

### Travelling Salesman Problem

Salesman travels over a set of cities, he has to return to source. Minimize total distance travelled by him. Such cycle is also called hamiltonian cycle. We want minimum weight hamiltonian cycle. we will use bitmask to make it efficient. 000001 means out of all 6 cities 1st is visited.
Expand Down
169 changes: 169 additions & 0 deletions graph-theory.md
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,26 @@ TreeNode* recoverFromPreorder(string S)
}
```
### [Binary Tree Longest Consecutive Sequence](https://www.lintcode.com/problem/binary-tree-longest-consecutive-sequence/description)
```c++
unordered_map<TreeNode*, int> dp;
void solve(TreeNode* root, TreeNode* par = NULL)
{
if (!root) return;
dp[root] = (par && root->val == par->val+1) ? dp[par]+1 : 1;
solve(root->left, root);
solve(root->right, root);
}
int longestConsecutive(TreeNode* root)
{
dp.clear();
solve(root);
int res = 0;
for (auto &x : dp) res = max(res, x.second);
return res;
}
```

### [Flatten BST to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/)

```cpp
Expand Down Expand Up @@ -1682,6 +1702,155 @@ public:
};
```
### Bidirectional BFS
- [Word Ladder](https://leetcode.com/problems/word-ladder/)
```c++
// Slow normal BFS
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
{
int m = beginWord.size(); // since all words are of same length
unordered_map<string, vector<string>> preprocess;
for (auto x : wordList)
for (int i = 0; i < m; ++i)
preprocess[x.substr(0, i) + '*' + x.substr(i+1)].push_back(x);
queue<pair<string, int>> q;
q.push({beginWord, 1});
unordered_set<string> vis; // vis to make sure we dont repeat same word
vis.insert(beginWord);
while (!q.empty())
{
auto cur = q.front(); q.pop();
if (cur.first == endWord) return cur.second;
for (int i = 0; i < m; ++i)
{
string tmp = cur.first.substr(0, i) + '*' + cur.first.substr(i+1);
for (auto &nxt : preprocess[tmp])
{
if (vis.find(nxt) == vis.end())
{
vis.insert(nxt);
q.push({nxt, cur.second+1});
}
}
}
}
return 0;
}
// Further optimization Bi directional BFS
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
{
unordered_set<string_view> rec(wordList.begin(), wordList.end());
if (rec.find(endWord) == rec.end()) return 0;
unordered_set<string_view> s1{beginWord}, s2{endWord};
rec.erase(beginWord); rec.erase(endWord);
int res = 1;
while (!s1.empty() && !s2.empty())
{
/* make sure we always expand the smaller side, thus
reduce the overall size of the 2 predecessor tree */
if (s1.size() > s2.size()) swap(s1, s2);
unordered_set<string_view> tmp;
for (const auto word : s1)
{
string wordCopy = word.data();
for (auto &ch : wordCopy)
{
char orig = ch;
for (ch = 'a'; ch <= 'z'; ++ch)
{
if (s2.find(wordCopy) != s2.end()) return res+1;
if (rec.find(wordCopy) == rec.end()) continue;
const auto it = rec.find(wordCopy);
tmp.insert(*it); rec.erase(*it);
}
ch = orig;
}
}
s1 = tmp;
++res;
}
return 0;
}
```

### [Open the lock](https://leetcode.com/problems/open-the-lock/)
```c++
int openLock(vector<string>& deadends, string target)
{
unordered_set<string> rec(deadends.begin(), deadends.end()), vis;

queue<string> q;
q.push("0000");
int cnt = 0;
while (!q.empty())
{
int sz = q.size();
while (sz--)
{
string u = q.front(); q.pop();
if (rec.find(u) != rec.end() || vis.find(u) != vis.end()) continue;
if (u == target) return cnt;
vis.insert(u);

for (auto &ch : u)
{
char orig = ch;
for (const int dir : {-1, 1})
{
ch = (((orig-'0')+dir+10) % 10) + '0';
q.push(u);
}
ch = orig;
}
}
cnt++;
}
return -1;
}

// Bi directional BFS Optimization
int openLock(vector<string>& deadends, string target)
{
unordered_set<string> rec(deadends.begin(), deadends.end()), vis;
queue<string> q1, q2;
unordered_set<string> r1, r2;
q1.push("0000"); q2.push(target); r1.insert("0000"); r2.insert(target);

int cnt = 0;
while (!q1.empty() && !q2.empty())
{
if (q1.size() > q2.size()) swap(q1, q2), swap(r1, r2);
int sz = q1.size();
while (sz--)
{
string u = q1.front(); q1.pop();
if (rec.find(u) != rec.end() || vis.find(u) != vis.end()) continue;
if (r2.find(u) != r2.end()) return cnt;
vis.insert(u);

for (auto &ch : u)
{
char orig = ch;
for (const int dir : {-1, 1})
{
ch = (((orig-'0')+dir+10) % 10) + '0';
q1.push(u);
r1.insert(u);
}
ch = orig;
}
}
cnt++;
}
return -1;
}
```
[https://codeforces.com/problemset/problem/1294/F](https://codeforces.com/problemset/problem/1294/F)
We want to find 3 points as far away as possible, two of them can be diameter of the tree third one we can by using Multisource BFS with sources \(dA and dB\) then finding farthest point
Expand Down
Loading

0 comments on commit 5b0cb15

Please sign in to comment.