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/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/1857. Largest_Color_Value_in_a_Directed_Graph.cpp b/1857. Largest_Color_Value_in_a_Directed_Graph.cpp new file mode 100644 index 0000000..beb8aa7 --- /dev/null +++ b/1857. Largest_Color_Value_in_a_Directed_Graph.cpp @@ -0,0 +1,64 @@ +// Use Topological Sorting (Kahn’s Algorithm) + Dynamic Programming. + +// For each node, maintain a count[node][color] array of size 26. + +// When processing a node, propagate color counts to its neighbors. + +// Keep track of max color count during traversal. + +// If all nodes are processed → return max count; else → cycle → -1. + + +#include +#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/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/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/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/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/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/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/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/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/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/50.Pow(x,n).cpp b/50.Pow(x,n).cpp new file mode 100644 index 0000000..6dd63b6 --- /dev/null +++ b/50.Pow(x,n).cpp @@ -0,0 +1,44 @@ +/* Approach + +We use exponentiation by squaring to efficiently compute x^n: + +Handle base cases: + +If n == 0, return 1. +If x == 0, return 0 (unless n is 0). +Handle negative powers: + +If n < 0, compute x^{-n} by inverting x (x = 1/x) and making n positive. +For positive powers: + +If n is even: x^n = (x^(n/2)) * (x^(n/2)) +If n is odd: x^n = x * (x^(n-1)) +Implement iteratively to avoid recursion stack overflow for large n: + +While n > 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/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/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/99.Maximize the Number of Target Nodes After Connecting Trees.cpp b/99.Maximize the Number of Target Nodes After Connecting Trees.cpp deleted file mode 100644 index 389385f..0000000 --- a/99.Maximize the Number of Target Nodes After Connecting Trees.cpp +++ /dev/null @@ -1,50 +0,0 @@ -class Solution { -public: - vector maxTargetNodes(vector>& edges1, vector>& edges2, int k) { - // Build adjacency lists - auto graph2 = buildGraph(edges2); - auto graph1 = buildGraph(edges1); - int tree2Size = edges2.size() + 1; - int tree1Size = edges1.size() + 1; - - // Step 1: Find maximum nodes reachable within distance (k - 1) in tree2 - int maxNodesInTree2 = 0; - for (int node = 0; node < tree2Size; ++node) { - maxNodesInTree2 = max(maxNodesInTree2, countReachableNodes(graph2, node, -1, k - 1)); - } - - // Step 2: For each node in tree1, count reachable nodes within distance k - vector result(tree1Size); - for (int node = 0; node < tree1Size; ++node) { - int reachable = countReachableNodes(graph1, node, -1, k); - result[node] = reachable + maxNodesInTree2; - } - - return result; - } - -private: - // Builds adjacency list for given edges - vector> buildGraph(const vector>& edges) { - int nodeCount = edges.size() + 1; - vector> adj(nodeCount); - for (auto& e : edges) { - adj[e[0]].push_back(e[1]); - adj[e[1]].push_back(e[0]); - } - return adj; - } - - // Counts number of nodes within remainingDistance using DFS - int countReachableNodes(const vector>& graph, int node, int parent, int remainingDistance) { - if (remainingDistance < 0) return 0; - - int count = 1; // count current node - for (int neighbor : graph[node]) { - if (neighbor != parent) { - count += countReachableNodes(graph, neighbor, node, remainingDistance - 1); - } - } - return count; - } -};