— Diary, Programming — 1 min read
I started with today's Leetcode Challenge.
The question is to remove k
identical consecutive letters from a string till it's no longer possible.
The approach that I took is with stack and to store the counter, the stack is modified to be a stack of pairs.
1string removeDuplicates(string s, int k) {2 stack<pair<char, int>> stk;34 for (auto c : s) {5 if (stk.empty()) {6 stk.push(make_pair(c, 1));7 } else {8 pair<char, int> temp = stk.top();9 if (temp.first == c) {10 if (temp.second == k - 1) stk.pop();11 else {12 stk.pop();13 stk.push(make_pair(c, temp.second + 1));14 }15 } else {16 stk.push(make_pair(c, 1));17 }18 }19 }2021 string ans = "";22 while (!stk.empty()) {23 pair<char, int> temp = stk.top();24 for (int i = 0; i < temp.second; i++) {25 ans = temp.first + ans;26 }27 stk.pop();28 }2930 return ans;31}
Trying the question for 11th April.
The simplest approach would be to calculate the depth of the tree and then iterate the tree for the second time and adding the nodes at the level. It would take two iterations.
The next approach could be to store all the levels along with their sums in a map and then finding the sum associated with the maximum value. This would mean just a single iteration over the tree.
1unordered_map<int, int> umap;23void traverse(TreeNode *root, int level) {4 if (!root) return;56 umap[level] += root->val;78 traverse(root->left, level + 1);9 traverse(root->right, level + 1);10}1112int deepestLeavesSum(TreeNode *root) {13 traverse(root, 0);1415 int mx = 0;1617 for (auto a : umap) {18 mx = max(a.first, mx);19 }2021 return umap[mx];22}
The next approach is to find the maximum depth value as we traverse, and then calculating the sum according to that.
1int deepestLevel = 0, sum = 0;23void traverse(TreeNode *root, int level) {4 if (!root) return;56 if (level > deepestLevel) {7 deepestLevel = level;8 sum = 0;9 }1011 if (level == deepestLevel) {12 sum += root->val;13 }1415 traverse(root->left, level + 1);16 traverse(root->right, level + 1);17}1819int deepestLeavesSum(TreeNode *root) {20 traverse(root, 0);2122 return sum;23}
Okay, done for the day! Bye.