diff --git a/03-Arrays/3sum-leetcode.cpp b/03-Arrays/3sum-leetcode.cpp new file mode 100644 index 0000000..3cc3ff6 --- /dev/null +++ b/03-Arrays/3sum-leetcode.cpp @@ -0,0 +1,29 @@ +//Optimized Approach - O(n^2 logn + nlogn) - o(n^2 logn) time and O(n) space +class Solution { +public: + vector> threeSum(vector& nums) { + int target = 0; + sort(nums.begin(), nums.end()); + set> s; + vector> output; + for (int i = 0; i < nums.size(); i++){ + int j = i + 1; + int k = nums.size() - 1; + while (j < k) { + int sum = nums[i] + nums[j] + nums[k]; + if (sum == target) { + s.insert({nums[i], nums[j], nums[k]}); + j++; + k--; + } else if (sum < target) { + j++; + } else { + k--; + } + } + } + for(auto triplets : s) + output.push_back(triplets); + return output; + } +}; diff --git a/10- Recursion & Backtracking/Path-Sum-II.cpp b/10- Recursion & Backtracking/Path-Sum-II.cpp new file mode 100644 index 0000000..18da2e4 --- /dev/null +++ b/10- Recursion & Backtracking/Path-Sum-II.cpp @@ -0,0 +1,43 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + + vector> res; //to store final result + + void traverse(TreeNode* root, vector &path, int rem){ + if(!root) return; //return at NULL + + if(!root->left && !root->right){ //leaf node reached + path.push_back(root->val); //do + if(rem == root->val) res.push_back(path); + //if remaining sum is same as value of root we have valid path + path.pop_back(); // undo + return; + } + + int val = root->val; //subtract the contribution of this value from rem (remaining sum) + path.push_back(val); //do + traverse(root->left, path, rem-val); //recurse left subtree + traverse(root->right, path, rem-val); //recurse right subtree + path.pop_back(); //undo + + } + + vector> pathSum(TreeNode* root, int targetSum) { + res.clear(); //reset res + if(!root) return res; //if root itself NULL there are no paths + vector path; //to store the path + traverse(root, path, targetSum); + return res; + } +};