From 0f52d46c6757c32abdd5cc92bed43d3690ece565 Mon Sep 17 00:00:00 2001 From: Wander_Lust Date: Wed, 11 Feb 2026 14:48:41 +0530 Subject: [PATCH] leetcode new problems --- leetcode/lc14/LongPrefix.cpp | 26 +++++++++++ leetcode/lc14/notes.md | 5 +++ leetcode/lc15/notes.md | 7 +++ leetcode/lc15/threesome.cpp | 25 +++++++++++ leetcode/lc16/closest3Sum.cpp | 24 +++++++++++ leetcode/lc18/4sumPointers.cpp | 34 +++++++++++++++ leetcode/lc18/brute4loop.cpp | 28 ++++++++++++ leetcode/lc18/ksum.cpp | 45 ++++++++++++++++++++ leetcode/lc18/notes.md | 19 +++++++++ leetcode/lc19/OnePass.cpp | 0 leetcode/lc19/TwoPass.cpp | 26 +++++++++++ leetcode/lc20/OptimalParantheses.cpp | 18 ++++++++ leetcode/lc20/ValidParantheses1.cpp | 17 ++++++++ leetcode/lc21/MergeLists.cpp | 36 ++++++++++++++++ leetcode/lc21/RecursiveMerge.cpp | 17 ++++++++ leetcode/lc22/generateParantheses.cpp | 25 +++++++++++ leetcode/lc22/optimalGenerateParantheses.cpp | 33 ++++++++++++++ leetcode/lc23/MergeKLists.cpp | 34 +++++++++++++++ leetcode/lc24/SwapNodes.cpp | 30 +++++++++++++ leetcode/lc26.cpp | 25 +++++++++++ leetcode/lc27.cpp | 14 ++++++ leetcode/lc28/bruteForce.cpp | 15 +++++++ leetcode/lc28/spaceOptimized.cpp | 11 +++++ leetcode/lc29.cpp | 28 ++++++++++++ leetcode/lc3010/MinCostArray.cpp | 15 +++++++ leetcode/lc3637/betterTrionicArray.cpp | 21 +++++++++ leetcode/lc3637/trionicArray.cpp | 20 +++++++++ leetcode/lc3637/trionicSegmentCount.cpp | 20 +++++++++ leetcode/lc5/ExpandCentre.cpp | 45 +++++++++++++++++--- 29 files changed, 658 insertions(+), 5 deletions(-) create mode 100644 leetcode/lc14/LongPrefix.cpp create mode 100644 leetcode/lc14/notes.md create mode 100644 leetcode/lc15/notes.md create mode 100644 leetcode/lc15/threesome.cpp create mode 100644 leetcode/lc16/closest3Sum.cpp create mode 100644 leetcode/lc18/4sumPointers.cpp create mode 100644 leetcode/lc18/brute4loop.cpp create mode 100644 leetcode/lc18/ksum.cpp create mode 100644 leetcode/lc18/notes.md create mode 100644 leetcode/lc19/OnePass.cpp create mode 100644 leetcode/lc19/TwoPass.cpp create mode 100644 leetcode/lc20/OptimalParantheses.cpp create mode 100644 leetcode/lc20/ValidParantheses1.cpp create mode 100644 leetcode/lc21/MergeLists.cpp create mode 100644 leetcode/lc21/RecursiveMerge.cpp create mode 100644 leetcode/lc22/generateParantheses.cpp create mode 100644 leetcode/lc22/optimalGenerateParantheses.cpp create mode 100644 leetcode/lc23/MergeKLists.cpp create mode 100644 leetcode/lc24/SwapNodes.cpp create mode 100644 leetcode/lc26.cpp create mode 100644 leetcode/lc27.cpp create mode 100644 leetcode/lc28/bruteForce.cpp create mode 100644 leetcode/lc28/spaceOptimized.cpp create mode 100644 leetcode/lc29.cpp create mode 100644 leetcode/lc3010/MinCostArray.cpp create mode 100644 leetcode/lc3637/betterTrionicArray.cpp create mode 100644 leetcode/lc3637/trionicArray.cpp create mode 100644 leetcode/lc3637/trionicSegmentCount.cpp diff --git a/leetcode/lc14/LongPrefix.cpp b/leetcode/lc14/LongPrefix.cpp new file mode 100644 index 0000000..68ea6d7 --- /dev/null +++ b/leetcode/lc14/LongPrefix.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + string longestCommonPrefix(vector& strs) { + if (strs.empty()) return ""; + + string comm = ""; + int n = strs.size(); + + for (int left = 0; left < strs[0].size(); left++) { + char ch = strs[0][left]; + + for (int i = 1; i < n; i++) { + + if (left >= strs[i].size() || strs[i][left] != ch) { + return comm; + } + } + + + comm += ch; + } + + return comm; + } +}; + diff --git a/leetcode/lc14/notes.md b/leetcode/lc14/notes.md new file mode 100644 index 0000000..5740a88 --- /dev/null +++ b/leetcode/lc14/notes.md @@ -0,0 +1,5 @@ +Time complexity : O(n*m) where is n is the number of strings in the list and m is length of the shortest string + +space complexity : O(1) + +We start from first character of first string and compare it with all other strings, if no mismatch then add it to prefix string else return the prefix string diff --git a/leetcode/lc15/notes.md b/leetcode/lc15/notes.md new file mode 100644 index 0000000..cf6df6d --- /dev/null +++ b/leetcode/lc15/notes.md @@ -0,0 +1,7 @@ +The intuition in this problem is we first sort the entire list and then fix i on first index and j at i+1 and k at last index and then compute total ,if(total>0) then since it is sorted, we need to bring total down so we do k-- and if total<0 then j++ + +To avoid recomputations for same j, we do j++ until nums[j]!=nums[j-1] + +TC : o(nlogn) + o(n*n); SC : o(1) + + diff --git a/leetcode/lc15/threesome.cpp b/leetcode/lc15/threesome.cpp new file mode 100644 index 0000000..2616dbf --- /dev/null +++ b/leetcode/lc15/threesome.cpp @@ -0,0 +1,25 @@ +class Solution{ + public: + vector> ThreeSum(vector &nums){ + vector> res; + sort(nums.begin(), nums.end()); + int n = nums.size(); + for(int i =0;i0) break; + if(i>0 && nums[i]==nums[i-1]) continue; + int j = i+1; + int k = nums.size() -1; + while(j0) k--; + else if(total<0) j++; + else{ + res.push_back({nums[i], nums[j], nums[k]}); + j++; + while(j &nums, int target){ + sort(nums.begin(), nums.end()); + int n =nums.size(); + int res = nums[0] + nums[1] + nums[2]; + for(int i =0;i0 && nums[i]==nums[i-1]) break; + int left = i+1; + int right= n -1; + while(left> fourSum(vector& nums, int target) { + int n = nums.size(); + sort(nums.begin(), nums.end()); + set> set; + vector> output; + for(int i=0; i newTarget){ + high--; + } + else{ + set.insert({nums[i], nums[j], nums[low], nums[high]}); + low++; high--; + } + } + } + } + for(auto it : set){ + output.push_back(it); + } + return output; + } +}; + +//TC : O(n^3) +//SC : o(n) diff --git a/leetcode/lc18/brute4loop.cpp b/leetcode/lc18/brute4loop.cpp new file mode 100644 index 0000000..82e730d --- /dev/null +++ b/leetcode/lc18/brute4loop.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + vector> fourSum(vector& nums, int target) { + int n = nums.size(); + sort(nums.begin(), nums.end()); + set> set; + vector> output; + for(int i=0; i> foursum(vector &nums, int target){ + sort(begin(nums), end(nums)); + return ksum(nums, target, 0 ,4); + } + vector> ksum(vector &nums, long long target, int start, int k){ + vector> res; + if(start == nums.size()) return res; + long long avg = target/k; + if(nums[start] > avg || nums.back()> twosum(vector &nums, long long target, int start){ + vector> res; + unordered_set s; + for(int i = start; inext; + } + if(n==count) { + ListNode* newHead = head->next; + delete head; + return newHead; + } + temp = head; + for(int i = 1; i<(count-n);i++){ + temp = temp->next; + } + ListNode* nodeToDelete = temp->next; + temp->next = nodeToDelete->next; + delete nodeToDelete; + + return head; + +} +//n == count is when removal node is head +//count-n just goes to one node before the removal node diff --git a/leetcode/lc20/OptimalParantheses.cpp b/leetcode/lc20/OptimalParantheses.cpp new file mode 100644 index 0000000..998e454 --- /dev/null +++ b/leetcode/lc20/OptimalParantheses.cpp @@ -0,0 +1,18 @@ +class Solution{ + public: + bool isValid(string s){ + stack st; + for(char c : s){ + if(c=='(' || c == '{' || c == '[') st.push(c); + else{ + if(st.empty()) return false; + + char top = st.top(); + st.pop(); + + if((c==')' && top!='(') || (c == '}' && top!= '{') || (c == ']' && top!= '[')) return false; + } + } + return st.empty(); + } +}; diff --git a/leetcode/lc20/ValidParantheses1.cpp b/leetcode/lc20/ValidParantheses1.cpp new file mode 100644 index 0000000..b497880 --- /dev/null +++ b/leetcode/lc20/ValidParantheses1.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool isValid(string s) { + stack st; + unordered_map mapping = {{')','('}, {'}','{'}, {']','['}}; + for(char c: s){ + if(mapping.find(c) == mapping.end()) st.push(c); + else if(!st.empty() && mapping[c] == st.top()) st.pop(); + else return false; + + } + return st.empty(); + + + + } +}; diff --git a/leetcode/lc21/MergeLists.cpp b/leetcode/lc21/MergeLists.cpp new file mode 100644 index 0000000..4c04dfc --- /dev/null +++ b/leetcode/lc21/MergeLists.cpp @@ -0,0 +1,36 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + ListNode* dummy = new ListNode(0); + ListNode* cur = dummy; + + while(l1 && l2){ + if((l1->val) < (l2->val) ){ + cur->next = l1; + l1 = l1->next; + } + else{ + cur->next = l2; + l2 = l2->next; + } + cur = cur->next; + } + cur->next = l1? l1 : l2; + ListNode* head = dummy->next; + delete dummy; + return head; + + } +}; +// TC : O(m+n) +// SC : O(1) diff --git a/leetcode/lc21/RecursiveMerge.cpp b/leetcode/lc21/RecursiveMerge.cpp new file mode 100644 index 0000000..a9355b4 --- /dev/null +++ b/leetcode/lc21/RecursiveMerge.cpp @@ -0,0 +1,17 @@ +class Solution{ + public : + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2){ + if(!l1 || !l2) + return l1? l1: l2; + if(l1->val > l2->val) + swap(l1,l2); + l1->next = mergeTwoLists(l1->next, l2); + return l1; + + } +} + +//At every step, pick the smaller head node, attach it to the result,and recursively merge the remaining lists +//TC : O(m+n) +//SC: O(m+n), recursion stack space + diff --git a/leetcode/lc22/generateParantheses.cpp b/leetcode/lc22/generateParantheses.cpp new file mode 100644 index 0000000..3ac7e37 --- /dev/null +++ b/leetcode/lc22/generateParantheses.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector generateParenthesis(int n) { + vector res; + dfs(0,0, "", n,res); + return res; + } + void dfs(int openP, int closeP, string s, int n, vector & res){ + if(openP == closeP && openP+closeP == 2*n){ + res.push_back(s); + return; + } + + if(openP ans; + void helper(string s,int open,int close) { + if(open==0 && close==0) { + ans.push_back(s); + return; + } + if(open>0) { + s+='('; + helper(s,open-1,close); + s.pop_back(); + } + if(close>0) { + if(open generateParenthesis(int n) { + helper("",n,n); + return ans; + } +}; + +//This solution uses DFS with backtracking to generate all valid parentheses by exploring one complete construction path at a time. +//pop_back() is used to backtrack by removing the last added character, as string s is passed by reference, hence more optimal + +//TC : O(Cn), catalan number, The number of valid parentheses strings with n pairs is the n-th Catalan number. +//SC: O(n) diff --git a/leetcode/lc23/MergeKLists.cpp b/leetcode/lc23/MergeKLists.cpp new file mode 100644 index 0000000..026c683 --- /dev/null +++ b/leetcode/lc23/MergeKLists.cpp @@ -0,0 +1,34 @@ +class Solution{ + public : + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2){ + if(!l1 || !l2) return l1?l1:l2; + if(l1->val < l2->val){ + l1->next = mergeTwoLists(l1->next, l2); + return l1; + }else{ + l2->next = mergeTwoLists(l1,l2->next); + return l2; + } + } + + ListNode* mergeKLists(vector &lists){ + if(lists.empty()) return nullptr; + return divideAndConquer(lists, 0 , lists.size()-1); + } + ListNode* divideAndConquer(vector &lists, int left, int right){ + if(left == right) return lists[left]; + + int mid = left + (right-left)/2; + ListNode* l1 = divideAndConquer(lists, left, mid); + ListNode* l2 = divideAndConquer(lists, mid+1, right); + return mergeTwoLists(l1,l2); + } +}; + +//We recursively split the K lists into smaller groups, merge pairs of lists at the bottom, and keep merging upward until one sorted list remains. + +//TC: O(nlogk) , Each level merges all nodes once, Number of levels = log₂(k), naive merging takes O(nk) + + +//SC : O(logK) + diff --git a/leetcode/lc24/SwapNodes.cpp b/leetcode/lc24/SwapNodes.cpp new file mode 100644 index 0000000..4ca7fd1 --- /dev/null +++ b/leetcode/lc24/SwapNodes.cpp @@ -0,0 +1,30 @@ +class Solution{ + public: + ListNode* SwapNode(ListNode* head){ + if(!head || !head->next) return head; + + ListNode* dummy = new ListNode(0); + dummy->next = head; + + ListNode* cur = head; + ListNode* prev = dummy; + + while(cur && cur->next){ + ListNode* nextPair = cur->next->next; + ListNode* second = cur->next; + + second->next = cur; + cur->next = nextPair; + prev->next = second; + + prev = cur; + cur = nextPair; + } + ListNode* newHead = dummy->next; + delete dummy; + return newHead; + } +}; + +//TC : O(n) +//SC : O(1) diff --git a/leetcode/lc26.cpp b/leetcode/lc26.cpp new file mode 100644 index 0000000..769ddbb --- /dev/null +++ b/leetcode/lc26.cpp @@ -0,0 +1,25 @@ +class Solution{ + public: + int removeDuplicates(vector & nums){ + if(nums.empty()) return 0; + int i =1; + for(int j =1;j marks the position where the next unique element should be stored +j-> scans the array to find new elements +*/ diff --git a/leetcode/lc27.cpp b/leetcode/lc27.cpp new file mode 100644 index 0000000..1ef5ffb --- /dev/null +++ b/leetcode/lc27.cpp @@ -0,0 +1,14 @@ +class Solution{ + public: + int removeELement(vector& nums, int val){ + int k = 0; + for(int i = 0;i scans every element +// k-> stores only valid(!=val) elements diff --git a/leetcode/lc28/bruteForce.cpp b/leetcode/lc28/bruteForce.cpp new file mode 100644 index 0000000..c73c8c5 --- /dev/null +++ b/leetcode/lc28/bruteForce.cpp @@ -0,0 +1,15 @@ +class Solution{ + public: + int strStr(string haystack, string needle){ + if(needle.length() > haystack.length()) return -1; + for(int i =0;i <= haystack.length() - needle.length();i++){ + if(haystack.substr(i, needle.length()) == needle) + return i; + } + return -1; + } +}; + +// TC : O(n*m) +// SC : O(m) +// m-> needle.length(), n-> haystack.length() diff --git a/leetcode/lc28/spaceOptimized.cpp b/leetcode/lc28/spaceOptimized.cpp new file mode 100644 index 0000000..12e3b78 --- /dev/null +++ b/leetcode/lc28/spaceOptimized.cpp @@ -0,0 +1,11 @@ +class Solution{ + public : + int strStr(string haystack, string needle){ + if(needle.empty()) return 0; + int n = haystack.length(), m = needle.length(); + for(int i =0;i<=n-m; i++){ + + } + + } +} diff --git a/leetcode/lc29.cpp b/leetcode/lc29.cpp new file mode 100644 index 0000000..b7c8613 --- /dev/null +++ b/leetcode/lc29.cpp @@ -0,0 +1,28 @@ +class Solution{ + public: + int divide(int dividend, int divisor){ + if(divisor == 1) return dividend; + if(divisor == -1) return dividend == INT_MIN ? INT_MAX : -dividend; + + bool isPositive = (dividend > 0) == (divisor > 0); + + int a = dividend > 0? -dividend : dividend; + int b = divisor > 0? -divisor : divisor; + + int ans =0; + while(a<=b){ + int temp = b, multiple = 1; + while(temp>= INT_MIN>>1 && a< (temp<<1)){ + temp<<=1; + multiple <<= 1; + + } + a-= temp; + ans+=multiple; + } + return isPositive? ans: -ans; + + + } +}; +/*This solution performs integer division without using *, /, or % by simulating binary long division. To avoid overflow—especially the undefined behavior of abs(INT_MIN)—it first converts both the dividend and divisor into negative numbers, because the negative range of a 32-bit signed integer is larger and can safely represent INT_MIN. The only true overflow case (INT_MIN / -1) is handled upfront by returning INT_MAX. The algorithm then repeatedly subtracts the largest possible power-of-two multiple of the divisor from the dividend using safe left shifts guarded against overflow, accumulating the corresponding multiple in the quotient. This guarantees correctness for all edge cases, runs in O(log^2 n) time with O(1) space, and keeps all intermediate operations within valid integer bounds.*\ diff --git a/leetcode/lc3010/MinCostArray.cpp b/leetcode/lc3010/MinCostArray.cpp new file mode 100644 index 0000000..40756a9 --- /dev/null +++ b/leetcode/lc3010/MinCostArray.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int minimumCost(vector& nums) { + int min1 = 100, min2 = 100; + int n = nums.size(); + for(int i = 1;i& nums) { + int n = nums.size(), i = 1; + while (i < n && nums[i - 1] < nums[i]) { + i++; + } + int p = i - 1; + while (i < n && nums[i - 1] > nums[i]) { + i++; + } + int q = i - 1; + while (i < n && nums[i - 1] < nums[i]) { + i++; + } + int flag = i - 1; + return (p != 0) && (q != p) && (flag == n - 1 && flag != q); + } +}; + +// Uses single pointer, and checks for all 3 required segments one after one.a diff --git a/leetcode/lc3637/trionicArray.cpp b/leetcode/lc3637/trionicArray.cpp new file mode 100644 index 0000000..b846dfd --- /dev/null +++ b/leetcode/lc3637/trionicArray.cpp @@ -0,0 +1,20 @@ +class Solution { + public : + bool isTrionic(vector &nums){ + int n =nums.size(); + if(n<3) return false; + int p = 0; + int q = n-1; + while(p+1 =0 && nums[q] > nums[q-1]) q--; + if(p==0 || q==n-1) return false; + while(p+1<=q){ + if(nums[p] > nums[p+1]) p++; + else return false; + } + return p==q; + } +}; + +// Uses two pointers, TC : o(n) , SC : o(1) +// finds valid p and q if they exist, adn checks for strictly decreasing between p...q diff --git a/leetcode/lc3637/trionicSegmentCount.cpp b/leetcode/lc3637/trionicSegmentCount.cpp new file mode 100644 index 0000000..dd56eb6 --- /dev/null +++ b/leetcode/lc3637/trionicSegmentCount.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + bool isTrionic(vector& nums) { + int n = nums.size(); + if (nums[0] >= nums[1]) { + return false; + } + int count = 1; + for (int i = 2; i < n; i++) { + if (nums[i - 1] == nums[i]) { + return false; + } + if ((nums[i - 2] - nums[i - 1]) * (nums[i - 1] - nums[i]) < 0) { + count++; + } + } + return count == 3; + } +}; +// count denotes the number of monotonic segments and 3 elements are considered at a time, and checked for sign flip, if theres sign flip then segment has changed, starting from increasing segment, if count ==3 then it has three monotonic segments and hence return true diff --git a/leetcode/lc5/ExpandCentre.cpp b/leetcode/lc5/ExpandCentre.cpp index 723d445..79876f0 100644 --- a/leetcode/lc5/ExpandCentre.cpp +++ b/leetcode/lc5/ExpandCentre.cpp @@ -1,17 +1,18 @@ + class Solution { public: string longestPalindrome(string s) { if (s.length() <= 1) { return s; - } + } auto expand_from_center = [&](int left, int right) { while (left >= 0 && right < s.length() && s[left] == s[right]) { left--; right++; - } + } return s.substr(left + 1, right - left - 1); - }; + }; string max_str = s.substr(0, 1); @@ -28,5 +29,39 @@ public: } return max_str; - } -}; + } +}; + +class Solution { +public: + std::string longestPalindrome(std::string s) { + if (s.length() <= 1) { + return s; + } + + auto expand_from_center = [&](int left, int right) { + while (left >= 0 && right < s.length() && s[left] == s[right]) { + left--; + right++; + } + return s.substr(left + 1, right - left - 1); + }; + + std::string max_str = s.substr(0, 1); + + for (int i = 0; i < s.length() - 1; i++) { + std::string odd = expand_from_center(i, i); + std::string even = expand_from_center(i, i + 1); + + if (odd.length() > max_str.length()) { + max_str = odd; + } + if (even.length() > max_str.length()) { + max_str = even; + } + } + + return max_str; + } +}; +