diff --git a/.github/ISSUE_TEMPLATE/solution-contribution.yml b/.github/ISSUE_TEMPLATE/solution-contribution.yml new file mode 100644 index 0000000..3bc6285 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/solution-contribution.yml @@ -0,0 +1,89 @@ +name: "Solution Contribution (C++)" +description: "Submit a C++ solution for a LeetCode problem which already not exists in the repo." +title: "[Problem Number]: " +body: + - type: markdown + attributes: + value: | + Thank you for contributing a solution! Please fill out the details below. + + PR File Naming Convention: + - Your solution file must be named exactly as: `[Number]. [Problem Title].cpp` + - Example: `2785. Sort Vowels in a String.cpp` + + - type: input + id: problem_number + attributes: + label: Problem Number + description: Enter the LeetCode problem number. + placeholder: "2785" + validations: + required: true + + - type: input + id: problem_title + attributes: + label: Problem Title + description: Enter the exact LeetCode problem title. + placeholder: "Sort Vowels in a String" + validations: + required: true + + - type: input + id: leetcode_link + attributes: + label: LeetCode Link + description: Provide the link to the problem on LeetCode. + placeholder: "https://leetcode.com/problems/sort-vowels-in-a-string/" + validations: + required: true + + - type: checkboxes + id: contribution_checklist + attributes: + label: Contribution Checklist + options: + - label: I have written the Approach section. + required: true + - label: I have written the Intuition section. + required: true + - label: I have included a working C++ solution. + required: true + - label: I will raise a PR and ensure the filename follows the convention `[Number]. [Problem Title].cpp`. + required: true + + - type: textarea + id: approach + attributes: + label: Approach + description: Describe the algorithm, data structures used, and time/space complexity. + placeholder: "Explain step-by-step how your solution works and its complexity." + validations: + required: true + + - type: textarea + id: intuition + attributes: + label: Intuition + description: Explain the core idea behind your approach. + placeholder: "Why does this approach work? What insights led you to it?" + validations: + required: true + + - type: textarea + id: code + attributes: + label: Solution in C++ + description: Paste your C++ solution code. Ensure it compiles and passes sample tests. + render: cpp + placeholder: | + ```cpp + class Solution { + public: + // Your solution code here + }; + ``` + validations: + required: true + + diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..ef5a10a --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,31 @@ +**PR Title Format:** Problem no.Problem name.cpp + + +### Intuition + + + + +### Approach + + + + +## Code Solution (C++) + +```cpp + // Your code goes here + +``` + + +## Related Issues + + + + +**By submitting this PR, I confirm that:** +- [ ] This is my original work not totally AI generated +- [ ] I have tested the solution thoroughly on leetcode +- [ ] I have maintained proper PR description format +- [ ] This is a meaningful contribution, not spam \ No newline at end of file diff --git a/.github/workflows/pr-merged-automate-message.yml b/.github/workflows/pr-merged-automate-message.yml new file mode 100644 index 0000000..5afa9a8 --- /dev/null +++ b/.github/workflows/pr-merged-automate-message.yml @@ -0,0 +1,28 @@ +name: Auto Comment on PR Merged + +on: + pull_request_target: + types: [closed] + +permissions: + pull-requests: write + +jobs: + comment: + if: github.event.pull_request.merged == true + runs-on: ubuntu-latest + steps: + - name: Add Comment to Merged Pull Request + uses: actions/github-script@v6 + with: + script: | + const prNumber = context.issue.number; + const prAuthor = context.payload.pull_request.user.login; + const commentBody = `### 🎉 Congrats on getting your PR merged in, @${prAuthor}! 🙌🏼\n\nThanks for your contribution every effort helps improve the project.\n\nLooking forward to seeing more from you! 🥳✨`; + + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: prNumber, + body: commentBody + }); diff --git a/100. same Tree or Identical Tree b/100. same Tree or Identical Tree.cpp similarity index 100% rename from 100. same Tree or Identical Tree rename to 100. same Tree or Identical Tree.cpp diff --git a/101. Symetric Tree b/101. Symetric Tree.cpp similarity index 100% rename from 101. Symetric Tree rename to 101. Symetric Tree.cpp diff --git a/1019. Next Greater Node in Linked List b/1019. Next Greater Node in Linked List.cpp similarity index 100% rename from 1019. Next Greater Node in Linked List rename to 1019. Next Greater Node in Linked List.cpp diff --git a/102. Binary Tree level Order Traversal b/102. Binary Tree level Order Traversal.cpp similarity index 100% rename from 102. Binary Tree level Order Traversal rename to 102. Binary Tree level Order Traversal.cpp diff --git a/104. Maximum Depth of Binary Tree b/104. Maximum Depth of Binary Tree.cpp similarity index 100% rename from 104. Maximum Depth of Binary Tree rename to 104. Maximum Depth of Binary Tree.cpp diff --git a/1094.Car Pooling.cpp b/1094.Car Pooling.cpp new file mode 100644 index 0000000..ffec631 --- /dev/null +++ b/1094.Car Pooling.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + bool carPooling(vector>& trips, int capacity) { + vector> pickups; + priority_queue, vector>, greater>> drops; + pickups.reserve(trips.size()); + for (auto &t : trips){ + pickups.emplace_back(t[1], t[0]); + drops.push({t[2], t[0]}); + } + sort(pickups.begin(), pickups.end()); + int i = 0, curr = 0; + while (!drops.empty()){ + int nextDrop = drops.top().first; + while (i < (int)pickups.size() && pickups[i].first < nextDrop){ + curr += pickups[i].second; + if (curr > capacity) return false; + ++i; + } + curr -= drops.top().second; + drops.pop(); + } + while (i < (int)pickups.size()){ + curr += pickups[i].second; + if (curr > capacity) return false; + ++i; + } + return true; + } +}; diff --git a/11. Container With Most Water.cpp b/11. Container With Most Water.cpp new file mode 100644 index 0000000..4fb4b8f --- /dev/null +++ b/11. Container With Most Water.cpp @@ -0,0 +1,23 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxArea(vector& height) { + int maxWater = 0; + int lp = 0, rp = (int)height.size() - 1; + while (lp < rp) { + int width = rp - lp; + int ht = min(height[lp], height[rp]); + int currWater = width * ht; + maxWater = max(maxWater, currWater); + + // Move the pointer at the shorter line inward + if (height[lp] < height[rp]) ++lp; + else --rp; + } + return maxWater; + } +}; diff --git a/110. Blanced Binary Tree b/110. Blanced Binary Tree.cpp similarity index 100% rename from 110. Blanced Binary Tree rename to 110. Blanced Binary Tree.cpp diff --git a/1128.NumberOfEquivalentDominoPairs.cpp b/1128.NumberOfEquivalentDominoPairs.cpp new file mode 100644 index 0000000..0a08f1c --- /dev/null +++ b/1128.NumberOfEquivalentDominoPairs.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int numEquivDominoPairs(vector>& dominoes) { + unordered_map count; + int res = 0; + + for (auto &d : dominoes) { + int a = d[0], b = d[1]; + int key = min(a, b) * 10 + max(a, b); + + res += count[key]; + count[key]++; + } + + return res; + } +}; diff --git a/113. Path Sum 2 b/113. Path Sum 2.cpp similarity index 100% rename from 113. Path Sum 2 rename to 113. Path Sum 2.cpp diff --git a/114. Flatten Binary Tree to Linked List b/114. Flatten Binary Tree to Linked List.cpp similarity index 100% rename from 114. Flatten Binary Tree to Linked List rename to 114. Flatten Binary Tree to Linked List.cpp diff --git a/118. Pascal Triangle b/118. Pascal Triangle.cpp similarity index 100% rename from 118. Pascal Triangle rename to 118. Pascal Triangle.cpp diff --git a/123. Best time to buy or sell stock iii .cpp b/123. Best time to buy or sell stock iii .cpp new file mode 100644 index 0000000..21027dd --- /dev/null +++ b/123. Best time to buy or sell stock iii .cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int maxProfit(vector& a) { + int n = a.size(); + vector>> dp(n+1, vector>(2, vector(3, 0))); + for(int i=n-1;i>=0;i--) + { + for(int buy=1;buy>=0;buy--) + { + for(int cap=1;cap<=2;cap++) + { + if (buy) { + // Either buy now, or skip + dp[i][buy][cap] = max(-a[i] + dp[i+1][0][cap],dp[i+1][1][cap]); + } else { + // Either sell now, or skip + dp[i][buy][cap] = max(a[i] +dp[i+1][1][cap-1], dp[i+1][0][cap]); + } + } + } + } + return dp[0][1][2]; + } +}; \ No newline at end of file diff --git a/134. Gas Station b/134. Gas Station.cpp similarity index 100% rename from 134. Gas Station rename to 134. Gas Station.cpp diff --git a/135. Candy.cpp b/135. Candy.cpp new file mode 100644 index 0000000..f276999 --- /dev/null +++ b/135. Candy.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int candy(vector& ratings) { + int n = ratings.size(); + vector count(n, 1); // Step 1: Initialize with 1 + + // Step 2: Left to Right + for (int i = 1; i < n; i++) { + if (ratings[i] > ratings[i - 1]) { + count[i] = count[i - 1] + 1; + } + } + + // Step 3: Right to Left + for (int i = n - 2; i >= 0; i--) { + if (ratings[i] > ratings[i + 1]) { + count[i] = max(count[i], count[i + 1] + 1); + } + } + + // Step 4: Total candies + return accumulate(count.begin(), count.end(), 0); + } +}; diff --git a/138. Copy List with random pointer b/138. Copy List with random pointer.cpp similarity index 100% rename from 138. Copy List with random pointer rename to 138. Copy List with random pointer.cpp diff --git a/FloydCycle.cpp b/141. FloydCycle.cpp similarity index 100% rename from FloydCycle.cpp rename to 141. FloydCycle.cpp diff --git a/145. Binary tree PostOrder Traversal b/145. Binary tree PostOrder Traversal.cpp similarity index 100% rename from 145. Binary tree PostOrder Traversal rename to 145. Binary tree PostOrder Traversal.cpp diff --git a/15. 3Sum b/15. 3Sum.cpp similarity index 100% rename from 15. 3Sum rename to 15. 3Sum.cpp diff --git a/1512. Number of Good Pairs b/1512. Number of Good Pairs.cpp similarity index 100% rename from 1512. Number of Good Pairs rename to 1512. Number of Good Pairs.cpp diff --git a/152. Maximum-Product-Subarray.cpp b/152. Maximum-Product-Subarray.cpp new file mode 100644 index 0000000..41e13cb --- /dev/null +++ b/152. Maximum-Product-Subarray.cpp @@ -0,0 +1,26 @@ +// 152. Maximum Product Subarray +// By Traversing in Both Directions +// Time Complexity - O(n) and Space Complexity - O(1) +class Solution { +public: + int maxProduct(vector& nums) { + int n = nums.size(); + int maxi = INT_MIN; + int ltr = 1, rtl = 1; + for(int i=0; i +#include +#include +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + int largestPathValue(string colors, vector>& edges) { + int n=colors.size(); + vector> graph(n); + vector indegree(n, 0); + + + for (auto &e:edges) { + graph[e[0]].push_back(e[1]); + indegree[e[1]]++; + } + + + queue q; + for (int i=0;i> count(n,vector(26, 0)); + int vis=0; + int ans=0; + + while (!q.empty()) { + int u=q.front(); + q.pop(); + vis++; + + + int colorIdx=colors[u]-'a'; + count[u][colorIdx]++; + ans=max(ans,count[u][colorIdx]); + + for(int v:graph[u]) { + for(int c=0;c<26;c++) + count[v][c] = max(count[v][c],count[u][c]); + if(--indegree[v]==0) + q.push(v); + } + } + + return (vis==n)?ans:-1; + } +}; diff --git a/191. Number of 1 Bits b/191. Number of 1 Bits.cpp similarity index 100% rename from 191. Number of 1 Bits rename to 191. Number of 1 Bits.cpp diff --git a/1920. Build Array from Permutation.cpp b/1920. Build Array from Permutation.cpp new file mode 100644 index 0000000..8b99463 --- /dev/null +++ b/1920. Build Array from Permutation.cpp @@ -0,0 +1,39 @@ +// ---------------- Approach ---------------- +// +// - We are directly asked to create a new array `ans` such that: +// ans[i] = nums[nums[i]] +// - Since nums is guaranteed to be a valid permutation (all elements in [0..n-1] without duplicates), +// the indexing nums[nums[i]] is always valid. +// - Just iterate through `nums` and build `ans`. +// +// Time Complexity: O(n) +// Space Complexity: O(n) for the output array + + +// ---------------- Intuition ---------------- +// +// The problem is a straightforward application of indexing. +// Each element at position i is mapped to the value at nums[i], +// and then we fetch nums[nums[i]]. +// +// Example: nums = [0,2,1,5,3,4] +// ans[0] = nums[nums[0]] = nums[0] = 0 +// ans[1] = nums[nums[1]] = nums[2] = 1 +// ans[2] = nums[nums[2]] = nums[1] = 2 +// ... +// Result: ans = [0,1,2,4,5,3] + + +// ---------------- Solution in Code ---------------- + +class Solution { +public: + vector buildArray(vector& nums) { + int n = nums.size(); + vector ans(n); + for (int i = 0; i < n; i++) { + ans[i] = nums[nums[i]]; + } + return ans; + } +}; diff --git a/199. Binary Tree Right Side View.cpp b/199. Binary Tree Right Side View.cpp new file mode 100644 index 0000000..6a4c034 --- /dev/null +++ b/199. Binary Tree Right Side View.cpp @@ -0,0 +1,32 @@ +/** + * 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 rightSideView(TreeNode* root) { + // unordered_mapmap; + vectorans; + int level=-1; + traverseRightSide(root,level,0,ans); + return ans; + } + void traverseRightSide(TreeNode* root,int &mainLevel,int level, vector&ans){ + if(root==NULL) return ; + + if(mainLevelval); + mainLevel=max(mainLevel,level); + } + + traverseRightSide(root->right,mainLevel,level+1,ans); + traverseRightSide(root->left,mainLevel,level+1,ans); + } +}; diff --git a/20. Valid Parentheses.cpp b/20. Valid Parentheses.cpp new file mode 100644 index 0000000..c5b2c9d --- /dev/null +++ b/20. Valid Parentheses.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + bool isValid(string s) { + stack stk; + for (char chr : s) { + if (chr == '(' || chr == '[' || chr == '{') { //open bracket being pushed to the stack if found + stk.push(chr); + } + else { + + //checking for empty stack before popping or comparison + if (stk.empty()) { + return false; + } + + //getting most recent open bracket and popping for the comparison + char top = stk.top(); + stk.pop(); + + // Verify the closing bracket 'chr' matches the popped open bracket 'top'... + if (chr == ')' && top != '(') { + return false; + } + if (chr == ']' && top != '[') { + return false; + } + if (chr == '}' && top != '{') { + return false; + } + } + } + return stk.empty(); + } +}; \ No newline at end of file diff --git a/2058. Find min and max number between critical Point b/2058. Find min and max number between critical Point.cpp similarity index 100% rename from 2058. Find min and max number between critical Point rename to 2058. Find min and max number between critical Point.cpp diff --git a/206.Course Schedule.cpp b/206.Course Schedule.cpp new file mode 100644 index 0000000..3497589 --- /dev/null +++ b/206.Course Schedule.cpp @@ -0,0 +1,67 @@ +// 🧠 Approach + +// This problem can be modeled as a Directed Graph Cycle Detection problem. +// Each course is represented as a node, and a directed edge b → a means you must take course b before course a. + +// To determine if all courses can be finished, we must ensure no cycle exists in this graph. +// We use Kahn’s Algorithm (Topological Sorting using BFS) to detect cycles. + +// 🚀 Algorithm Steps + +// Build the Graph: + +// - Create an adjacency list adj where adj[b] contains all courses that depend on b. +// - Maintain an array inDeg to store the number of prerequisites (incoming edges) for each course. + +// Find Starting Nodes: + +// - Push all nodes with inDeg[i] == 0 (no prerequisites) into a queue — these can be taken first. +// - Topological Sorting using BFS: +// - While the queue isn’t empty: +// - Pop a node x (a course that can be completed now). +// - Increment a counter c for completed courses. +// - For each neighbor adj[x][i], reduce its inDeg by 1 (as its prerequisite x is now done). +// - If any neighbor’s inDeg becomes 0, push it into the queue. + +// Check Completion: + +// - If all courses are processed (c == V), return true. +// - Otherwise, there’s a cycle → some courses depend on each other, so return false. + + +// Solution in CPP: + +class Solution { +public: + bool canFinish(int V, vector>& prerequisites) { + vector> adj(V); + vector inDeg(V); + for (int i = 0; i < prerequisites.size(); i++) { + int a = prerequisites[i][0]; + int b = prerequisites[i][1]; + + adj[b].push_back(a); + inDeg[a]++; + } + vector vis(V); + queue q; + + for (int i = 0; i < V; i++) { + if (inDeg[i] == 0) + q.push(i); + } + int c = 0; + while (!q.empty()) { + int x = q.front(); + q.pop(); + c++; + + for (int i = 0; i < adj[x].size(); i++) { + inDeg[adj[x][i]]--; + if (inDeg[adj[x][i]] == 0) + q.push(adj[x][i]); + } + } + return c == V; + } +}; \ No newline at end of file diff --git a/2071. Maximum Number of Tasks You Can Assign.cpp b/2071. Maximum Number of Tasks You Can Assign.cpp new file mode 100644 index 0000000..50fc665 --- /dev/null +++ b/2071. Maximum Number of Tasks You Can Assign.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + bool check(vector& tasks, vector& workers, int pills, int strength, int mid) { + int pillsUsed = 0; + multiset st(begin(workers), begin(workers) + mid); //best mid workers + + for(int i = mid-1; i >= 0; i--) { + int reqrd = tasks[i]; + auto it = prev(st.end()); + + if(*it >= reqrd) { + st.erase(it); + } else if(pillsUsed >= pills) { + return false; + } else { + //find the weakest worker which can do this strong task using pills + auto weakestWorkerIt = st.lower_bound(reqrd - strength); + if(weakestWorkerIt == st.end()) { + return false; + } + st.erase(weakestWorkerIt); + pillsUsed++; + } + } + + return true; + } + int maxTaskAssign(vector& tasks, vector& workers, int pills, int strength) { + int m = tasks.size(); + int n = workers.size(); + + int l = 0; + int r = min(m, n); + + sort(begin(tasks), end(tasks)); + sort(begin(workers), end(workers), greater()); + + int result = 0; + + while(l <= r) { + int mid = l + (r-l)/2; + + if(check(tasks, workers, pills, strength, mid)) { + result = mid; + l = mid+1; + } else { + r = mid-1; + } + } + + return result; + + + } +}; diff --git a/2109. Adding Spaces to a String b/2109. Adding Spaces to a String.cpp similarity index 100% rename from 2109. Adding Spaces to a String rename to 2109. Adding Spaces to a String.cpp diff --git a/2181. Merge Nodes between two Zeros b/2181. Merge Nodes between two Zeros.cpp similarity index 100% rename from 2181. Merge Nodes between two Zeros rename to 2181. Merge Nodes between two Zeros.cpp diff --git a/219.NearbyDuplicate.cpp b/219.NearbyDuplicate.cpp new file mode 100644 index 0000000..22e8fb5 --- /dev/null +++ b/219.NearbyDuplicate.cpp @@ -0,0 +1,24 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool containsNearbyDuplicate(vector& nums, int k) { + int n=nums.size(); + unordered_map indexmap; + + for(int i=0;i removeAnagrams(vector &words) + { + if (words.size() == 1) + return {words[0]}; + vector ans; + ans.push_back(words[0]); + for (int i = 1; i < words.size(); i++) + { + string tempcurr = words[i]; + string prevtemp = words[i - 1]; + sort(tempcurr.begin(), tempcurr.end()); + sort(prevtemp.begin(), prevtemp.end()); + if (tempcurr != prevtemp) + { + ans.push_back(words[i]); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/23. Merge k Sorted Lists.cpp b/23. Merge k Sorted Lists.cpp new file mode 100644 index 0000000..ef13afa --- /dev/null +++ b/23. Merge k Sorted Lists.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* mergeKLists(vector& lists) { + ListNode* res = new ListNode(0); + ListNode* temp = res; + + priority_queue, greater> minHeap; + + for (auto l : lists) { + while (l != nullptr) { + minHeap.push(l->val); + l = l->next; + } + } + + while (!minHeap.empty()) { + int num = minHeap.top(); + minHeap.pop(); + + temp->next = new ListNode(num); + temp = temp->next; + } + + return res->next; + } +}; \ No newline at end of file diff --git a/230. Kth Smallest Element b/230. Kth Smallest Element.cpp similarity index 100% rename from 230. Kth Smallest Element rename to 230. Kth Smallest Element.cpp diff --git a/231. Power of Two.cpp b/231. Power of Two.cpp new file mode 100644 index 0000000..4bdd369 --- /dev/null +++ b/231. Power of Two.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + bool isPowerOfTwo(int n) { + if (n <= 0) return false; + return (n & (n - 1)) == 0; + } +}; diff --git a/232.Implement Queue using Stacks b/232.Implement Queue using Stacks.cpp similarity index 100% rename from 232.Implement Queue using Stacks rename to 232.Implement Queue using Stacks.cpp diff --git a/235. Lowest Common Ancestor of a Binary Search Tree b/235. Lowest Common Ancestor of a Binary Search Tree.cpp similarity index 100% rename from 235. Lowest Common Ancestor of a Binary Search Tree rename to 235. Lowest Common Ancestor of a Binary Search Tree.cpp diff --git a/236. lowest Common Ancestor of A Binary tree b/236. lowest Common Ancestor of A Binary tree.cpp similarity index 100% rename from 236. lowest Common Ancestor of A Binary tree rename to 236. lowest Common Ancestor of A Binary tree.cpp diff --git a/239. Sliding Window Maximum b/239. Sliding Window Maximum.cpp similarity index 100% rename from 239. Sliding Window Maximum rename to 239. Sliding Window Maximum.cpp diff --git a/242. Valid Anagram.cpp b/242. Valid Anagram.cpp new file mode 100644 index 0000000..a7a28b8 --- /dev/null +++ b/242. Valid Anagram.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + bool isAnagram(string s, string t) { + if(s.length() != t.length()) return false; + + int count[26] = {0}; + + for(int i = 0; i < s.length(); i++) { + count[s[i]-'a']++; + count[t[i]-'a']--; + } + + for(int i = 0; i < 26; i++) { + if(count[i] != 0) return false; + } + + return true; + } +}; diff --git a/2561. Rearranging Fruits.cpp b/2561. Rearranging Fruits.cpp new file mode 100644 index 0000000..019298e --- /dev/null +++ b/2561. Rearranging Fruits.cpp @@ -0,0 +1,31 @@ + + +class Solution { +public: + long long minCost(vector& basket1, vector& basket2) { + unordered_map freq; + for (int x : basket1) freq[x]++; + for (int x : basket2) freq[x]--; + + vector extra1, extra2; + int minFruit = INT_MAX; + + // Collect unbalanced fruits + for (auto [fruit, diff] : freq) { + minFruit = min(minFruit, fruit); + if (diff % 2 != 0) return -1; // impossible to balance + int count = abs(diff) / 2; + if (diff > 0) while (count--) extra1.push_back(fruit); + else while (count--) extra2.push_back(fruit); + } + + sort(extra1.begin(), extra1.end()); + sort(extra2.rbegin(), extra2.rend()); + + long long cost = 0; + for (int i = 0; i < extra1.size(); ++i) { + cost += min((long long)min(extra1[i], extra2[i]), 2LL * minFruit); + } + return cost; + } +}; diff --git a/26. Remove Duplicates from Sorted Array.cpp b/26. Remove Duplicates from Sorted Array.cpp new file mode 100644 index 0000000..db7f30d --- /dev/null +++ b/26. Remove Duplicates from Sorted Array.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int removeDuplicates(vector& nums) { + if (nums.empty()) return 0; + int j = 0; + for (int i = 1; i < nums.size(); i++) { + if (nums[i] != nums[j]) { + j++; + nums[j] = nums[i]; + } + } + return j + 1; + } +}; diff --git a/283. Move Zeroes.cpp b/283. Move Zeroes.cpp new file mode 100644 index 0000000..f10822c --- /dev/null +++ b/283. Move Zeroes.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + void moveZeroes(vector& nums) { + int j = 0; + for(int i = 0; i < nums.size(); i++) { + if(nums[i] != 0) nums[j++] = nums[i]; + } + while(j < nums.size()) nums[j++] = 0; + } +}; diff --git a/287. Find The Duplicate number b/287. Find The Duplicate number.cpp similarity index 100% rename from 287. Find The Duplicate number rename to 287. Find The Duplicate number.cpp diff --git a/2894. Divisible and Non-Divisible SumDifferences.cpp b/2894. Divisible and Non-Divisible SumDifferences.cpp new file mode 100644 index 0000000..050a2c0 --- /dev/null +++ b/2894. Divisible and Non-Divisible SumDifferences.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int differenceOfSums(int n, int m) { + int ans=0; + for(int i=1;i<=n;i++){ + if(i%m==0) ans-=i; + else ans+=i; + + } + return ans; + } +}; \ No newline at end of file diff --git a/2894. Divisible and Non-divisible Sums Difference.cpp b/2894. Divisible and Non-divisible Sums Difference.cpp new file mode 100644 index 0000000..9f55912 --- /dev/null +++ b/2894. Divisible and Non-divisible Sums Difference.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int differenceOfSums(int n, int m) { + int num1 = 0, num2 = 0; + for (int i = 1; i <= n; i++) { + if (i % m == 0) + num2 += i; // divisible by m + else + num1 += i; // not divisible by m + } + return num1 - num2; + } +}; diff --git a/292.NimGame.cpp b/292.NimGame.cpp new file mode 100644 index 0000000..b767b69 --- /dev/null +++ b/292.NimGame.cpp @@ -0,0 +1,12 @@ +// Includes Soln to 292. Nim Game Problem +// Using trial and error it can be found that you can win the game for any n less than 4 or if n is not divisible by 4 +// This code uses the simple observation to solve the problem + + +class Solution { +public: + bool canWinNim(int n) { + if (n<=3 || n%4!=0) return true; + return false; + } +}; \ No newline at end of file diff --git a/2942. Find Words Containing Character.cpp b/2942. Find Words Containing Character.cpp new file mode 100644 index 0000000..5c17cab --- /dev/null +++ b/2942. Find Words Containing Character.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector findWordsContaining(vector& words, char x) { + vector ans; + for(int i=0;i dp; + ll solve(ll i, ll mask, ll change, int k, string& s) { + + int n = s.size(); + if (i == n) { + return 1; + } + + ll currState = (i << 27) | (mask << 1) | (change); + + if (dp.find(currState) != dp.end()) { + return dp[currState]; + } + + int val = s[i] - 'a'; + ll newMask = mask | (1 << val); + + int count = __builtin_popcount(newMask); + + ll ans = 0; + ll maxi = 0; + + if (count > k) { + ans = 1 + solve(i + 1, 1 << val, change, k, s); + maxi = max(maxi, ans); + } else { + ans = solve(i + 1, newMask, change, k, s); + maxi = max(maxi, ans); + } + + if (change) { + return dp[currState] = maxi; + } + + for (int j = 0; j < 26; j++) { + + ll newMask = mask | (1 << j); + ll count = __builtin_popcount(newMask); + + if (count > k) { + maxi = max(maxi, 1 + solve(i + 1, 1 << j, 1, k, s)); + } else { + maxi = max(maxi, solve(i + 1, newMask, 1, k, s)); + } + } + + return dp[currState] = maxi; + } + int maxPartitionsAfterOperations(string s, int k) { + return solve(0, 0, 0, k, s); + } +}; diff --git a/3024.Type of Triangle.cpp b/3024.Type of Triangle.cpp new file mode 100644 index 0000000..7f00b43 --- /dev/null +++ b/3024.Type of Triangle.cpp @@ -0,0 +1,27 @@ +/* APPROACH +The solution involves two key steps: triangle validity checking and triangle classification. First, verify if the three sides can form a valid triangle using the triangle inequality theorem, then classify the triangle type based on side equality patterns + +Intuition +For three sides to form a valid triangle, they must satisfy the triangle inequality theorem: the sum of any two sides must be greater than the third side. This gives us three conditions to check: a + b > c, b + c > a, and c + a > b +*/ +class Solution { +public: + string triangleType(vector& nums) { + int a = nums[0], b = nums[1], c = nums[2]; + + // Check triangle inequality theorem + if (a + b <= c || b + c <= a || c + a <= b) { + return "none"; + } + + // Check triangle type based on side equality + if (a == b && b == c) { + return "equilateral"; + } else if (a == b || b == c || a == c) { + return "isosceles"; + } else { + return "scalene"; + } + } +}; + diff --git a/3068. Find the Maximum Sum of Node Values.cpp b/3068. Find the Maximum Sum of Node Values.cpp new file mode 100644 index 0000000..b91d489 --- /dev/null +++ b/3068. Find the Maximum Sum of Node Values.cpp @@ -0,0 +1,65 @@ +#include +using namespace std; + +// Definition for a binary tree node +struct Node { + int data; + Node* left; + Node* right; + Node(int val) { + data = val; + left = right = nullptr; + } +}; + +class Solution { + int maxSum; // Global maximum sum + // Helper function to compute maximum gain from a node + int findMaxPath(Node* root) { + if (!root) return 0; + + int leftGain = max(0, findMaxPath(root->left)); // Max path sum from left + int rightGain = max(0, findMaxPath(root->right)); // Max path sum from right + + // Update global maximum including current node + maxSum = max(maxSum, leftGain + rightGain + root->data); + + // Return max gain including current node for recursion + return root->data + max(leftGain, rightGain); + } + +public: + int maxPathSum(Node* root) { + maxSum = INT_MIN; + findMaxPath(root); + return maxSum; + } +}; + +// Example usage +int main() { + /* + 10 + / \ + 2 10 + / \ \ + 20 1 -25 + / \ + 3 4 + Expected Output: 42 (20 + 2 + 10 + 10) + */ + + Node* root = new Node(10); + root->left = new Node(2); + root->right = new Node(10); + root->left->left = new Node(20); + root->left->right = new Node(1); + root->right->right = new Node(-25); + root->right->right->left = new Node(3); + root->right->right->right = new Node(4); + + Solution sol; + cout << "Maximum Path Sum: " << sol.maxPathSum(root) << endl; + + return 0; +} diff --git a/3147.Taking Maximum Energy From the Mystic Dungeon.cpp b/3147.Taking Maximum Energy From the Mystic Dungeon.cpp new file mode 100644 index 0000000..8bb1a73 --- /dev/null +++ b/3147.Taking Maximum Energy From the Mystic Dungeon.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; + +class Solution { +public: + int maximumEnergy(vector& energy, int k) { + int n = energy.size(); + vector dp(n, 0); + int ans = INT_MIN; + + for (int i = n - 1; i >= 0; i--) { + dp[i] = energy[i]; + if (i + k < n) + dp[i] += dp[i + k]; + ans = max(ans, dp[i]); + } + + return ans; + } +}; diff --git a/32. Longest Valid Parentheses b/32. Longest Valid Parentheses.cpp similarity index 100% rename from 32. Longest Valid Parentheses rename to 32. Longest Valid Parentheses.cpp diff --git a/3208.Alternating Groups II.cpp b/3208.Alternating Groups II.cpp new file mode 100644 index 0000000..94bf78d --- /dev/null +++ b/3208.Alternating Groups II.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int numberOfAlternatingGroups(vector& colors, int k) { + int n = colors.size(); + vector arr(2 * n); + copy(colors.begin(), colors.end(), arr.begin()); + copy(colors.begin(), colors.end(), arr.begin() + n); + int l = 0, r = 1, flag = colors[0], count = 0; + while (r < arr.size() && l < n) { + if (arr[r] == flag) l = r; + else flag = arr[r]; + if ((r - l + 1) == k) { + count++; + l++; + } + r++; + } + return count; + } +}; diff --git a/3297. Count Substrings That Can Be Rearranged to Contain a String I.cpp b/3297. Count Substrings That Can Be Rearranged to Contain a String I.cpp new file mode 100644 index 0000000..42bcd5e --- /dev/null +++ b/3297. Count Substrings That Can Be Rearranged to Contain a String I.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + long long validSubstringCount(string word1, string word2) { + int count = 0; + long long ans = 0; + int l = 0, r = 0; + vector map2(27, 0), map1(27, 0); + for (int i = 0; i < word2.size(); i++) { + map2[word2[i] - 'a']++; + } + while (r < word1.size()) { + map1[word1[r] - 'a']++; + if (map1[word1[r] - 'a'] == map2[word1[r] - 'a']) + count += map2[word1[r] - 'a']; + while (count == word2.size()) { + ans += (word1.size() - r); + map1[word1[l] - 'a']--; + if (map1[word1[l] - 'a'] < map2[word1[l] - 'a']) + count -= map2[word1[l] - 'a']; + l++; + } + r++; + } + return ans; + } +}; diff --git a/3298. Count Substrings That Can Be Rearranged to Contain a String II.cpp b/3298. Count Substrings That Can Be Rearranged to Contain a String II.cpp new file mode 100644 index 0000000..42bcd5e --- /dev/null +++ b/3298. Count Substrings That Can Be Rearranged to Contain a String II.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + long long validSubstringCount(string word1, string word2) { + int count = 0; + long long ans = 0; + int l = 0, r = 0; + vector map2(27, 0), map1(27, 0); + for (int i = 0; i < word2.size(); i++) { + map2[word2[i] - 'a']++; + } + while (r < word1.size()) { + map1[word1[r] - 'a']++; + if (map1[word1[r] - 'a'] == map2[word1[r] - 'a']) + count += map2[word1[r] - 'a']; + while (count == word2.size()) { + ans += (word1.size() - r); + map1[word1[l] - 'a']--; + if (map1[word1[l] - 'a'] < map2[word1[l] - 'a']) + count -= map2[word1[l] - 'a']; + l++; + } + r++; + } + return ans; + } +}; diff --git a/3341. Find Minimum Time to Reach Last Room I.cpp b/3341. Find Minimum Time to Reach Last Room I.cpp new file mode 100644 index 0000000..21f5536 --- /dev/null +++ b/3341. Find Minimum Time to Reach Last Room I.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + struct Node { + int r, c, t; + }; + + struct Cmp { + bool operator()(const Node &a, const Node &b) const { + return a.t > b.t; + } + }; + + int minTimeToReach(vector>& moveTime) { + int n = moveTime.size(); + int m = moveTime[0].size(); + const int INF = INT_MAX / 2; + vector> dist(n, vector(m, INF)); + priority_queue, Cmp> pq; + dist[0][0] = 0; + pq.push({0, 0, 0}); + int dr[4] = {1, -1, 0, 0}; + int dc[4] = {0, 0, 1, -1}; + + while (!pq.empty()) { + Node cur = pq.top(); + pq.pop(); + if (cur.t > dist[cur.r][cur.c]) continue; + if (cur.r == n - 1 && cur.c == m - 1) return cur.t; + + for (int i = 0; i < 4; i++) { + int nr = cur.r + dr[i]; + int nc = cur.c + dc[i]; + if (nr < 0 || nr >= n || nc < 0 || nc >= m) continue; + int arrival = max(moveTime[nr][nc], cur.t) + 1; + if (arrival < dist[nr][nc]) { + dist[nr][nc] = arrival; + pq.push({nr, nc, arrival}); + } + } + } + + return -1; + } +}; diff --git a/3342. Find Minimum Time to Reach Last Room II.cpp b/3342. Find Minimum Time to Reach Last Room II.cpp new file mode 100644 index 0000000..28b1c89 --- /dev/null +++ b/3342. Find Minimum Time to Reach Last Room II.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + vector dir = {0, 1, 0, -1, 0}; + + bool isValid(int x, int y, int r, int c) { + return (x >= 0 && x < r && y >= 0 && y < c); + } + + int minTimeToReach(vector>& moveTime) { + int r = moveTime.size(), c = moveTime[0].size(); + + vector> mn(r, vector(c, INT_MAX)); + vector> vis(r, vector(c, false)); + + using T = tuple; // t, x, y, idx + priority_queue, greater> pq; + + pq.push({0, 0, 0, 0}); + mn[0][0] = 0; + + while (!pq.empty()) { + auto [t, x, y, idx] = pq.top(); pq.pop(); + if (vis[x][y]) continue; + vis[x][y] = true; + + for (int i = 0; i < 4; i++) { + int nx = x + dir[i]; + int ny = y + dir[i + 1]; + if (!isValid(nx, ny, r, c)) continue; + + int nt = max(mn[x][y], moveTime[nx][ny]) + (idx % 2 == 0 ? 1 : 2); + if (nt < mn[nx][ny]) { + mn[nx][ny] = nt; + pq.push({nt, nx, ny, idx + 1}); + } + } + } + + return mn[r - 1][c - 1]; + } +}; diff --git a/3350. Adjacent Increasing Subarrays Detection II.cpp b/3350. Adjacent Increasing Subarrays Detection II.cpp new file mode 100644 index 0000000..2b43486 --- /dev/null +++ b/3350. Adjacent Increasing Subarrays Detection II.cpp @@ -0,0 +1,55 @@ +#include +using namespace std; +/* +APPROACH: +Use an array to track lengths of increasing streaks, then apply binary search +to find the largest k for which two adjacent increasing subarrays exist. +*/ +bool check(int *inc, int n, int k) +{ + for (int end1 = k - 1; end1 + k < n; end1++) + { + if (inc[end1] >= k && inc[end1 + k] >= k) + { + return true; + } + } + return false; +} + +int maxIncreasingSubarrays(int *nums, int numsSize) +{ + int n = numsSize; + int inc[n]; + for (int i = 0; i < n; i++) + inc[i] = 1; + + // Build the increasing streak lengths + for (int i = 1; i < n; i++) + { + if (nums[i] > nums[i - 1]) + { + inc[i] = inc[i - 1] + 1; + } + } + + int L = 1, R = n / 2; + int ans = 0; + + // Binary search for max k + while (L <= R) + { + int mid = L + (R - L) / 2; + if (check(inc, n, mid)) + { + ans = mid; // mid works, try bigger k + L = mid + 1; + } + else + { + R = mid - 1; // mid too big, try smaller k + } + } + + return ans; +} diff --git a/3355. Zero Array Transformation I.cpp b/3355. Zero Array Transformation I.cpp new file mode 100644 index 0000000..49ea254 --- /dev/null +++ b/3355. Zero Array Transformation I.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; + +class Solution { +public: + bool isZeroArray(vector& nums, vector>& queries) { + int n = nums.size(); + vector diff(n + 1, 0); + + for(const auto& q : queries){ + int l = q[0], r = q[1]; + diff[l] += 1; + if(r + 1 < n){ + diff[r + 1] -= 1; + } + } + + int coverage = 0; + for(int i = 0; i < n; ++i){ + coverage += diff[i]; + if(nums[i] > coverage){ + return false; + } + } + return true; + } +}; diff --git a/3362. Zero Array Transformation III.cpp b/3362. Zero Array Transformation III.cpp new file mode 100644 index 0000000..26e0d3a --- /dev/null +++ b/3362. Zero Array Transformation III.cpp @@ -0,0 +1,56 @@ +```cpp +// Problem: 3362. Zero Array Transformation III + +// Approach: +// Intuition: +// The problem asks us to transform an array of non-negative integers into an array of all zeros using a specific operation. The operation involves choosing an index `i` and a non-negative integer `x`, then subtracting `x` from `nums[i]` and `nums[i+1]`. We want to find the minimum total sum of `x` values used. + +// Let's analyze the operation. When we subtract `x` from `nums[i]` and `nums[i+1]`, it means `nums[i]` and `nums[i+1]` are reduced by the same amount. This suggests a greedy approach from left to right. + +// Consider `nums[0]`. To make `nums[0]` zero, we must apply an operation at index `0` with `x = nums[0]`. This will also affect `nums[1]`. After this operation, `nums[0]` becomes zero. We then move to `nums[1]` (which has been modified) and repeat the process. + +// Let's try a direct greedy approach. Iterate from `i = 0` to `n-1`. +// For each `nums[i]`, if `nums[i]` is not zero, we must perform an operation at index `i` to make it zero. The value of `x` for this operation must be `nums[i]` itself. This operation will also subtract `nums[i]` from `nums[i+1]` (if `i+1 < n`). +// We add `nums[i]` to our total operations count. + +// Example: +// nums = [1, 2, 3] + +// i = 0: nums[0] = 1. We need to subtract 1 from nums[0] and nums[1]. +// x = 1. Total operations = 1. +// nums becomes [0, 1, 3] + +// i = 1: nums[1] = 1. We need to subtract 1 from nums[1] and nums[2]. +// x = 1. Total operations = 1 + 1 = 2. +// nums becomes [0, 0, 2] + +// i = 2: nums[2] = 2. We need to subtract 2 from nums[2] (and nums[3] if it existed, but it doesn't). +// x = 2. Total operations = 2 + 2 = 4. +// nums becomes [0, 0, 0] + +// This greedy strategy seems to work. For each element `nums[i]`, if it's positive, we must reduce it to zero. The only way to reduce `nums[i]` without affecting `nums[0...i-1]` (which we've already made zero) is to apply the operation at index `i`. The amount we subtract, `x`, must be exactly `nums[i]` to make it zero. This `x` then also reduces `nums[i+1]`. + +// Solution in Code: +class Solution { +public: + long long zeroArray(vector& nums) { + long long total_operations = 0; + int n = nums.size(); + + for (int i = 0; i < n; ++i) { + if (nums[i] > 0) { + total_operations += nums[i]; + if (i + 1 < n) { + nums[i+1] -= nums[i]; + // Ensure nums[i+1] does not become negative + if (nums[i+1] < 0) { + nums[i+1] = 0; + } + } + nums[i] = 0; // nums[i] is now zero + } + } + return total_operations; + } +}; +``` \ No newline at end of file diff --git a/338.Counting Bits b/338.Counting Bits.cpp similarity index 100% rename from 338.Counting Bits rename to 338.Counting Bits.cpp diff --git a/34. Find First and Last Position of Element in Sorted Array b/34. Find First and Last Position of Element in Sorted Array.cpp similarity index 100% rename from 34. Find First and Last Position of Element in Sorted Array rename to 34. Find First and Last Position of Element in Sorted Array.cpp diff --git a/3446. Sort Matrix by Diagonals.cpp b/3446. Sort Matrix by Diagonals.cpp new file mode 100644 index 0000000..7b06b20 --- /dev/null +++ b/3446. Sort Matrix by Diagonals.cpp @@ -0,0 +1,70 @@ +class Solution { +public: + vector> sortMatrix(vector>& grid) { + vector> ans; + vector t; + int cnt = 1; + int j=0; + for(int i=grid.size()-1;i>=0;i--){ + int p=i; + while(j < grid.size() && p < grid.size()){ + t.push_back(grid[p][j]); + p++; + j++; + } + sort(t.begin(), t.end()); + reverse(t.begin(), t.end()); + ans.push_back(t); + t.clear(); + j=0; + } + vector> a1; + int r = 1; + for(int k=1;k=0;i--){ + int r = i; + while(q < ans[p].size()){ + grid[r][j] = ans[p][q]; + q++; + r++; + j++; + } + j=0; + q=0; + p++; + } + q=0; + j=1; + r=0; + for(int i=1;i 2){ + string temp = ""; + for(int i = 0; i < s.length()-1; i++){ + int a = s[i] - '0'; + int b = s[i + 1] - '0'; + temp.push_back(((a + b) % 10) + '0'); + } + s = temp; + } + return s.length() && s[0] == s[1]; + } +}; \ No newline at end of file diff --git a/3477. Fruits Into Baskets II b/3477. Fruits Into Baskets II.cpp similarity index 100% rename from 3477. Fruits Into Baskets II rename to 3477. Fruits Into Baskets II.cpp diff --git a/3479.Fruits Into Baskets 3 b/3479.Fruits Into Baskets 3.cpp similarity index 100% rename from 3479.Fruits Into Baskets 3 rename to 3479.Fruits Into Baskets 3.cpp diff --git a/35. Search Insert Position b/35. Search Insert Position.cpp similarity index 100% rename from 35. Search Insert Position rename to 35. Search Insert Position.cpp diff --git a/355. Design Twitter.cpp b/355. Design Twitter.cpp new file mode 100644 index 0000000..ca563a9 --- /dev/null +++ b/355. Design Twitter.cpp @@ -0,0 +1,48 @@ +class Twitter { +private: + int time; + unordered_map> mp; // Stores followers + unordered_map>> mp2; // Stores tweets (time, tweetId) +public: + Twitter() { + time=0; + } + + void postTweet(int userId, int tweetId) { + mp2[userId].emplace_back(time,tweetId); + time++; + } + + vector getNewsFeed(int userId) { + priority_queue> pq; + for(auto i: mp2[userId]) pq.push(i); + for(auto i: mp[userId]){ + for(auto j: mp2[i]) pq.push(j); + } + vector feed; + int count=10; + while(!pq.empty() && count){ + feed.push_back(pq.top().second); + pq.pop(); + count--; + } + return feed; + } + + void follow(int followerId, int followeeId) { + mp[followerId].insert(followeeId); + } + + void unfollow(int followerId, int followeeId) { + mp[followerId].erase(followeeId); +} +}; + +/** + * Your Twitter object will be instantiated and called as such: + * Twitter* obj = new Twitter(); + * obj->postTweet(userId,tweetId); + * vector param_2 = obj->getNewsFeed(userId); + * obj->follow(followerId,followeeId); + * obj->unfollow(followerId,followeeId); + */ diff --git a/3703. Remove K-Balanced Substrings.cpp b/3703. Remove K-Balanced Substrings.cpp new file mode 100644 index 0000000..e4c9e2c --- /dev/null +++ b/3703. Remove K-Balanced Substrings.cpp @@ -0,0 +1,63 @@ +class Solution { +public: + string removeSubstring(string s, int k) { + stack> stk; + auto f = [&]() -> void { + int cnt = 0; + int len = 0; + for(auto &I : s) { + if(I == '(' && !stk.empty() && stk.top().first == I) { + stk.top().second++; + } else if(I == '(') { + stk.push({I, 1}); + len++; + } + if(I == ')' && !stk.empty() && stk.top().first == I) { + stk.top().second++; + } else if(I == ')') { + stk.push({I, 1}); + len++; + } + //cout << len << endl; + if(len >= 2) { + // atleast one ( and one ) present + if(stk.top().first == ')' && stk.top().second >= k) { + // enough ')' there + // stk = ((()))())(()) , and if k = 2 + auto preserve_top = stk.top(); + stk.pop(); + if(stk.top().first == '(' && stk.top().second >= k){ + int viable = min(preserve_top.second, stk.top().second); + stk.top().second -= viable; + preserve_top.second -= viable; + if(stk.top().second == 0) { + stk.pop(); + len--; + } + if(preserve_top.second == 0) { + len--; + } else { + stk.push(preserve_top); + } + } else { + stk.push(preserve_top); + } + } + } + } + if(!stk.empty() && stk.top().second == 0) { + stk.pop(); + } + }; + f(); + string ans; + while(!stk.empty()) { + int times = stk.top().second; + while(times--) + ans.push_back(stk.top().first); + stk.pop(); + } + reverse(ans.begin(), ans.end()); + return ans; + } +}; \ No newline at end of file diff --git a/3705. Longest substring without repeating characters.cpp b/3705. Longest substring without repeating characters.cpp new file mode 100644 index 0000000..6254ce9 --- /dev/null +++ b/3705. Longest substring without repeating characters.cpp @@ -0,0 +1,27 @@ +#include +#include +#include + +class Solution { +public: + int lengthOfLongestSubstring(std::string s) { + int n = s.size(); + if (n == 0) { + return 0; + } + std::unordered_set char_set; + int left = 0; + int maxLength = 0; + for (int right = 0; right < n; ++right) { + char current_char = s[right]; + while (char_set.count(current_char)) { + char_set.erase(s[left]); + left++; + } + char_set.insert(current_char); + maxLength = std::max(maxLength, right - left + 1); + } + + return maxLength; + } +}; diff --git a/3720. Lexicographically Smallest Permutation Greater Than Target.cpp b/3720. Lexicographically Smallest Permutation Greater Than Target.cpp new file mode 100644 index 0000000..ff27a7e --- /dev/null +++ b/3720. Lexicographically Smallest Permutation Greater Than Target.cpp @@ -0,0 +1,48 @@ +#include +using namespace std; +class Solution { +public: + string lexGreaterPermutation(string s, string target) { + string ans =""; + int n = s.length(); + mapmp; + for(auto&e:s)mp[e]++; + for(int i =0;i m2=mp; + string res =""; + bool ip=1; + for(int j = 0;jfirst; + it->second--; + if(it->second==0)m2.erase(it); + } + else continue; + for(auto&e:m2) + { + while(e.second--)res+=e.first; + } + if(ans =="")ans=res; + else ans = min(ans,res); + } + } + return ans; + } +}; \ No newline at end of file diff --git a/389. Find the Difference b/389. Find the Difference.cpp similarity index 100% rename from 389. Find the Difference rename to 389. Find the Difference.cpp diff --git a/407. Trapping Rain Water II b/407. Trapping Rain Water II.cpp similarity index 100% rename from 407. Trapping Rain Water II rename to 407. Trapping Rain Water II.cpp diff --git a/417. Pacific Atlantic Water Flow.cpp b/417. Pacific Atlantic Water Flow.cpp new file mode 100644 index 0000000..68a8dcb --- /dev/null +++ b/417. Pacific Atlantic Water Flow.cpp @@ -0,0 +1,63 @@ +class Solution { +public: + vector> directions = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}}; + + void DFS(vector>& heights, int i, int j, int prevCellVal, vector>& visited) { + if(i < 0 || i >= heights.size() || j < 0 || j >= heights[0].size()) { //invalid cell + return; + } + + if(heights[i][j] < prevCellVal || visited[i][j]) + return; + + visited[i][j] = true; + for(auto &dir : directions) { + int i_ = i + dir[0]; + int j_ = j + dir[1]; + + DFS(heights, i_, j_, heights[i][j], visited); + } + + } + + vector> pacificAtlantic(vector>& heights) { + int m = heights.size(); //rows + int n = heights[0].size(); //cols + + vector> result; + + vector> pacificVisited(m, vector(n, false)); //pacificVisited[i][j] = true, means [i][j] water can go to Pacific //m*n + vector> atlanticVisited(m, vector(n, false)); //atlanticVisited[i][j] = true, means [i][j] water can go to atlantic //m*n + //T.C : O(m*n) + //S.C : O(m*n) + + + //Top Row and Bottom Row + //Top Row : Pacific connected already + //Bottom Row : atlantic connected already + + for(int j = 0; j < n; j++) { + DFS(heights, 0, j, INT_MIN, pacificVisited); //Top Row + DFS(heights, m-1, j, INT_MIN, atlanticVisited); //Top Row + } + + //First col and last column + //First col : Pacific connected already + //Last col : atlantic connected already + for(int i = 0; i < m; i++) { + DFS(heights, i, 0, INT_MIN, pacificVisited); //First column + DFS(heights, i, n-1, INT_MIN, atlanticVisited); //Last Column + } + + + for(int i = 0; i < m; i++) { + for(int j = 0; j < n; j++) { + if(pacificVisited[i][j] && atlanticVisited[i][j]) { + result.push_back({i, j}); + } + } + } + + return result; + } +}; diff --git a/45.Jump Game II.cpp b/45.Jump Game II.cpp new file mode 100644 index 0000000..79e8e00 --- /dev/null +++ b/45.Jump Game II.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int jump(vector& nums) { + int right = 0, left = 0, steps = 0; + while(right& nums) { + int max = 0; + int count = 0; + for(int i=0;i 0: +If n is odd, multiply result by x. +Square x and divide n by 2. +Return the accumulated result. */ + + class Solution { +public: + double myPow(double x, int n) { + long long N = n; // Convert to long long to handle INT_MIN + if (N < 0) { // Handle negative powers + x = 1 / x; + N = -N; + } + + double result = 1.0; + while (N > 0) { + if (N % 2 == 1) { // If the current power is odd + result *= x; + } + x *= x; // Square x + N /= 2; + } + + return result; + } +}; + \ No newline at end of file diff --git a/51.N-Queens.cpp b/51.N-Queens.cpp new file mode 100644 index 0000000..1c75b86 --- /dev/null +++ b/51.N-Queens.cpp @@ -0,0 +1,44 @@ +#include +using namespace std; + +class Solution { +public: + void solve(int col, int n, vector &board, + vector> &ans, + vector &leftrow, vector &upperdiag, vector &lowerdiag) { + + if (col == n) { + ans.push_back(board); + return; + } + + for (int row = 0; row < n; row++) { + if (leftrow[row] == 0 && lowerdiag[row + col] == 0 && upperdiag[(n - 1) + (col - row)] == 0) { + + board[row][col] = 'Q'; + leftrow[row] = 1; + lowerdiag[row + col] = 1; + upperdiag[(n - 1) + (col - row)] = 1; + + solve(col + 1, n, board, ans, leftrow, upperdiag, lowerdiag); + + board[row][col] = '.'; // backtrack + leftrow[row] = 0; + lowerdiag[row + col] = 0; + upperdiag[(n - 1) + (col - row)] = 0; + } + } + } + + vector> solveNQueens(int n) { + vector> ans; + vector board(n, string(n, '.')); + + vector leftrow(n, 0); + vector lowerdiag(2 * n - 1, 0); + vector upperdiag(2 * n - 1, 0); + + solve(0, n, board, ans, leftrow, upperdiag, lowerdiag); + return ans; + } +}; diff --git a/543. Diameter of Binary Tree b/543. Diameter of Binary Tree.cpp similarity index 100% rename from 543. Diameter of Binary Tree rename to 543. Diameter of Binary Tree.cpp diff --git a/55. Jump Game.cpp b/55. Jump Game.cpp new file mode 100644 index 0000000..b1bf984 --- /dev/null +++ b/55. Jump Game.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + bool canJump(vector& nums) { + int maxDist = 0; + for(int i=0;imaxDist) return false; + maxDist = std::max(maxDist,i+nums[i]); + } + return true; + } +}; diff --git a/557. Reverse Words in a String III b/557. Reverse Words in a String III.cpp similarity index 100% rename from 557. Reverse Words in a String III rename to 557. Reverse Words in a String III.cpp diff --git a/56. Merge intervals.cpp b/56. Merge intervals.cpp new file mode 100644 index 0000000..271e14c --- /dev/null +++ b/56. Merge intervals.cpp @@ -0,0 +1,18 @@ +// 56. Merge Intervals solution + +class Solution { + public: + vector> merge(vector>& intervals) { + vector> ans; + + ranges::sort(intervals); + + for (const vector& interval : intervals) + if (ans.empty() || ans.back()[1] < interval[0]) + ans.push_back(interval); + else + ans.back()[1] = max(ans.back()[1], interval[1]); + + return ans; + } +}; diff --git a/57. Insert Interval.cpp b/57. Insert Interval.cpp new file mode 100644 index 0000000..b63523b --- /dev/null +++ b/57. Insert Interval.cpp @@ -0,0 +1,24 @@ +// Leetcode insert interval solution + +class Solution { +public: + vector> insert(vector>& intervals, vector& newInterval) { + intervals.emplace_back(newInterval); + return merge(intervals); + } + + vector> merge(vector>& intervals) { + sort(intervals.begin(), intervals.end()); + vector> ans; + ans.emplace_back(intervals[0]); + + for (int i = 1; i < intervals.size(); ++i) { + if (ans.back()[1] < intervals[i][0]) { + ans.emplace_back(intervals[i]); + } else { + ans.back()[1] = max(ans.back()[1], intervals[i][1]); + } + } + return ans; + } +}; diff --git a/61. Rotate List b/61. Rotate List.cpp similarity index 100% rename from 61. Rotate List rename to 61. Rotate List.cpp diff --git a/653. Two Sum IV - Input is a BST b/653. Two Sum IV - Input is a BST.cpp similarity index 100% rename from 653. Two Sum IV - Input is a BST rename to 653. Two Sum IV - Input is a BST.cpp diff --git a/678. Valid Parenthesis String.cpp b/678. Valid Parenthesis String.cpp new file mode 100644 index 0000000..4b823ba --- /dev/null +++ b/678. Valid Parenthesis String.cpp @@ -0,0 +1,20 @@ +class Solution { + public boolean checkValidString(String s) { + int min=0,max=0; + for(int i=0;i>& matrix) { + bool zeroinFirstCol = false; + for (int row = 0; row < matrix.size(); row++) { + if (matrix[row][0] == 0) zeroinFirstCol = true; + for (int col = 1; col < matrix[0].size(); col++) { + if (matrix[row][col] == 0) { + matrix[row][0] = 0; + matrix[0][col] = 0; + } + } + } + + for (int row = matrix.size() - 1; row >= 0; row--) { + for (int col = matrix[0].size() - 1; col >= 1; col--) { + if (matrix[row][0] == 0 || matrix[0][col] == 0) { + matrix[row][col] = 0; + } + } + if (zeroinFirstCol) { + matrix[row][0] = 0; + } + } + } +}; diff --git a/763. Partition Labels b/763. Partition Labels.cpp similarity index 100% rename from 763. Partition Labels rename to 763. Partition Labels.cpp diff --git a/78. Subsets.cpp b/78. Subsets.cpp new file mode 100644 index 0000000..f5534c6 --- /dev/null +++ b/78. Subsets.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector> subsets(vector& nums) { + int n=nums.size(); + int Mask=1<> powerSet(Mask); + for (int m=0; m INT_MAX) { + return INT_MAX; + } + if (sign == -1 && (-1 * ans) < INT_MIN) { + return INT_MIN; + } + i++; + } + + return (int)(ans * sign); + } +}; \ No newline at end of file diff --git a/83. Remove Duplicates from Sorted List b/83. Remove Duplicates from Sorted List.cpp similarity index 100% rename from 83. Remove Duplicates from Sorted List rename to 83. Remove Duplicates from Sorted List.cpp diff --git a/838. Push Dominoes.cpp b/838. Push Dominoes.cpp new file mode 100644 index 0000000..833b1ef --- /dev/null +++ b/838. Push Dominoes.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + string pushDominoes(string dominoes) { + int n = dominoes.size(); + vector left(n, 0), right(n, 0); + + // Step 1: Propagate rightward forces + int force = 0; + for (int i = 0; i < n; i++) { + if (dominoes[i] == 'R') force = n; // reset strong rightward force + else if (dominoes[i] == 'L') force = 0; // leftward push blocks rightward + else force = max(force - 1, 0); // decrease over distance + right[i] = force; + } + + // Step 2: Propagate leftward forces + force = 0; + for (int i = n - 1; i >= 0; i--) { + if (dominoes[i] == 'L') force = n; // reset strong leftward force + else if (dominoes[i] == 'R') force = 0; // rightward push blocks leftward + else force = max(force - 1, 0); // decrease over distance + left[i] = force; + } + + // Step 3: Determine final state + string result; + for (int i = 0; i < n; i++) { + if (left[i] == right[i]) result += '.'; + else if (left[i] > right[i]) result += 'L'; + else result += 'R'; + } + + return result; + } +}; diff --git a/84. Largest Rectangle in Histogram b/84. Largest Rectangle in Histogram.cpp similarity index 100% rename from 84. Largest Rectangle in Histogram rename to 84. Largest Rectangle in Histogram.cpp diff --git a/852. peak Index in a Mountain Array b/852. peak Index in a Mountain Array.cpp similarity index 100% rename from 852. peak Index in a Mountain Array rename to 852. peak Index in a Mountain Array.cpp diff --git a/853. Car Fleet I b/853. Car Fleet I.cpp similarity index 100% rename from 853. Car Fleet I rename to 853. Car Fleet I.cpp diff --git a/867. Transpose Matrix b/867. Transpose Matrix.cpp similarity index 100% rename from 867. Transpose Matrix rename to 867. Transpose Matrix.cpp diff --git a/875.Koko Eating Bananas b/875.Koko Eating Bananas.cpp similarity index 100% rename from 875.Koko Eating Bananas rename to 875.Koko Eating Bananas.cpp diff --git a/89. Grey Code b/89. Grey Code.cpp similarity index 100% rename from 89. Grey Code rename to 89. Grey Code.cpp diff --git a/896.Monotonic Array b/896.Monotonic Array.cpp similarity index 100% rename from 896.Monotonic Array rename to 896.Monotonic Array.cpp diff --git a/92. Reverse Linked List II b/92. Reverse Linked List II.cpp similarity index 100% rename from 92. Reverse Linked List II rename to 92. Reverse Linked List II.cpp diff --git a/96. Unique Binary Search Trees.cpp b/96. Unique Binary Search Trees.cpp new file mode 100644 index 0000000..7be39aa --- /dev/null +++ b/96. Unique Binary Search Trees.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int dp[20]{}; + int numTrees(int n) { + if(n <= 1) return 1; + if(dp[n]) return dp[n]; + for(int i = 1; i <= n; i++) + dp[n] += numTrees(i-1) * numTrees(n-i); + return dp[n]; + } +}; \ No newline at end of file diff --git a/98. Validate Binary Search Tree b/98. Validate Binary Search Tree.cpp similarity index 100% rename from 98. Validate Binary Search Tree rename to 98. Validate Binary Search Tree.cpp diff --git a/991. Broken Calculator.cpp b/991. Broken Calculator.cpp new file mode 100644 index 0000000..579d6e1 --- /dev/null +++ b/991. Broken Calculator.cpp @@ -0,0 +1,17 @@ +// 991. Broken Calculator + +class Solution { +public: + int brokenCalc(int startValue, int target) { + int res = 0; + while(startValue < target){ + if(target & 1){ + ++target; + ++res; + } + target >>= 1; + ++res; + } + return res + startValue - target; + } +};