From 84aa8109220fe4645e6e7b9a0d788d0804c32dd7 Mon Sep 17 00:00:00 2001 From: Mayank Bansal Date: Sat, 4 Oct 2025 20:47:08 +0530 Subject: [PATCH 001/135] 991. Broken Calculator --- 991. Broken Calculator.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 991. Broken Calculator.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; + } +}; From 8ed5df0583fd8b82153e2a0b03a40c01b90be131 Mon Sep 17 00:00:00 2001 From: Harshita Patidar Date: Sun, 5 Oct 2025 00:19:56 +0530 Subject: [PATCH 002/135] Create 1920. Build Array from Permutation.cpp --- 1920. Build Array from Permutation.cpp | 39 ++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 1920. Build Array from Permutation.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; + } +}; From 9c1e33cdea466520dcf667d17097a0c3da9b2078 Mon Sep 17 00:00:00 2001 From: Tiago Silva Date: Sat, 4 Oct 2025 23:37:04 -0300 Subject: [PATCH 003/135] Add solution for Leetcode 1128 - Number of Equivalent Domino Pairs --- 1128.NumberOfEquivalentDominoPairs.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 1128.NumberOfEquivalentDominoPairs.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; + } +}; From 4c8ce3051127f985b66c01edd7735e74d3ca65b6 Mon Sep 17 00:00:00 2001 From: Jay Shah Date: Sun, 5 Oct 2025 10:08:39 +0530 Subject: [PATCH 004/135] 3703. Remove K-Balanced Substrings --- 3703. Remove K-Balanced Substrings.cpp | 63 ++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 3703. Remove K-Balanced Substrings.cpp 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 From d66f06a35ad4b52d34c7763eedaf30d7dfab7ba1 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 5 Oct 2025 06:43:23 +0000 Subject: [PATCH 005/135] Initial plan From 9888a66bad403865655c754d89eadff933a8c2f5 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 5 Oct 2025 06:46:32 +0000 Subject: [PATCH 006/135] Add GitHub issue templates for LeetCode solution contributions Co-authored-by: SjxSubham <142329838+SjxSubham@users.noreply.github.com> --- .github/ISSUE_TEMPLATE/leetcode-solution.yml | 76 +++++++++++++++++++ .../ISSUE_TEMPLATE/solution-contribution.md | 48 ++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/leetcode-solution.yml create mode 100644 .github/ISSUE_TEMPLATE/solution-contribution.md diff --git a/.github/ISSUE_TEMPLATE/leetcode-solution.yml b/.github/ISSUE_TEMPLATE/leetcode-solution.yml new file mode 100644 index 0000000..3bc9e1f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/leetcode-solution.yml @@ -0,0 +1,76 @@ +name: LeetCode Solution Contribution +description: Submit a new LeetCode problem solution +title: "[Problem Number]. [Problem Title]" +labels: ["leetcode-solution"] +body: + - type: markdown + attributes: + value: | + Thanks for contributing to our LeetCode solutions repository! Please fill out the following information about your solution. + + - type: input + id: problem-number + attributes: + label: Problem Number + description: The LeetCode problem number + placeholder: e.g., 2785 + validations: + required: true + + - type: input + id: problem-title + attributes: + label: Problem Title + description: The full title of the LeetCode problem + placeholder: e.g., Sort Vowels in a String + validations: + required: true + + - type: textarea + id: approach + attributes: + label: Approach + description: Describe the approach you used to solve this problem + placeholder: Explain your approach in detail... + validations: + required: true + + - type: textarea + id: intuition + attributes: + label: Intuition + description: Explain the intuition behind your solution + placeholder: Share your thought process and intuition... + validations: + required: true + + - type: textarea + id: solution + attributes: + label: Solution in Code + description: Paste your C++ solution code here + placeholder: | + ```cpp + class Solution { + public: + // Your solution code here + }; + ``` + render: cpp + validations: + required: true + + - type: checkboxes + id: pr-checklist + attributes: + label: PR Checklist + description: Please ensure you follow these guidelines before raising a PR + options: + - label: I will raise a PR with the solution + required: true + - label: The file name format follows the repository convention (e.g., "2785. Sort Vowels in a String.cpp") + required: true + - label: The code is properly formatted and follows C++ best practices + required: false + - label: I have included comments explaining complex logic (if applicable) + required: false diff --git a/.github/ISSUE_TEMPLATE/solution-contribution.md b/.github/ISSUE_TEMPLATE/solution-contribution.md new file mode 100644 index 0000000..55f2d15 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/solution-contribution.md @@ -0,0 +1,48 @@ +--- +name: LeetCode Problem Solution +about: Use this template to contribute a LeetCode problem solution +title: '[Problem Number]. [Problem Title]' +labels: 'leetcode-solution' +assignees: '' + +--- + +## Problem Information +**Problem Number:** +**Problem Title:** +**Problem Link:** https://leetcode.com/problems/[problem-name]/ + +## Contribution Checklist + +- [ ] Approach +- [ ] Intuition +- [ ] Solution in Code +- [ ] Raise a PR, make sure file name format should be according to the others file in this repo .cpp + +--- + +### Approach + + + +### Intuition + + + +### Solution in Code + +```cpp +class Solution { +public: + // Your solution code here +}; +``` + +### Additional Notes + + + +--- + +**File Naming Convention:** Please ensure your file follows the format: `[Number]. [Problem Title].cpp` +**Example:** `2785. Sort Vowels in a String.cpp` From f3481ec16216745e22df0cfd208feeda98bbcf40 Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Sun, 5 Oct 2025 12:24:06 +0530 Subject: [PATCH 007/135] Remove LeetCode solution template and update conventions Removed the template for LeetCode problem solutions and updated file naming conventions. --- .../ISSUE_TEMPLATE/solution-contribution.md | 20 +------------------ 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/solution-contribution.md b/.github/ISSUE_TEMPLATE/solution-contribution.md index 55f2d15..7195f7e 100644 --- a/.github/ISSUE_TEMPLATE/solution-contribution.md +++ b/.github/ISSUE_TEMPLATE/solution-contribution.md @@ -1,17 +1,3 @@ ---- -name: LeetCode Problem Solution -about: Use this template to contribute a LeetCode problem solution -title: '[Problem Number]. [Problem Title]' -labels: 'leetcode-solution' -assignees: '' - ---- - -## Problem Information -**Problem Number:** -**Problem Title:** -**Problem Link:** https://leetcode.com/problems/[problem-name]/ - ## Contribution Checklist - [ ] Approach @@ -38,11 +24,7 @@ public: }; ``` -### Additional Notes - - ---- -**File Naming Convention:** Please ensure your file follows the format: `[Number]. [Problem Title].cpp` +**PR File Naming Convention:** Please ensure your file follows the format: `[Number]. [Problem Title].cpp` **Example:** `2785. Sort Vowels in a String.cpp` From 4752bb232bbb1ad8d75bcd3637bc1b835a43297d Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Sun, 5 Oct 2025 12:24:27 +0530 Subject: [PATCH 008/135] Delete .github/ISSUE_TEMPLATE/leetcode-solution.yml --- .github/ISSUE_TEMPLATE/leetcode-solution.yml | 76 -------------------- 1 file changed, 76 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/leetcode-solution.yml diff --git a/.github/ISSUE_TEMPLATE/leetcode-solution.yml b/.github/ISSUE_TEMPLATE/leetcode-solution.yml deleted file mode 100644 index 3bc9e1f..0000000 --- a/.github/ISSUE_TEMPLATE/leetcode-solution.yml +++ /dev/null @@ -1,76 +0,0 @@ -name: LeetCode Solution Contribution -description: Submit a new LeetCode problem solution -title: "[Problem Number]. [Problem Title]" -labels: ["leetcode-solution"] -body: - - type: markdown - attributes: - value: | - Thanks for contributing to our LeetCode solutions repository! Please fill out the following information about your solution. - - - type: input - id: problem-number - attributes: - label: Problem Number - description: The LeetCode problem number - placeholder: e.g., 2785 - validations: - required: true - - - type: input - id: problem-title - attributes: - label: Problem Title - description: The full title of the LeetCode problem - placeholder: e.g., Sort Vowels in a String - validations: - required: true - - - type: textarea - id: approach - attributes: - label: Approach - description: Describe the approach you used to solve this problem - placeholder: Explain your approach in detail... - validations: - required: true - - - type: textarea - id: intuition - attributes: - label: Intuition - description: Explain the intuition behind your solution - placeholder: Share your thought process and intuition... - validations: - required: true - - - type: textarea - id: solution - attributes: - label: Solution in Code - description: Paste your C++ solution code here - placeholder: | - ```cpp - class Solution { - public: - // Your solution code here - }; - ``` - render: cpp - validations: - required: true - - - type: checkboxes - id: pr-checklist - attributes: - label: PR Checklist - description: Please ensure you follow these guidelines before raising a PR - options: - - label: I will raise a PR with the solution - required: true - - label: The file name format follows the repository convention (e.g., "2785. Sort Vowels in a String.cpp") - required: true - - label: The code is properly formatted and follows C++ best practices - required: false - - label: I have included comments explaining complex logic (if applicable) - required: false From e6dbf7e63239754b01e8ca9850585c20eb069225 Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Sun, 5 Oct 2025 12:25:30 +0530 Subject: [PATCH 009/135] Add solution contribution issue template --- .../{solution-contribution.md => solution-contribution.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/ISSUE_TEMPLATE/{solution-contribution.md => solution-contribution.yml} (100%) diff --git a/.github/ISSUE_TEMPLATE/solution-contribution.md b/.github/ISSUE_TEMPLATE/solution-contribution.yml similarity index 100% rename from .github/ISSUE_TEMPLATE/solution-contribution.md rename to .github/ISSUE_TEMPLATE/solution-contribution.yml From 5b720a8c3ec7a4a2796dd1e288218a5aa98212d5 Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Sun, 5 Oct 2025 12:33:57 +0530 Subject: [PATCH 010/135] Update solution-contribution.yml --- .../ISSUE_TEMPLATE/solution-contribution.yml | 97 +++++++++++++++---- 1 file changed, 79 insertions(+), 18 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/solution-contribution.yml b/.github/ISSUE_TEMPLATE/solution-contribution.yml index 7195f7e..ff4bd76 100644 --- a/.github/ISSUE_TEMPLATE/solution-contribution.yml +++ b/.github/ISSUE_TEMPLATE/solution-contribution.yml @@ -1,29 +1,90 @@ -## Contribution Checklist +name: "Solution Contribution (C++)" +description: "Submit a C++ solution for a LeetCode problem." +title: "[Solution]: . " +body: + - type: markdown + attributes: + value: | + Thank you for contributing a solution! Please fill out the details below. -- [ ] Approach -- [ ] Intuition -- [ ] Solution in Code -- [ ] Raise a PR, make sure file name format should be according to the others file in this repo .cpp + 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 -### Approach - + - 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 -### Intuition - + - 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 -### Solution in Code - -```cpp -class Solution { -public: - // Your solution code here -}; -``` + - 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 **PR File Naming Convention:** Please ensure your file follows the format: `[Number]. [Problem Title].cpp` From c762d289ad1461f3cd814a343272504c2532d30f Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Sun, 5 Oct 2025 12:35:08 +0530 Subject: [PATCH 011/135] Update solution-contribution.yml --- .github/ISSUE_TEMPLATE/solution-contribution.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/solution-contribution.yml b/.github/ISSUE_TEMPLATE/solution-contribution.yml index ff4bd76..ce1b862 100644 --- a/.github/ISSUE_TEMPLATE/solution-contribution.yml +++ b/.github/ISSUE_TEMPLATE/solution-contribution.yml @@ -1,5 +1,5 @@ name: "Solution Contribution (C++)" -description: "Submit a C++ solution for a LeetCode problem." +description: "Submit a C++ solution for a LeetCode problem which already not exists in the repo." title: "[Solution]: . " body: - type: markdown @@ -87,5 +87,3 @@ body: required: true -**PR File Naming Convention:** Please ensure your file follows the format: `[Number]. [Problem Title].cpp` -**Example:** `2785. Sort Vowels in a String.cpp` From 6a86dc682e02b7083da3184381a17c5fa4cd40a6 Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Sun, 5 Oct 2025 12:37:40 +0530 Subject: [PATCH 012/135] Update issue template title format for contributions --- .github/ISSUE_TEMPLATE/solution-contribution.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/solution-contribution.yml b/.github/ISSUE_TEMPLATE/solution-contribution.yml index ce1b862..3bc6285 100644 --- a/.github/ISSUE_TEMPLATE/solution-contribution.yml +++ b/.github/ISSUE_TEMPLATE/solution-contribution.yml @@ -1,6 +1,6 @@ name: "Solution Contribution (C++)" description: "Submit a C++ solution for a LeetCode problem which already not exists in the repo." -title: "[Solution]: . " +title: "[Problem Number]: " body: - type: markdown attributes: From 23d2523ef174f5d3b2d567f838906e5be052a14d Mon Sep 17 00:00:00 2001 From: Subrat Kumar Behera <118915829+Subratkb02@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:17:24 +0530 Subject: [PATCH 013/135] Implementing maximum product subarray --- maximum-product-subarray.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 maximum-product-subarray.cpp diff --git a/maximum-product-subarray.cpp b/maximum-product-subarray.cpp new file mode 100644 index 0000000..b0060b4 --- /dev/null +++ b/maximum-product-subarray.cpp @@ -0,0 +1,23 @@ +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 Date: Mon, 6 Oct 2025 15:04:27 +0300 Subject: [PATCH 014/135] Create 3342. Find Minimum Time to Reach Last Room II.cpp --- .idea/.gitignore | 8 + .idea/Leetcode.iml | 8 + .idea/editor.xml | 341 ++++++++++++++++++ .idea/modules.xml | 8 + .idea/vcs.xml | 6 + ...ind Minimum Time to Reach Last Room II.cpp | 42 +++ 6 files changed, 413 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/Leetcode.iml create mode 100644 .idea/editor.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 3342. Find Minimum Time to Reach Last Room II.cpp diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/Leetcode.iml b/.idea/Leetcode.iml new file mode 100644 index 0000000..bc2cd87 --- /dev/null +++ b/.idea/Leetcode.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/editor.xml b/.idea/editor.xml new file mode 100644 index 0000000..bea4289 --- /dev/null +++ b/.idea/editor.xml @@ -0,0 +1,341 @@ + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..ad30c66 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file 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..875094c --- /dev/null +++ b/3342. Find Minimum Time to Reach Last Room II.cpp @@ -0,0 +1,42 @@ +// +// Created by SaraNabih on 10/6/2025. +// +#include +class Solution { +public: + int minTimeToReach(vector>& moveTime) { + int n = moveTime.size(), m = moveTime[0].size(); + vector> dist(n, vector(m, INT_MAX)); + vector> dir = {{1,0}, {-1,0}, {0,1}, {0,-1}}; + using T = tuple; // time, x, y + priority_queue, greater<>> pq; + pq.push({0, 0, 0}); + dist[0][0] = 0; + + while (!pq.empty()) { + auto [t, x, y] = pq.top(); + pq.pop(); + if (x == n-1 && y == m-1) return t; + if (t > dist[x][y]) continue; + + for (auto& [dx, dy] : dir) { + int nx = x + dx, ny = y + dy; + if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; + + int nt = t + 1; + if (nt < moveTime[nx][ny]) { + int diff = moveTime[nx][ny] - nt; + if (diff % 2 == 1) nt = moveTime[nx][ny] + 1; + else nt = moveTime[nx][ny]; + } + + if (nt < dist[nx][ny]) { + dist[nx][ny] = nt; + pq.push({nt, nx, ny}); + } + } + } + + return -1; + } +}; From d51a22eee272ba1d3f7aa4e54e2383919564ea30 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:24:44 +0300 Subject: [PATCH 015/135] Update .gitignore --- .idea/.gitignore | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/.idea/.gitignore b/.idea/.gitignore index 13566b8..8b13789 100644 --- a/.idea/.gitignore +++ b/.idea/.gitignore @@ -1,8 +1 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml + From 3a4f5d046ea24613f5ddf93a6bbde2fab86593c0 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:25:08 +0300 Subject: [PATCH 016/135] Delete .idea/.gitignore --- .idea/.gitignore | 1 - 1 file changed, 1 deletion(-) delete mode 100644 .idea/.gitignore diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 8b13789..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1 +0,0 @@ - From f06a2bb7e48cee184233ea09f17c5c43aa453138 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:25:29 +0300 Subject: [PATCH 017/135] Delete .idea/vcs.xml --- .idea/vcs.xml | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 .idea/vcs.xml diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 35eb1dd..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file From 1f7cf4817af88d6bbe590f62bf918702fd0a1b42 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:26:01 +0300 Subject: [PATCH 018/135] Delete .idea/modules.xml --- .idea/modules.xml | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 .idea/modules.xml diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index ad30c66..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file From 38ef4d7ab34129cbc952a780b5fdaccfa8a83c22 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:26:15 +0300 Subject: [PATCH 019/135] Delete .idea/editor.xml --- .idea/editor.xml | 341 ----------------------------------------------- 1 file changed, 341 deletions(-) delete mode 100644 .idea/editor.xml diff --git a/.idea/editor.xml b/.idea/editor.xml deleted file mode 100644 index bea4289..0000000 --- a/.idea/editor.xml +++ /dev/null @@ -1,341 +0,0 @@ - - - - - \ No newline at end of file From 598a08fa7c5a9d3d12b3ea7207296798ad223e16 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:26:29 +0300 Subject: [PATCH 020/135] Delete .idea/Leetcode.iml --- .idea/Leetcode.iml | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 .idea/Leetcode.iml diff --git a/.idea/Leetcode.iml b/.idea/Leetcode.iml deleted file mode 100644 index bc2cd87..0000000 --- a/.idea/Leetcode.iml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file From 0f0c6a764f7979105423586d1a82da4829a16680 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:46:24 +0300 Subject: [PATCH 021/135] Update 3342. Find Minimum Time to Reach Last Room II.cpp --- ...ind Minimum Time to Reach Last Room II.cpp | 65 +++++++++---------- 1 file changed, 32 insertions(+), 33 deletions(-) diff --git a/3342. Find Minimum Time to Reach Last Room II.cpp b/3342. Find Minimum Time to Reach Last Room II.cpp index 875094c..28b1c89 100644 --- a/3342. Find Minimum Time to Reach Last Room II.cpp +++ b/3342. Find Minimum Time to Reach Last Room II.cpp @@ -1,42 +1,41 @@ -// -// Created by SaraNabih on 10/6/2025. -// -#include 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 n = moveTime.size(), m = moveTime[0].size(); - vector> dist(n, vector(m, INT_MAX)); - vector> dir = {{1,0}, {-1,0}, {0,1}, {0,-1}}; - using T = tuple; // time, x, y - priority_queue, greater<>> pq; - pq.push({0, 0, 0}); - dist[0][0] = 0; - + 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] = pq.top(); - pq.pop(); - if (x == n-1 && y == m-1) return t; - if (t > dist[x][y]) continue; - - for (auto& [dx, dy] : dir) { - int nx = x + dx, ny = y + dy; - if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; - - int nt = t + 1; - if (nt < moveTime[nx][ny]) { - int diff = moveTime[nx][ny] - nt; - if (diff % 2 == 1) nt = moveTime[nx][ny] + 1; - else nt = moveTime[nx][ny]; - } - - if (nt < dist[nx][ny]) { - dist[nx][ny] = nt; - pq.push({nt, nx, ny}); + 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 -1; + + return mn[r - 1][c - 1]; } }; From 037007910705540a90a295f1826e1898630556bc Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:55:04 +0300 Subject: [PATCH 022/135] Solve 3341. Find Minimum Time to Reach Last Room I --- ...me to Reach Last Room I_20251006155100.cpp | 0 ...me to Reach Last Room I_20251006155127.cpp | 43 ++++++++++++++ ...me to Reach Last Room I_20251006155244.cpp | 0 ...me to Reach Last Room I_20251006155303.cpp | 51 ++++++++++++++++ ...me to Reach Last Room I_20251006155351.cpp | 51 ++++++++++++++++ ...e to Reach Last Room II_20251006150115.cpp | 42 +++++++++++++ ...e to Reach Last Room II_20251006153515.cpp | 43 ++++++++++++++ ...e to Reach Last Room II_20251006153524.cpp | 42 +++++++++++++ .vscode/c_cpp_properties.json | 18 ++++++ .vscode/launch.json | 24 ++++++++ .vscode/settings.json | 59 +++++++++++++++++++ ...Find Minimum Time to Reach Last Room I.cpp | 51 ++++++++++++++++ 12 files changed, 424 insertions(+) create mode 100644 .history/3341. Find Minimum Time to Reach Last Room I_20251006155100.cpp create mode 100644 .history/3341. Find Minimum Time to Reach Last Room I_20251006155127.cpp create mode 100644 .history/3341. Find Minimum Time to Reach Last Room I_20251006155244.cpp create mode 100644 .history/3341. Find Minimum Time to Reach Last Room I_20251006155303.cpp create mode 100644 .history/3341. Find Minimum Time to Reach Last Room I_20251006155351.cpp create mode 100644 .history/3342. Find Minimum Time to Reach Last Room II_20251006150115.cpp create mode 100644 .history/3342. Find Minimum Time to Reach Last Room II_20251006153515.cpp create mode 100644 .history/3342. Find Minimum Time to Reach Last Room II_20251006153524.cpp create mode 100644 .vscode/c_cpp_properties.json create mode 100644 .vscode/launch.json create mode 100644 .vscode/settings.json create mode 100644 3341. Find Minimum Time to Reach Last Room I.cpp diff --git a/.history/3341. Find Minimum Time to Reach Last Room I_20251006155100.cpp b/.history/3341. Find Minimum Time to Reach Last Room I_20251006155100.cpp new file mode 100644 index 0000000..e69de29 diff --git a/.history/3341. Find Minimum Time to Reach Last Room I_20251006155127.cpp b/.history/3341. Find Minimum Time to Reach Last Room I_20251006155127.cpp new file mode 100644 index 0000000..d9a025f --- /dev/null +++ b/.history/3341. Find Minimum Time to Reach Last Room I_20251006155127.cpp @@ -0,0 +1,43 @@ +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; + priority_queue, greater> pq; + pq.push({0, 0, 0}); // t,x,y + mn[0][0] = 0; + while (!pq.empty()) + { + auto [t, x, y] = 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]) + 1; + if (nt < mn[nx][ny]) + { + mn[nx][ny] = nt; + pq.push({nt, nx, ny}); + } + } + } + return mn[r - 1][c - 1]; + } +}; \ No newline at end of file diff --git a/.history/3341. Find Minimum Time to Reach Last Room I_20251006155244.cpp b/.history/3341. Find Minimum Time to Reach Last Room I_20251006155244.cpp new file mode 100644 index 0000000..e69de29 diff --git a/.history/3341. Find Minimum Time to Reach Last Room I_20251006155303.cpp b/.history/3341. Find Minimum Time to Reach Last Room I_20251006155303.cpp new file mode 100644 index 0000000..188ad8d --- /dev/null +++ b/.history/3341. Find Minimum Time to Reach Last Room I_20251006155303.cpp @@ -0,0 +1,51 @@ +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 + priority_queue, greater> pq; + + pq.push({0, 0, 0}); + mn[0][0] = 0; + + while (!pq.empty()) + { + auto [t, x, y] = 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]) + 1; + if (nt < mn[nx][ny]) + { + mn[nx][ny] = nt; + pq.push({nt, nx, ny}); + } + } + } + + return mn[r - 1][c - 1]; + } +}; diff --git a/.history/3341. Find Minimum Time to Reach Last Room I_20251006155351.cpp b/.history/3341. Find Minimum Time to Reach Last Room I_20251006155351.cpp new file mode 100644 index 0000000..188ad8d --- /dev/null +++ b/.history/3341. Find Minimum Time to Reach Last Room I_20251006155351.cpp @@ -0,0 +1,51 @@ +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 + priority_queue, greater> pq; + + pq.push({0, 0, 0}); + mn[0][0] = 0; + + while (!pq.empty()) + { + auto [t, x, y] = 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]) + 1; + if (nt < mn[nx][ny]) + { + mn[nx][ny] = nt; + pq.push({nt, nx, ny}); + } + } + } + + return mn[r - 1][c - 1]; + } +}; diff --git a/.history/3342. Find Minimum Time to Reach Last Room II_20251006150115.cpp b/.history/3342. Find Minimum Time to Reach Last Room II_20251006150115.cpp new file mode 100644 index 0000000..875094c --- /dev/null +++ b/.history/3342. Find Minimum Time to Reach Last Room II_20251006150115.cpp @@ -0,0 +1,42 @@ +// +// Created by SaraNabih on 10/6/2025. +// +#include +class Solution { +public: + int minTimeToReach(vector>& moveTime) { + int n = moveTime.size(), m = moveTime[0].size(); + vector> dist(n, vector(m, INT_MAX)); + vector> dir = {{1,0}, {-1,0}, {0,1}, {0,-1}}; + using T = tuple; // time, x, y + priority_queue, greater<>> pq; + pq.push({0, 0, 0}); + dist[0][0] = 0; + + while (!pq.empty()) { + auto [t, x, y] = pq.top(); + pq.pop(); + if (x == n-1 && y == m-1) return t; + if (t > dist[x][y]) continue; + + for (auto& [dx, dy] : dir) { + int nx = x + dx, ny = y + dy; + if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; + + int nt = t + 1; + if (nt < moveTime[nx][ny]) { + int diff = moveTime[nx][ny] - nt; + if (diff % 2 == 1) nt = moveTime[nx][ny] + 1; + else nt = moveTime[nx][ny]; + } + + if (nt < dist[nx][ny]) { + dist[nx][ny] = nt; + pq.push({nt, nx, ny}); + } + } + } + + return -1; + } +}; diff --git a/.history/3342. Find Minimum Time to Reach Last Room II_20251006153515.cpp b/.history/3342. Find Minimum Time to Reach Last Room II_20251006153515.cpp new file mode 100644 index 0000000..69dacce --- /dev/null +++ b/.history/3342. Find Minimum Time to Reach Last Room II_20251006153515.cpp @@ -0,0 +1,43 @@ +// +// Created by SaraNabih on 10/6/2025. +// +#include +using namespace std; +class Solution { +public: + int minTimeToReach(vector>& moveTime) { + int n = moveTime.size(), m = moveTime[0].size(); + vector> dist(n, vector(m, INT_MAX)); + vector> dir = {{1,0}, {-1,0}, {0,1}, {0,-1}}; + using T = tuple; // time, x, y + priority_queue, greater<>> pq; + pq.push({0, 0, 0}); + dist[0][0] = 0; + + while (!pq.empty()) { + auto [t, x, y] = pq.top(); + pq.pop(); + if (x == n-1 && y == m-1) return t; + if (t > dist[x][y]) continue; + + for (auto& [dx, dy] : dir) { + int nx = x + dx, ny = y + dy; + if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; + + int nt = t + 1; + if (nt < moveTime[nx][ny]) { + int diff = moveTime[nx][ny] - nt; + if (diff % 2 == 1) nt = moveTime[nx][ny] + 1; + else nt = moveTime[nx][ny]; + } + + if (nt < dist[nx][ny]) { + dist[nx][ny] = nt; + pq.push({nt, nx, ny}); + } + } + } + + return -1; + } +}; diff --git a/.history/3342. Find Minimum Time to Reach Last Room II_20251006153524.cpp b/.history/3342. Find Minimum Time to Reach Last Room II_20251006153524.cpp new file mode 100644 index 0000000..875094c --- /dev/null +++ b/.history/3342. Find Minimum Time to Reach Last Room II_20251006153524.cpp @@ -0,0 +1,42 @@ +// +// Created by SaraNabih on 10/6/2025. +// +#include +class Solution { +public: + int minTimeToReach(vector>& moveTime) { + int n = moveTime.size(), m = moveTime[0].size(); + vector> dist(n, vector(m, INT_MAX)); + vector> dir = {{1,0}, {-1,0}, {0,1}, {0,-1}}; + using T = tuple; // time, x, y + priority_queue, greater<>> pq; + pq.push({0, 0, 0}); + dist[0][0] = 0; + + while (!pq.empty()) { + auto [t, x, y] = pq.top(); + pq.pop(); + if (x == n-1 && y == m-1) return t; + if (t > dist[x][y]) continue; + + for (auto& [dx, dy] : dir) { + int nx = x + dx, ny = y + dy; + if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; + + int nt = t + 1; + if (nt < moveTime[nx][ny]) { + int diff = moveTime[nx][ny] - nt; + if (diff % 2 == 1) nt = moveTime[nx][ny] + 1; + else nt = moveTime[nx][ny]; + } + + if (nt < dist[nx][ny]) { + dist[nx][ny] = nt; + pq.push({nt, nx, ny}); + } + } + } + + return -1; + } +}; diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..bf24b14 --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,18 @@ +{ + "configurations": [ + { + "name": "windows-gcc-x64", + "includePath": [ + "${workspaceFolder}/**" + ], + "compilerPath": "C:/mingw64/mingw64/bin/gcc.exe", + "cStandard": "${default}", + "cppStandard": "${default}", + "intelliSenseMode": "windows-gcc-x64", + "compilerArgs": [ + "" + ] + } + ], + "version": 4 +} \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..fca4833 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,24 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "C/C++ Runner: Debug Session", + "type": "cppdbg", + "request": "launch", + "args": [], + "stopAtEntry": false, + "externalConsole": true, + "cwd": "c:/Users/XPRISTO/Leetcode", + "program": "c:/Users/XPRISTO/Leetcode/build/Debug/outDebug", + "MIMode": "gdb", + "miDebuggerPath": "gdb", + "setupCommands": [ + { + "description": "Enable pretty-printing for gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + } + ] + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..c9e66f1 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,59 @@ +{ + "C_Cpp_Runner.cCompilerPath": "gcc", + "C_Cpp_Runner.cppCompilerPath": "g++", + "C_Cpp_Runner.debuggerPath": "gdb", + "C_Cpp_Runner.cStandard": "", + "C_Cpp_Runner.cppStandard": "", + "C_Cpp_Runner.msvcBatchPath": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Auxiliary/Build/vcvarsall.bat", + "C_Cpp_Runner.useMsvc": false, + "C_Cpp_Runner.warnings": [ + "-Wall", + "-Wextra", + "-Wpedantic", + "-Wshadow", + "-Wformat=2", + "-Wcast-align", + "-Wconversion", + "-Wsign-conversion", + "-Wnull-dereference" + ], + "C_Cpp_Runner.msvcWarnings": [ + "/W4", + "/permissive-", + "/w14242", + "/w14287", + "/w14296", + "/w14311", + "/w14826", + "/w44062", + "/w44242", + "/w14905", + "/w14906", + "/w14263", + "/w44265", + "/w14928" + ], + "C_Cpp_Runner.enableWarnings": true, + "C_Cpp_Runner.warningsAsError": false, + "C_Cpp_Runner.compilerArgs": [], + "C_Cpp_Runner.linkerArgs": [], + "C_Cpp_Runner.includePaths": [], + "C_Cpp_Runner.includeSearch": [ + "*", + "**/*" + ], + "C_Cpp_Runner.excludeSearch": [ + "**/build", + "**/build/**", + "**/.*", + "**/.*/**", + "**/.vscode", + "**/.vscode/**" + ], + "C_Cpp_Runner.useAddressSanitizer": false, + "C_Cpp_Runner.useUndefinedSanitizer": false, + "C_Cpp_Runner.useLeakSanitizer": false, + "C_Cpp_Runner.showCompilationTime": false, + "C_Cpp_Runner.useLinkTimeOptimization": false, + "C_Cpp_Runner.msvcSecureNoWarnings": false +} \ No newline at end of file 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..188ad8d --- /dev/null +++ b/3341. Find Minimum Time to Reach Last Room I.cpp @@ -0,0 +1,51 @@ +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 + priority_queue, greater> pq; + + pq.push({0, 0, 0}); + mn[0][0] = 0; + + while (!pq.empty()) + { + auto [t, x, y] = 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]) + 1; + if (nt < mn[nx][ny]) + { + mn[nx][ny] = nt; + pq.push({nt, nx, ny}); + } + } + } + + return mn[r - 1][c - 1]; + } +}; From 2b41b4781d4d7de052c61edc106655d90a5c0a20 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:58:39 +0300 Subject: [PATCH 023/135] Delete .history/3341. Find Minimum Time to Reach Last Room I_20251006155100.cpp --- ...341. Find Minimum Time to Reach Last Room I_20251006155100.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .history/3341. Find Minimum Time to Reach Last Room I_20251006155100.cpp diff --git a/.history/3341. Find Minimum Time to Reach Last Room I_20251006155100.cpp b/.history/3341. Find Minimum Time to Reach Last Room I_20251006155100.cpp deleted file mode 100644 index e69de29..0000000 From b9c8c99436348083748a7014f28b9341a6939a23 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:58:57 +0300 Subject: [PATCH 024/135] Delete .history/3341. Find Minimum Time to Reach Last Room I_20251006155127.cpp --- ...me to Reach Last Room I_20251006155127.cpp | 43 ------------------- 1 file changed, 43 deletions(-) delete mode 100644 .history/3341. Find Minimum Time to Reach Last Room I_20251006155127.cpp diff --git a/.history/3341. Find Minimum Time to Reach Last Room I_20251006155127.cpp b/.history/3341. Find Minimum Time to Reach Last Room I_20251006155127.cpp deleted file mode 100644 index d9a025f..0000000 --- a/.history/3341. Find Minimum Time to Reach Last Room I_20251006155127.cpp +++ /dev/null @@ -1,43 +0,0 @@ -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; - priority_queue, greater> pq; - pq.push({0, 0, 0}); // t,x,y - mn[0][0] = 0; - while (!pq.empty()) - { - auto [t, x, y] = 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]) + 1; - if (nt < mn[nx][ny]) - { - mn[nx][ny] = nt; - pq.push({nt, nx, ny}); - } - } - } - return mn[r - 1][c - 1]; - } -}; \ No newline at end of file From bd66dc19b5f0768b912d3c25472c28975ef38e72 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:59:28 +0300 Subject: [PATCH 025/135] Delete .history/3341. Find Minimum Time to Reach Last Room I_20251006155244.cpp --- ...341. Find Minimum Time to Reach Last Room I_20251006155244.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .history/3341. Find Minimum Time to Reach Last Room I_20251006155244.cpp diff --git a/.history/3341. Find Minimum Time to Reach Last Room I_20251006155244.cpp b/.history/3341. Find Minimum Time to Reach Last Room I_20251006155244.cpp deleted file mode 100644 index e69de29..0000000 From b208bfed7383f0494f45c5cb881461d0612c7e85 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 15:59:49 +0300 Subject: [PATCH 026/135] Delete 3341. Find Minimum Time to Reach Last Room I.cpp --- ...Find Minimum Time to Reach Last Room I.cpp | 51 ------------------- 1 file changed, 51 deletions(-) delete mode 100644 3341. Find Minimum Time to Reach Last Room I.cpp diff --git a/3341. Find Minimum Time to Reach Last Room I.cpp b/3341. Find Minimum Time to Reach Last Room I.cpp deleted file mode 100644 index 188ad8d..0000000 --- a/3341. Find Minimum Time to Reach Last Room I.cpp +++ /dev/null @@ -1,51 +0,0 @@ -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 - priority_queue, greater> pq; - - pq.push({0, 0, 0}); - mn[0][0] = 0; - - while (!pq.empty()) - { - auto [t, x, y] = 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]) + 1; - if (nt < mn[nx][ny]) - { - mn[nx][ny] = nt; - pq.push({nt, nx, ny}); - } - } - } - - return mn[r - 1][c - 1]; - } -}; From 34e05ffe50f6556f27ec447c7d084bab3251b0b8 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 16:00:14 +0300 Subject: [PATCH 027/135] Delete .history/3341. Find Minimum Time to Reach Last Room I_20251006155303.cpp --- ...me to Reach Last Room I_20251006155303.cpp | 51 ------------------- 1 file changed, 51 deletions(-) delete mode 100644 .history/3341. Find Minimum Time to Reach Last Room I_20251006155303.cpp diff --git a/.history/3341. Find Minimum Time to Reach Last Room I_20251006155303.cpp b/.history/3341. Find Minimum Time to Reach Last Room I_20251006155303.cpp deleted file mode 100644 index 188ad8d..0000000 --- a/.history/3341. Find Minimum Time to Reach Last Room I_20251006155303.cpp +++ /dev/null @@ -1,51 +0,0 @@ -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 - priority_queue, greater> pq; - - pq.push({0, 0, 0}); - mn[0][0] = 0; - - while (!pq.empty()) - { - auto [t, x, y] = 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]) + 1; - if (nt < mn[nx][ny]) - { - mn[nx][ny] = nt; - pq.push({nt, nx, ny}); - } - } - } - - return mn[r - 1][c - 1]; - } -}; From bddf4d27483497b980e002c0702b59fd1e1882a9 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 16:00:41 +0300 Subject: [PATCH 028/135] Delete .history/3341. Find Minimum Time to Reach Last Room I_20251006155351.cpp --- ...me to Reach Last Room I_20251006155351.cpp | 51 ------------------- 1 file changed, 51 deletions(-) delete mode 100644 .history/3341. Find Minimum Time to Reach Last Room I_20251006155351.cpp diff --git a/.history/3341. Find Minimum Time to Reach Last Room I_20251006155351.cpp b/.history/3341. Find Minimum Time to Reach Last Room I_20251006155351.cpp deleted file mode 100644 index 188ad8d..0000000 --- a/.history/3341. Find Minimum Time to Reach Last Room I_20251006155351.cpp +++ /dev/null @@ -1,51 +0,0 @@ -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 - priority_queue, greater> pq; - - pq.push({0, 0, 0}); - mn[0][0] = 0; - - while (!pq.empty()) - { - auto [t, x, y] = 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]) + 1; - if (nt < mn[nx][ny]) - { - mn[nx][ny] = nt; - pq.push({nt, nx, ny}); - } - } - } - - return mn[r - 1][c - 1]; - } -}; From ad0e9bde1f3af3b2465bfc2065b73f9f3e1e40e3 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 16:01:02 +0300 Subject: [PATCH 029/135] Delete .history/3342. Find Minimum Time to Reach Last Room II_20251006150115.cpp --- ...e to Reach Last Room II_20251006150115.cpp | 42 ------------------- 1 file changed, 42 deletions(-) delete mode 100644 .history/3342. Find Minimum Time to Reach Last Room II_20251006150115.cpp diff --git a/.history/3342. Find Minimum Time to Reach Last Room II_20251006150115.cpp b/.history/3342. Find Minimum Time to Reach Last Room II_20251006150115.cpp deleted file mode 100644 index 875094c..0000000 --- a/.history/3342. Find Minimum Time to Reach Last Room II_20251006150115.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// -// Created by SaraNabih on 10/6/2025. -// -#include -class Solution { -public: - int minTimeToReach(vector>& moveTime) { - int n = moveTime.size(), m = moveTime[0].size(); - vector> dist(n, vector(m, INT_MAX)); - vector> dir = {{1,0}, {-1,0}, {0,1}, {0,-1}}; - using T = tuple; // time, x, y - priority_queue, greater<>> pq; - pq.push({0, 0, 0}); - dist[0][0] = 0; - - while (!pq.empty()) { - auto [t, x, y] = pq.top(); - pq.pop(); - if (x == n-1 && y == m-1) return t; - if (t > dist[x][y]) continue; - - for (auto& [dx, dy] : dir) { - int nx = x + dx, ny = y + dy; - if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; - - int nt = t + 1; - if (nt < moveTime[nx][ny]) { - int diff = moveTime[nx][ny] - nt; - if (diff % 2 == 1) nt = moveTime[nx][ny] + 1; - else nt = moveTime[nx][ny]; - } - - if (nt < dist[nx][ny]) { - dist[nx][ny] = nt; - pq.push({nt, nx, ny}); - } - } - } - - return -1; - } -}; From fc97b3eb9e58bddcb4345f156e37d6e3a2dfc4b8 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 16:01:20 +0300 Subject: [PATCH 030/135] Delete .history/3342. Find Minimum Time to Reach Last Room II_20251006153515.cpp --- ...e to Reach Last Room II_20251006153515.cpp | 43 ------------------- 1 file changed, 43 deletions(-) delete mode 100644 .history/3342. Find Minimum Time to Reach Last Room II_20251006153515.cpp diff --git a/.history/3342. Find Minimum Time to Reach Last Room II_20251006153515.cpp b/.history/3342. Find Minimum Time to Reach Last Room II_20251006153515.cpp deleted file mode 100644 index 69dacce..0000000 --- a/.history/3342. Find Minimum Time to Reach Last Room II_20251006153515.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// -// Created by SaraNabih on 10/6/2025. -// -#include -using namespace std; -class Solution { -public: - int minTimeToReach(vector>& moveTime) { - int n = moveTime.size(), m = moveTime[0].size(); - vector> dist(n, vector(m, INT_MAX)); - vector> dir = {{1,0}, {-1,0}, {0,1}, {0,-1}}; - using T = tuple; // time, x, y - priority_queue, greater<>> pq; - pq.push({0, 0, 0}); - dist[0][0] = 0; - - while (!pq.empty()) { - auto [t, x, y] = pq.top(); - pq.pop(); - if (x == n-1 && y == m-1) return t; - if (t > dist[x][y]) continue; - - for (auto& [dx, dy] : dir) { - int nx = x + dx, ny = y + dy; - if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; - - int nt = t + 1; - if (nt < moveTime[nx][ny]) { - int diff = moveTime[nx][ny] - nt; - if (diff % 2 == 1) nt = moveTime[nx][ny] + 1; - else nt = moveTime[nx][ny]; - } - - if (nt < dist[nx][ny]) { - dist[nx][ny] = nt; - pq.push({nt, nx, ny}); - } - } - } - - return -1; - } -}; From a41163fe98e1df725b34c11ce657bfc1e76dadb9 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 16:01:38 +0300 Subject: [PATCH 031/135] Delete .history/3342. Find Minimum Time to Reach Last Room II_20251006153524.cpp --- ...e to Reach Last Room II_20251006153524.cpp | 42 ------------------- 1 file changed, 42 deletions(-) delete mode 100644 .history/3342. Find Minimum Time to Reach Last Room II_20251006153524.cpp diff --git a/.history/3342. Find Minimum Time to Reach Last Room II_20251006153524.cpp b/.history/3342. Find Minimum Time to Reach Last Room II_20251006153524.cpp deleted file mode 100644 index 875094c..0000000 --- a/.history/3342. Find Minimum Time to Reach Last Room II_20251006153524.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// -// Created by SaraNabih on 10/6/2025. -// -#include -class Solution { -public: - int minTimeToReach(vector>& moveTime) { - int n = moveTime.size(), m = moveTime[0].size(); - vector> dist(n, vector(m, INT_MAX)); - vector> dir = {{1,0}, {-1,0}, {0,1}, {0,-1}}; - using T = tuple; // time, x, y - priority_queue, greater<>> pq; - pq.push({0, 0, 0}); - dist[0][0] = 0; - - while (!pq.empty()) { - auto [t, x, y] = pq.top(); - pq.pop(); - if (x == n-1 && y == m-1) return t; - if (t > dist[x][y]) continue; - - for (auto& [dx, dy] : dir) { - int nx = x + dx, ny = y + dy; - if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; - - int nt = t + 1; - if (nt < moveTime[nx][ny]) { - int diff = moveTime[nx][ny] - nt; - if (diff % 2 == 1) nt = moveTime[nx][ny] + 1; - else nt = moveTime[nx][ny]; - } - - if (nt < dist[nx][ny]) { - dist[nx][ny] = nt; - pq.push({nt, nx, ny}); - } - } - } - - return -1; - } -}; From 15aae4136f42ab833df4c1c214e1448fa8c1f632 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 16:01:51 +0300 Subject: [PATCH 032/135] Delete .vscode/c_cpp_properties.json --- .vscode/c_cpp_properties.json | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 .vscode/c_cpp_properties.json diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json deleted file mode 100644 index bf24b14..0000000 --- a/.vscode/c_cpp_properties.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "configurations": [ - { - "name": "windows-gcc-x64", - "includePath": [ - "${workspaceFolder}/**" - ], - "compilerPath": "C:/mingw64/mingw64/bin/gcc.exe", - "cStandard": "${default}", - "cppStandard": "${default}", - "intelliSenseMode": "windows-gcc-x64", - "compilerArgs": [ - "" - ] - } - ], - "version": 4 -} \ No newline at end of file From 4b1b82071e364ac66313c2522a5f41b8c0299294 Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 16:02:10 +0300 Subject: [PATCH 033/135] Delete .vscode/launch.json --- .vscode/launch.json | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 .vscode/launch.json diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index fca4833..0000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "name": "C/C++ Runner: Debug Session", - "type": "cppdbg", - "request": "launch", - "args": [], - "stopAtEntry": false, - "externalConsole": true, - "cwd": "c:/Users/XPRISTO/Leetcode", - "program": "c:/Users/XPRISTO/Leetcode/build/Debug/outDebug", - "MIMode": "gdb", - "miDebuggerPath": "gdb", - "setupCommands": [ - { - "description": "Enable pretty-printing for gdb", - "text": "-enable-pretty-printing", - "ignoreFailures": true - } - ] - } - ] -} \ No newline at end of file From 0fb69532cc4647f007e72db21f228742888875cb Mon Sep 17 00:00:00 2001 From: Sara Nabih <147654777+saraanbih@users.noreply.github.com> Date: Mon, 6 Oct 2025 16:02:25 +0300 Subject: [PATCH 034/135] Delete .vscode/settings.json --- .vscode/settings.json | 59 ------------------------------------------- 1 file changed, 59 deletions(-) delete mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index c9e66f1..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "C_Cpp_Runner.cCompilerPath": "gcc", - "C_Cpp_Runner.cppCompilerPath": "g++", - "C_Cpp_Runner.debuggerPath": "gdb", - "C_Cpp_Runner.cStandard": "", - "C_Cpp_Runner.cppStandard": "", - "C_Cpp_Runner.msvcBatchPath": "C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Auxiliary/Build/vcvarsall.bat", - "C_Cpp_Runner.useMsvc": false, - "C_Cpp_Runner.warnings": [ - "-Wall", - "-Wextra", - "-Wpedantic", - "-Wshadow", - "-Wformat=2", - "-Wcast-align", - "-Wconversion", - "-Wsign-conversion", - "-Wnull-dereference" - ], - "C_Cpp_Runner.msvcWarnings": [ - "/W4", - "/permissive-", - "/w14242", - "/w14287", - "/w14296", - "/w14311", - "/w14826", - "/w44062", - "/w44242", - "/w14905", - "/w14906", - "/w14263", - "/w44265", - "/w14928" - ], - "C_Cpp_Runner.enableWarnings": true, - "C_Cpp_Runner.warningsAsError": false, - "C_Cpp_Runner.compilerArgs": [], - "C_Cpp_Runner.linkerArgs": [], - "C_Cpp_Runner.includePaths": [], - "C_Cpp_Runner.includeSearch": [ - "*", - "**/*" - ], - "C_Cpp_Runner.excludeSearch": [ - "**/build", - "**/build/**", - "**/.*", - "**/.*/**", - "**/.vscode", - "**/.vscode/**" - ], - "C_Cpp_Runner.useAddressSanitizer": false, - "C_Cpp_Runner.useUndefinedSanitizer": false, - "C_Cpp_Runner.useLeakSanitizer": false, - "C_Cpp_Runner.showCompilationTime": false, - "C_Cpp_Runner.useLinkTimeOptimization": false, - "C_Cpp_Runner.msvcSecureNoWarnings": false -} \ No newline at end of file From de6a1ecc842309266a80838773816ed1c6d9368d Mon Sep 17 00:00:00 2001 From: Rajanya Saha Date: Mon, 6 Oct 2025 19:01:14 +0530 Subject: [PATCH 035/135] Created 2894. Divisible and Non-divisible Sums Difference.cpp --- ...ible and Non-divisible Sums Difference.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 2894. Divisible and Non-divisible Sums Difference.cpp 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..3b54f6c --- /dev/null +++ b/2894. Divisible and Non-divisible Sums Difference.cpp @@ -0,0 +1,33 @@ +// Intuition -- +// We are separating the total range [1…n] into two complementary sets: +//Multiples of m +//Non-multiples of m + +// The trick is simple -- +// Loop through each number once. +// If it’s divisible by m, add it to one sum (num2). +// Otherwise, add to the other sum (num1). +// Finally, return their difference. +// This ensures O(n) time and O(1) extra space. + +// Step-by-Step Approach -- +//1. Initialize num1 = 0, num2 = 0 +//2. Loop i from 1 to n +//3. If i % m == 0 → num2 += i +//4. Else → num1 += i +//5. Return num1 - num2 + +// code -- +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; + } +}; From 01ed9cb0839aae90d4a1546b0b3160f2b986e7da Mon Sep 17 00:00:00 2001 From: Subhosjx Date: Mon, 6 Oct 2025 19:53:26 +0530 Subject: [PATCH 036/135] Create 417. Pacific Atlantic Water Flow.cpp --- 417. Pacific Atlantic Water Flow.cpp | 63 ++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 417. Pacific Atlantic Water Flow.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; + } +}; From c15c9e18951ed245d0cab2b81fe202bf2e58284d Mon Sep 17 00:00:00 2001 From: Rajanya Saha Date: Mon, 6 Oct 2025 20:22:04 +0530 Subject: [PATCH 037/135] 2894. Divisible and Non-divisible Sums Difference --- ...ivisible and Non-divisible Sums Difference | 33 +++++++++++++++++++ ...ible and Non-divisible Sums Difference.cpp | 33 ------------------- 2 files changed, 33 insertions(+), 33 deletions(-) create mode 100644 2894. Divisible and Non-divisible Sums Difference delete mode 100644 2894. Divisible and Non-divisible Sums Difference.cpp diff --git a/2894. Divisible and Non-divisible Sums Difference b/2894. Divisible and Non-divisible Sums Difference new file mode 100644 index 0000000..c1247aa --- /dev/null +++ b/2894. Divisible and Non-divisible Sums Difference @@ -0,0 +1,33 @@ +## Intuition -- +We are separating the total range [1…n] into two complementary sets: +Multiples of m +Non-multiples of m + +• The trick is simple -- +Loop through each number once. +If it’s divisible by m, add it to one sum (num2). +Otherwise, add to the other sum (num1). +Finally, return their difference. +This ensures O(n) time and O(1) extra space. + +## Intuition -- +1. Initialize num1 = 0, num2 = 0 +2. Loop i from 1 to n +3. If i % m == 0 → num2 += i +4. Else → num1 += i +5. Return num1 - num2 + +## code -- +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/2894. Divisible and Non-divisible Sums Difference.cpp b/2894. Divisible and Non-divisible Sums Difference.cpp deleted file mode 100644 index 3b54f6c..0000000 --- a/2894. Divisible and Non-divisible Sums Difference.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// Intuition -- -// We are separating the total range [1…n] into two complementary sets: -//Multiples of m -//Non-multiples of m - -// The trick is simple -- -// Loop through each number once. -// If it’s divisible by m, add it to one sum (num2). -// Otherwise, add to the other sum (num1). -// Finally, return their difference. -// This ensures O(n) time and O(1) extra space. - -// Step-by-Step Approach -- -//1. Initialize num1 = 0, num2 = 0 -//2. Loop i from 1 to n -//3. If i % m == 0 → num2 += i -//4. Else → num1 += i -//5. Return num1 - num2 - -// code -- -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; - } -}; From 086f0aa7afb5c0b88cd960a0e5ea783d0702655b Mon Sep 17 00:00:00 2001 From: Rajanya Saha Date: Mon, 6 Oct 2025 20:25:18 +0530 Subject: [PATCH 038/135] Rename 2894. Divisible and Non-divisible Sums Difference to 2894. Divisible and Non-divisible Sums Difference.md --- ...erence => 2894. Divisible and Non-divisible Sums Difference.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 2894. Divisible and Non-divisible Sums Difference => 2894. Divisible and Non-divisible Sums Difference.md (100%) diff --git a/2894. Divisible and Non-divisible Sums Difference b/2894. Divisible and Non-divisible Sums Difference.md similarity index 100% rename from 2894. Divisible and Non-divisible Sums Difference rename to 2894. Divisible and Non-divisible Sums Difference.md From eb67ca92156d9f87251cfbc0c885b5346bb445cd Mon Sep 17 00:00:00 2001 From: Rajanya Saha Date: Mon, 6 Oct 2025 20:26:35 +0530 Subject: [PATCH 039/135] Update 2894. Divisible and Non-divisible Sums Difference.md --- 2894. Divisible and Non-divisible Sums Difference.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/2894. Divisible and Non-divisible Sums Difference.md b/2894. Divisible and Non-divisible Sums Difference.md index c1247aa..5d48021 100644 --- a/2894. Divisible and Non-divisible Sums Difference.md +++ b/2894. Divisible and Non-divisible Sums Difference.md @@ -1,4 +1,4 @@ -## Intuition -- +## Appreach -- We are separating the total range [1…n] into two complementary sets: Multiples of m Non-multiples of m @@ -18,6 +18,7 @@ This ensures O(n) time and O(1) extra space. 5. Return num1 - num2 ## code -- +``` class Solution { public: int differenceOfSums(int n, int m) { @@ -31,3 +32,4 @@ public: return num1 - num2; } }; +``` From b89fa5ca333f5a89eb7e1dc7bd4bd75f65daa594 Mon Sep 17 00:00:00 2001 From: Rajanya Saha Date: Mon, 6 Oct 2025 20:28:01 +0530 Subject: [PATCH 040/135] 2894. Divisible and Non-divisible Sums Difference --- 2894. Divisible and Non-divisible Sums Difference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/2894. Divisible and Non-divisible Sums Difference.md b/2894. Divisible and Non-divisible Sums Difference.md index 5d48021..cf6828a 100644 --- a/2894. Divisible and Non-divisible Sums Difference.md +++ b/2894. Divisible and Non-divisible Sums Difference.md @@ -17,7 +17,7 @@ This ensures O(n) time and O(1) extra space. 4. Else → num1 += i 5. Return num1 - num2 -## code -- +## Code -- ``` class Solution { public: From 9dfdcb4a793c50c44874476ad995d7e7bddbf769 Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Mon, 6 Oct 2025 21:25:22 +0530 Subject: [PATCH 041/135] Create pull request template for C++ solutions Add a pull request template for C++ solutions with sections for intuition, approach, code solution, and related issues. --- .github/pull_request_template.md | 33 ++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 .github/pull_request_template.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..575af0f --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,33 @@ +### Intuition + + + + + +### Approach + + + + +## Code Solution (C++) + +```cpp +// Paste your C++ solution here + // Your code here + + +``` + + + + +## Related Issues + + + + +**By submitting this PR, I confirm that:** +- [ ] This is my original work not totally AI genearted +- [ ] I have tested the solution thoroughly on leetcode +- [ ] I have maintained proper PR description format +- [ ] This is a meaningful contribution, not spam From 055f5e99d193d7d62de0a8e7826ae983ef7cf31c Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Mon, 6 Oct 2025 21:28:25 +0530 Subject: [PATCH 042/135] Revise pull request template for clarity Updated pull request template to clarify sections. --- .github/pull_request_template.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 575af0f..b746b43 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,19 +1,18 @@ ### Intuition - + ### Approach - + ## Code Solution (C++) ```cpp -// Paste your C++ solution here - // Your code here + // Your code goes here ``` From 1c0da4ebc0d137fe8b05b12548099cede367d670 Mon Sep 17 00:00:00 2001 From: Lochit-Vinay Date: Mon, 6 Oct 2025 22:02:55 +0530 Subject: [PATCH 043/135] Divisible and Non-Divisible Sum Differences --- 2894. Divisible and Non-Divisible SumDifferences.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 2894. Divisible and Non-Divisible SumDifferences.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 From 8e46fb651b734357a893ed4cac9e1fa1bbc5d578 Mon Sep 17 00:00:00 2001 From: Subrat Kumar Behera <118915829+Subratkb02@users.noreply.github.com> Date: Mon, 6 Oct 2025 22:43:19 +0530 Subject: [PATCH 044/135] Update maximum-product-subarray.cpp --- maximum-product-subarray.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/maximum-product-subarray.cpp b/maximum-product-subarray.cpp index b0060b4..41e13cb 100644 --- a/maximum-product-subarray.cpp +++ b/maximum-product-subarray.cpp @@ -1,3 +1,6 @@ +// 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) { From 0501dc5b56e28744d2b9550694604c4879728f6a Mon Sep 17 00:00:00 2001 From: Ishika Sunil <39624382+ishika9@users.noreply.github.com> Date: Mon, 6 Oct 2025 23:08:25 +0530 Subject: [PATCH 045/135] Create 355. Design Twitter.cpp solves issue #138 --- 355. Design Twitter.cpp | 48 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 355. Design Twitter.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); + */ From 5394a158adc9e2877074f11086bb31f482eabf67 Mon Sep 17 00:00:00 2001 From: Lochit-Vinay Date: Tue, 7 Oct 2025 10:31:59 +0530 Subject: [PATCH 046/135] Find Words Containing Character --- 2942. Find Words Containing Character.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 2942. Find Words Containing Character.cpp 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 Date: Tue, 7 Oct 2025 13:14:30 +0530 Subject: [PATCH 047/135] Rename maximum-product-subarray.cpp to 152. Maximum-Product-Subarray.cpp --- maximum-product-subarray.cpp => 152. Maximum-Product-Subarray.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename maximum-product-subarray.cpp => 152. Maximum-Product-Subarray.cpp (100%) diff --git a/maximum-product-subarray.cpp b/152. Maximum-Product-Subarray.cpp similarity index 100% rename from maximum-product-subarray.cpp rename to 152. Maximum-Product-Subarray.cpp From e024346bc7111e4c34084562b8e56b187648ae36 Mon Sep 17 00:00:00 2001 From: Rajanya Saha Date: Tue, 7 Oct 2025 14:06:38 +0530 Subject: [PATCH 048/135] 2894. Divisible and Non-divisible Sums Difference.cpp --- ...ible and Non-divisible Sums Difference.cpp | 13 +++++++ ...sible and Non-divisible Sums Difference.md | 35 ------------------- 2 files changed, 13 insertions(+), 35 deletions(-) create mode 100644 2894. Divisible and Non-divisible Sums Difference.cpp delete mode 100644 2894. Divisible and Non-divisible Sums Difference.md 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/2894. Divisible and Non-divisible Sums Difference.md b/2894. Divisible and Non-divisible Sums Difference.md deleted file mode 100644 index cf6828a..0000000 --- a/2894. Divisible and Non-divisible Sums Difference.md +++ /dev/null @@ -1,35 +0,0 @@ -## Appreach -- -We are separating the total range [1…n] into two complementary sets: -Multiples of m -Non-multiples of m - -• The trick is simple -- -Loop through each number once. -If it’s divisible by m, add it to one sum (num2). -Otherwise, add to the other sum (num1). -Finally, return their difference. -This ensures O(n) time and O(1) extra space. - -## Intuition -- -1. Initialize num1 = 0, num2 = 0 -2. Loop i from 1 to n -3. If i % m == 0 → num2 += i -4. Else → num1 += i -5. Return num1 - num2 - -## Code -- -``` -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; - } -}; -``` From 599eab6f74726f52d823422baa38394f2b2edfe1 Mon Sep 17 00:00:00 2001 From: Dhanush Date: Tue, 7 Oct 2025 16:51:29 +0530 Subject: [PATCH 049/135] 3355. Zero Array Transformation I.cpp Solves Issue #94 Approach Use a difference array diff[] to mark increments and decrements. For each query [l,r], we do: diff[l]+=1 , diff[r+1]-=1 (only if r+1 coverage at that point in the prefix sum, return false. If this never happens, return true. Time Complexity -Making Difference Array -> O(q) => q = number of queries -Prefix Sum -> O(n) => n = size of nums[] array Total = O(n+q) Space Complexity -Array diff[] of size n+1 -> O(n) Total = O(n) Intuition The problem asks whether we can transform an array nums into a Zero Array (all elements become 0) by applying a series of queries. Each query [l,r] allows us to decrement any subset of indices within that range by 1. If an index is covered by multiple queries, it can be decremented multiple times. So for each index i, we need to check: If the number of queries covering i >= nums[i] If yes, we can reduce nums[i] to 0. Solution #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; } }; --- 3355. Zero Array Transformation I.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 3355. Zero Array Transformation I.cpp 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; + } +}; From 88c43373f7af538a3d52fb3050fd4487622ff2f8 Mon Sep 17 00:00:00 2001 From: Amber Mishra <72464515+Amber-Mishra-2003@users.noreply.github.com> Date: Thu, 9 Oct 2025 22:25:20 +0530 Subject: [PATCH 050/135] Create 3341. Find Minimum Time to Reach Last Room I.cpp --- ...Find Minimum Time to Reach Last Room I.cpp | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 3341. Find Minimum Time to Reach Last Room I.cpp 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..e394c40 --- /dev/null +++ b/3341. Find Minimum Time to Reach Last Room I.cpp @@ -0,0 +1,53 @@ +#include +using namespace std; +using ll = long long; +struct Node { + int r, c; + ll t; +}; +struct Cmp { + bool operator()(const Node &a, const Node &b) const { + return a.t > b.t; + } +}; +ll minTimeToReach(vector>& moveTime) { + int n = moveTime.size(); + int m = moveTime[0].size(); + const ll INF = LLONG_MAX / 4; + 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; + ll arrival = max(moveTime[nr][nc], cur.t) + 1; + if (arrival < dist[nr][nc]) { + dist[nr][nc] = arrival; + pq.push({nr, nc, arrival}); + } + } + } + return dist[n - 1][m - 1]; +} +int main() { + int n, m; + cin >> n >> m; + vector> moveTime(n, vector(m)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + cin >> moveTime[i][j]; + } + } + ll res = minTimeToReach(moveTime); + cout << res << "\n"; + return 0; +} From 3bb23f67555815c45da2841bb61c8590fd0fea6b Mon Sep 17 00:00:00 2001 From: Amber Mishra <72464515+Amber-Mishra-2003@users.noreply.github.com> Date: Fri, 10 Oct 2025 14:24:58 +0530 Subject: [PATCH 051/135] Update 3341. Find Minimum Time to Reach Last Room I.cpp --- ...Find Minimum Time to Reach Last Room I.cpp | 91 +++++++++---------- 1 file changed, 41 insertions(+), 50 deletions(-) diff --git a/3341. Find Minimum Time to Reach Last Room I.cpp b/3341. Find Minimum Time to Reach Last Room I.cpp index e394c40..21f5536 100644 --- a/3341. Find Minimum Time to Reach Last Room I.cpp +++ b/3341. Find Minimum Time to Reach Last Room I.cpp @@ -1,53 +1,44 @@ -#include -using namespace std; -using ll = long long; -struct Node { - int r, c; - ll t; -}; -struct Cmp { - bool operator()(const Node &a, const Node &b) const { - return a.t > b.t; - } -}; -ll minTimeToReach(vector>& moveTime) { - int n = moveTime.size(); - int m = moveTime[0].size(); - const ll INF = LLONG_MAX / 4; - 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; - ll arrival = max(moveTime[nr][nc], cur.t) + 1; - if (arrival < dist[nr][nc]) { - dist[nr][nc] = arrival; - pq.push({nr, nc, arrival}); - } +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; } - } - return dist[n - 1][m - 1]; -} -int main() { - int n, m; - cin >> n >> m; - vector> moveTime(n, vector(m)); - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - cin >> moveTime[i][j]; + }; + + 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; } - ll res = minTimeToReach(moveTime); - cout << res << "\n"; - return 0; -} +}; From f490da28e621201998dddb7105c743eaf24fcdf3 Mon Sep 17 00:00:00 2001 From: Pralayesh Mukherjee <132552681+PralayeshMukherjee@users.noreply.github.com> Date: Fri, 10 Oct 2025 20:37:41 +0530 Subject: [PATCH 052/135] Create Jump Game II.cpp this is the optimal solution of jump game II in cpp --- Jump Game II.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Jump Game II.cpp diff --git a/Jump Game II.cpp b/Jump Game II.cpp new file mode 100644 index 0000000..79e8e00 --- /dev/null +++ b/Jump Game II.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int jump(vector& nums) { + int right = 0, left = 0, steps = 0; + while(right Date: Fri, 10 Oct 2025 20:44:56 +0530 Subject: [PATCH 053/135] Rename Jump Game II.cpp to 45.Jump Game II.cpp --- Jump Game II.cpp => 45.Jump Game II.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Jump Game II.cpp => 45.Jump Game II.cpp (100%) diff --git a/Jump Game II.cpp b/45.Jump Game II.cpp similarity index 100% rename from Jump Game II.cpp rename to 45.Jump Game II.cpp From fb9fd2ff8b8b40235887ecc12318cc683b3ae08a Mon Sep 17 00:00:00 2001 From: Pralayesh Mukherjee <132552681+PralayeshMukherjee@users.noreply.github.com> Date: Fri, 10 Oct 2025 20:58:19 +0530 Subject: [PATCH 054/135] Create 55. Jump Game.cpp this is the solution --- 55. Jump Game.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 55. Jump Game.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; + } +}; From 1eda5c1e55a370fbdf57de46ccc14e3efa72cd59 Mon Sep 17 00:00:00 2001 From: Pralayesh Mukherjee <132552681+PralayeshMukherjee@users.noreply.github.com> Date: Fri, 10 Oct 2025 21:06:28 +0530 Subject: [PATCH 055/135] Create 678. Valid Parenthesis String.cpp solution of the problem --- 678. Valid Parenthesis String.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 678. Valid Parenthesis String.cpp diff --git a/678. Valid Parenthesis String.cpp b/678. Valid Parenthesis String.cpp new file mode 100644 index 0000000..cf032fd --- /dev/null +++ b/678. Valid Parenthesis String.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + bool checkValidString(string s) { + int min=0,max=0; + for(int i=0;i Date: Fri, 10 Oct 2025 21:41:47 +0530 Subject: [PATCH 056/135] Added C++ solution for course schedule leetcode problem --- 206.Course Schedule.cpp | 67 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 206.Course Schedule.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 From 7c653d83b9ae443c803170ef9cc0dffa5243d760 Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Fri, 10 Oct 2025 23:04:06 +0530 Subject: [PATCH 057/135] Delete 678. Valid Parenthesis String.cpp --- 678. Valid Parenthesis String.cpp | 21 --------------------- 1 file changed, 21 deletions(-) delete mode 100644 678. Valid Parenthesis String.cpp diff --git a/678. Valid Parenthesis String.cpp b/678. Valid Parenthesis String.cpp deleted file mode 100644 index cf032fd..0000000 --- a/678. Valid Parenthesis String.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution { -public: - bool checkValidString(string s) { - int min=0,max=0; - for(int i=0;i Date: Sat, 11 Oct 2025 00:23:07 +0530 Subject: [PATCH 058/135] Create 678. Valid Parenthesis String.cpp The most optimal solution of this problem on leetcode --- 678. Valid Parenthesis String.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 678. Valid Parenthesis String.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 Date: Sat, 11 Oct 2025 02:07:27 +0530 Subject: [PATCH 059/135] added 65.Valid Number soln --- 65.Valid Number.cpp | 52 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 65.Valid Number.cpp diff --git a/65.Valid Number.cpp b/65.Valid Number.cpp new file mode 100644 index 0000000..ecc4cea --- /dev/null +++ b/65.Valid Number.cpp @@ -0,0 +1,52 @@ +#include +using namespace std; + +class ValidNumber { +public: + bool isNumber(string s) { + int n = s.size(); + int i = 0; + + // Remove leading whitespaces + while (i < n && s[i] == ' ') i++; + + // Remove trailing whitespaces + int j = n - 1; + while (j >= 0 && s[j] == ' ') j--; + + if (i > j) return false; + + bool num = false; // At least one digit before e + bool dot = false; // Only one '.' + bool exp = false; // Only one 'e' or 'E' + + for (int k = i; k <= j; k++) { + char c = s[k]; + + if (isdigit(c)) { + num = true; + } + else if (c == '.') { + // Only one '.' and it can't appear after e + if (dot || exp) return false; + dot = true; + } + else if (c == 'e' || c == 'E') { + // e must appear only once and must follow a number + if (exp || !num) return false; + exp = true; + num = false; // Reset, we need digits after e + } + else if (c == '+' || c == '-') { + // Sign must be at start or immediately after e + if (k != i && s[k-1] != 'e' && s[k-1] != 'E') + return false; + } + else { + return false; + } + } + + return num; + } +}; From b6ae010851591d0fa07bc4fd6de5f07d8cd6aa69 Mon Sep 17 00:00:00 2001 From: Sarthak Jalan Date: Sat, 11 Oct 2025 02:41:54 +0530 Subject: [PATCH 060/135] =?UTF-8?q?CPP=20solution=20for=20Leetcode=203147?= =?UTF-8?q?=20=E2=80=94=20Taking=20Maximum=20Energy=20From=20the=20Mystic?= =?UTF-8?q?=20Dungeon?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- leetcode 3147.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 leetcode 3147.cpp diff --git a/leetcode 3147.cpp b/leetcode 3147.cpp new file mode 100644 index 0000000..8bb1a73 --- /dev/null +++ b/leetcode 3147.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; + } +}; From 725d250fd74943fc5bc3d6184bb20f9b4c05abd6 Mon Sep 17 00:00:00 2001 From: Sarthak Jalan Date: Sat, 11 Oct 2025 02:45:25 +0530 Subject: [PATCH 061/135] deleted old --- 65.Valid Number.cpp | 52 --------------------------------------------- 1 file changed, 52 deletions(-) delete mode 100644 65.Valid Number.cpp diff --git a/65.Valid Number.cpp b/65.Valid Number.cpp deleted file mode 100644 index ecc4cea..0000000 --- a/65.Valid Number.cpp +++ /dev/null @@ -1,52 +0,0 @@ -#include -using namespace std; - -class ValidNumber { -public: - bool isNumber(string s) { - int n = s.size(); - int i = 0; - - // Remove leading whitespaces - while (i < n && s[i] == ' ') i++; - - // Remove trailing whitespaces - int j = n - 1; - while (j >= 0 && s[j] == ' ') j--; - - if (i > j) return false; - - bool num = false; // At least one digit before e - bool dot = false; // Only one '.' - bool exp = false; // Only one 'e' or 'E' - - for (int k = i; k <= j; k++) { - char c = s[k]; - - if (isdigit(c)) { - num = true; - } - else if (c == '.') { - // Only one '.' and it can't appear after e - if (dot || exp) return false; - dot = true; - } - else if (c == 'e' || c == 'E') { - // e must appear only once and must follow a number - if (exp || !num) return false; - exp = true; - num = false; // Reset, we need digits after e - } - else if (c == '+' || c == '-') { - // Sign must be at start or immediately after e - if (k != i && s[k-1] != 'e' && s[k-1] != 'E') - return false; - } - else { - return false; - } - } - - return num; - } -}; From ccd32cc0bf2d16ac4a45805acc14d292dc4d16aa Mon Sep 17 00:00:00 2001 From: Sarthak Jalan Date: Sat, 11 Oct 2025 09:05:19 +0530 Subject: [PATCH 062/135] changed the name --- ....cpp => 3147.Taking Maximum Energy From the Mystic Dungeon.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename leetcode 3147.cpp => 3147.Taking Maximum Energy From the Mystic Dungeon.cpp (100%) diff --git a/leetcode 3147.cpp b/3147.Taking Maximum Energy From the Mystic Dungeon.cpp similarity index 100% rename from leetcode 3147.cpp rename to 3147.Taking Maximum Energy From the Mystic Dungeon.cpp From f3aacbd260d32277f73922960ef7287ffdabd5f4 Mon Sep 17 00:00:00 2001 From: VN1702 Date: Sat, 11 Oct 2025 12:24:06 +0530 Subject: [PATCH 063/135] Containing Nearby Duplicate Problem Added --- 3704.NearbyDuplicate.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 3704.NearbyDuplicate.cpp diff --git a/3704.NearbyDuplicate.cpp b/3704.NearbyDuplicate.cpp new file mode 100644 index 0000000..fb85324 --- /dev/null +++ b/3704.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 Date: Sun, 12 Oct 2025 11:07:04 +0530 Subject: [PATCH 064/135] Update pull request template --- .github/pull_request_template.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index b746b43..ef5a10a 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,9 +1,11 @@ +**PR Title Format:** Problem no.Problem name.cpp + + ### Intuition - ### Approach @@ -14,10 +16,7 @@ ```cpp // Your code goes here - -``` - - +``` ## Related Issues @@ -26,7 +25,7 @@ **By submitting this PR, I confirm that:** -- [ ] This is my original work not totally AI genearted +- [ ] 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 +- [ ] This is a meaningful contribution, not spam \ No newline at end of file From 4354e946f8c3769bd661a146281e86f65d108423 Mon Sep 17 00:00:00 2001 From: VN1702 Date: Sun, 12 Oct 2025 15:42:44 +0530 Subject: [PATCH 065/135] Added longest substring without repeating characters problem --- 3705.Longest substring | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 3705.Longest substring diff --git a/3705.Longest substring b/3705.Longest substring new file mode 100644 index 0000000..54dc70e --- /dev/null +++ b/3705.Longest substring @@ -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; + } +}; \ No newline at end of file From 24367b87e1341c2b895a468228338d7450d3cfdd Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Sun, 12 Oct 2025 19:32:44 +0530 Subject: [PATCH 066/135] Delete 3704.NearbyDuplicate.cpp --- 3704.NearbyDuplicate.cpp | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 3704.NearbyDuplicate.cpp diff --git a/3704.NearbyDuplicate.cpp b/3704.NearbyDuplicate.cpp deleted file mode 100644 index fb85324..0000000 --- a/3704.NearbyDuplicate.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#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 Date: Sun, 12 Oct 2025 19:34:21 +0530 Subject: [PATCH 067/135] Rename file to match problem description --- ... => 3705. Longest substring without repeating characters.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename 3705.Longest substring => 3705. Longest substring without repeating characters.cpp (99%) diff --git a/3705.Longest substring b/3705. Longest substring without repeating characters.cpp similarity index 99% rename from 3705.Longest substring rename to 3705. Longest substring without repeating characters.cpp index 54dc70e..6254ce9 100644 --- a/3705.Longest substring +++ b/3705. Longest substring without repeating characters.cpp @@ -24,4 +24,4 @@ class Solution { return maxLength; } -}; \ No newline at end of file +}; From 7abadf5aeaf88f7b2a865412d13493e901653999 Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Sun, 12 Oct 2025 19:38:03 +0530 Subject: [PATCH 068/135] Rename file from 3704.NearbyDuplicate.cpp to 219.NearbyDuplicate.cpp --- 3704.NearbyDuplicate.cpp => 219.NearbyDuplicate.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename 3704.NearbyDuplicate.cpp => 219.NearbyDuplicate.cpp (99%) diff --git a/3704.NearbyDuplicate.cpp b/219.NearbyDuplicate.cpp similarity index 99% rename from 3704.NearbyDuplicate.cpp rename to 219.NearbyDuplicate.cpp index fb85324..22e8fb5 100644 --- a/3704.NearbyDuplicate.cpp +++ b/219.NearbyDuplicate.cpp @@ -21,4 +21,4 @@ class Solution { return false; } -}; \ No newline at end of file +}; From 99761153b2a1e4a267331b8e70e7310d9f480928 Mon Sep 17 00:00:00 2001 From: Rajanya Saha Date: Tue, 14 Oct 2025 18:10:51 +0530 Subject: [PATCH 069/135] 73. Set Matrix Zeroes.cpp --- 73. Set Matrix Zeroes.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 73. Set Matrix Zeroes.cpp diff --git a/73. Set Matrix Zeroes.cpp b/73. Set Matrix Zeroes.cpp new file mode 100644 index 0000000..489b094 --- /dev/null +++ b/73. Set Matrix Zeroes.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + void setZeroes(vector>& 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; + } + } + } +}; From c8c3a8b74df6751936e923903b6e672538a03615 Mon Sep 17 00:00:00 2001 From: rjvrr Date: Wed, 15 Oct 2025 15:54:56 +0530 Subject: [PATCH 070/135] Add triangle classification solution --- Type of Triangle.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Type of Triangle.cpp diff --git a/Type of Triangle.cpp b/Type of Triangle.cpp new file mode 100644 index 0000000..7f00b43 --- /dev/null +++ b/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"; + } + } +}; + From 5ecb367aa203eca557601ed5de559fd9a9794295 Mon Sep 17 00:00:00 2001 From: Tannu Singh Date: Wed, 15 Oct 2025 17:20:01 +0530 Subject: [PATCH 071/135] Add solution and explanation for Leetcode 3372 --- max_target_nodes.cpp | 50 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 max_target_nodes.cpp diff --git a/max_target_nodes.cpp b/max_target_nodes.cpp new file mode 100644 index 0000000..49c2c2a --- /dev/null +++ b/max_target_nodes.cpp @@ -0,0 +1,50 @@ +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; + } +}; \ No newline at end of file From 753ca0165a3fa344d984808dd7ed8d39e0f2262b Mon Sep 17 00:00:00 2001 From: Rishan Menezes Date: Wed, 15 Oct 2025 20:44:26 +0530 Subject: [PATCH 072/135] Add: 3362. Zero Array Transformation III --- 3362. Zero Array Transformation III.cpp | 54 +++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 3362. Zero Array Transformation III.cpp diff --git a/3362. Zero Array Transformation III.cpp b/3362. Zero Array Transformation III.cpp new file mode 100644 index 0000000..b4421d4 --- /dev/null +++ b/3362. Zero Array Transformation III.cpp @@ -0,0 +1,54 @@ +```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 `dp[i]` be the minimum operations to make `nums[0...i]` zero. This seems complicated because an operation at `i` affects `i+1`. + +// 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]; + } + nums[i] = 0; // nums[i] is now zero + } + } + return total_operations; + } +}; +``` \ No newline at end of file From 4169246098776ed74c625fe194a94abafc8cb457 Mon Sep 17 00:00:00 2001 From: Rishan Menezes Date: Wed, 15 Oct 2025 20:55:15 +0530 Subject: [PATCH 073/135] Fix: Address code review comments for 3362. Zero Array Transformation III --- 3362. Zero Array Transformation III.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/3362. Zero Array Transformation III.cpp b/3362. Zero Array Transformation III.cpp index b4421d4..26e0d3a 100644 --- a/3362. Zero Array Transformation III.cpp +++ b/3362. Zero Array Transformation III.cpp @@ -9,8 +9,6 @@ // 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 `dp[i]` be the minimum operations to make `nums[0...i]` zero. This seems complicated because an operation at `i` affects `i+1`. - // 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. @@ -44,6 +42,10 @@ class Solution { 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 } From cb3edbd1080712c2815e703badcfb717708b4e77 Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Wed, 15 Oct 2025 20:55:32 +0530 Subject: [PATCH 074/135] added .cpp extension to those files which hvn't extension before on --- ...Tree or Identical Tree => 100. same Tree or Identical Tree.cpp | 0 101. Symetric Tree => 101. Symetric Tree.cpp | 0 ...e in Linked List => 1019. Next Greater Node in Linked List.cpp | 0 ... Order Traversal => 102. Binary Tree level Order Traversal.cpp | 0 ... Depth of Binary Tree => 104. Maximum Depth of Binary Tree.cpp | 0 110. Blanced Binary Tree => 110. Blanced Binary Tree.cpp | 0 113. Path Sum 2 => 113. Path Sum 2.cpp | 0 ... to Linked List => 114. Flatten Binary Tree to Linked List.cpp | 0 118. Pascal Triangle => 118. Pascal Triangle.cpp | 0 134. Gas Station => 134. Gas Station.cpp | 0 ... with random pointer => 138. Copy List with random pointer.cpp | 0 ...ostOrder Traversal => 145. Binary tree PostOrder Traversal.cpp | 0 15. 3Sum => 15. 3Sum.cpp | 0 1512. Number of Good Pairs => 1512. Number of Good Pairs.cpp | 0 155. Min Stack => 155. Min Stack.cpp | 0 ...of Two Linked List => 160. Intersection of Two Linked List.cpp | 0 ...Sums => 1605. Find valid matrix Given Row and Coloumn Sums.cpp | 0 162. Find Peak Element => 162. Find Peak Element.cpp | 0 ...ivalent => 1662. Check if Two String Arrays are Equivalent.cpp | 0 ...in Leetcode bank => 1716. Calculate Money in Leetcode bank.cpp | 0 191. Number of 1 Bits => 191. Number of 1 Bits.cpp | 0 ...nt => 2058. Find min and max number between critical Point.cpp | 0 ...ding Spaces to a String => 2109. Adding Spaces to a String.cpp | 0 ...s between two Zeros => 2181. Merge Nodes between two Zeros.cpp | 0 ...s in an Array => 2210. count Hills and valleys in an Array.cpp | 0 ...ent Stack Using Queues => 225.Implement Stack Using Queues.cpp | 0 230. Kth Smallest Element => 230. Kth Smallest Element.cpp | 0 ...ent Queue using Stacks => 232.Implement Queue using Stacks.cpp | 0 ...ree => 235. Lowest Common Ancestor of a Binary Search Tree.cpp | 0 ...inary tree => 236. lowest Common Ancestor of A Binary tree.cpp | 0 239. Sliding Window Maximum => 239. Sliding Window Maximum.cpp | 0 ...ind The Duplicate number => 287. Find The Duplicate number.cpp | 0 ...cters => 3. Longest Substring Without Repeating Characters.cpp | 0 ...Longest Valid Parentheses => 32. Longest Valid Parentheses.cpp | 0 338.Counting Bits => 338.Counting Bits.cpp | 0 ...4. Find First and Last Position of Element in Sorted Array.cpp | 0 3477. Fruits Into Baskets II => 3477. Fruits Into Baskets II.cpp | 0 3479.Fruits Into Baskets 3 => 3479.Fruits Into Baskets 3.cpp | 0 35. Search Insert Position => 35. Search Insert Position.cpp | 0 389. Find the Difference => 389. Find the Difference.cpp | 0 407. Trapping Rain Water II => 407. Trapping Rain Water II.cpp | 0 48. Rotate image => 48. Rotate image.cpp | 0 ... Diameter of Binary Tree => 543. Diameter of Binary Tree.cpp | 0 ...ords in a String III => 557. Reverse Words in a String III.cpp | 0 61. Rotate List => 61. Rotate List.cpp | 0 ...um IV - Input is a BST => 653. Two Sum IV - Input is a BST.cpp | 0 70. Climbing Stairs => 70. Climbing Stairs.cpp | 0 724. Find Pivot Index => 724. Find Pivot Index.cpp | 0 ...it Linked list in parts => 725. Split Linked list in parts.cpp | 0 763. Partition Labels => 763. Partition Labels.cpp | 0 ...from Sorted List => 83. Remove Duplicates from Sorted List.cpp | 0 ...ctangle in Histogram => 84. Largest Rectangle in Histogram.cpp | 0 ...in a Mountain Array => 852. peak Index in a Mountain Array.cpp | 0 853. Car Fleet I => 853. Car Fleet I.cpp | 0 867. Transpose Matrix => 867. Transpose Matrix.cpp | 0 875.Koko Eating Bananas => 875.Koko Eating Bananas.cpp | 0 89. Grey Code => 89. Grey Code.cpp | 0 896.Monotonic Array => 896.Monotonic Array.cpp | 0 92. Reverse Linked List II => 92. Reverse Linked List II.cpp | 0 ...date Binary Search Tree => 98. Validate Binary Search Tree.cpp | 0 60 files changed, 0 insertions(+), 0 deletions(-) rename 100. same Tree or Identical Tree => 100. same Tree or Identical Tree.cpp (100%) rename 101. Symetric Tree => 101. Symetric Tree.cpp (100%) rename 1019. Next Greater Node in Linked List => 1019. Next Greater Node in Linked List.cpp (100%) rename 102. Binary Tree level Order Traversal => 102. Binary Tree level Order Traversal.cpp (100%) rename 104. Maximum Depth of Binary Tree => 104. Maximum Depth of Binary Tree.cpp (100%) rename 110. Blanced Binary Tree => 110. Blanced Binary Tree.cpp (100%) rename 113. Path Sum 2 => 113. Path Sum 2.cpp (100%) rename 114. Flatten Binary Tree to Linked List => 114. Flatten Binary Tree to Linked List.cpp (100%) rename 118. Pascal Triangle => 118. Pascal Triangle.cpp (100%) rename 134. Gas Station => 134. Gas Station.cpp (100%) rename 138. Copy List with random pointer => 138. Copy List with random pointer.cpp (100%) rename 145. Binary tree PostOrder Traversal => 145. Binary tree PostOrder Traversal.cpp (100%) rename 15. 3Sum => 15. 3Sum.cpp (100%) rename 1512. Number of Good Pairs => 1512. Number of Good Pairs.cpp (100%) rename 155. Min Stack => 155. Min Stack.cpp (100%) rename 160. Intersection of Two Linked List => 160. Intersection of Two Linked List.cpp (100%) rename 1605. Find valid matrix Given Row and Coloumn Sums => 1605. Find valid matrix Given Row and Coloumn Sums.cpp (100%) rename 162. Find Peak Element => 162. Find Peak Element.cpp (100%) rename 1662. Check if Two String Arrays are Equivalent => 1662. Check if Two String Arrays are Equivalent.cpp (100%) rename 1716. Calculate Money in Leetcode bank => 1716. Calculate Money in Leetcode bank.cpp (100%) rename 191. Number of 1 Bits => 191. Number of 1 Bits.cpp (100%) rename 2058. Find min and max number between critical Point => 2058. Find min and max number between critical Point.cpp (100%) rename 2109. Adding Spaces to a String => 2109. Adding Spaces to a String.cpp (100%) rename 2181. Merge Nodes between two Zeros => 2181. Merge Nodes between two Zeros.cpp (100%) rename 2210. count Hills and valleys in an Array => 2210. count Hills and valleys in an Array.cpp (100%) rename 225.Implement Stack Using Queues => 225.Implement Stack Using Queues.cpp (100%) rename 230. Kth Smallest Element => 230. Kth Smallest Element.cpp (100%) rename 232.Implement Queue using Stacks => 232.Implement Queue using Stacks.cpp (100%) rename 235. Lowest Common Ancestor of a Binary Search Tree => 235. Lowest Common Ancestor of a Binary Search Tree.cpp (100%) rename 236. lowest Common Ancestor of A Binary tree => 236. lowest Common Ancestor of A Binary tree.cpp (100%) rename 239. Sliding Window Maximum => 239. Sliding Window Maximum.cpp (100%) rename 287. Find The Duplicate number => 287. Find The Duplicate number.cpp (100%) rename 3. Longest Substring Without Repeating Characters => 3. Longest Substring Without Repeating Characters.cpp (100%) rename 32. Longest Valid Parentheses => 32. Longest Valid Parentheses.cpp (100%) rename 338.Counting Bits => 338.Counting Bits.cpp (100%) rename 34. Find First and Last Position of Element in Sorted Array => 34. Find First and Last Position of Element in Sorted Array.cpp (100%) rename 3477. Fruits Into Baskets II => 3477. Fruits Into Baskets II.cpp (100%) rename 3479.Fruits Into Baskets 3 => 3479.Fruits Into Baskets 3.cpp (100%) rename 35. Search Insert Position => 35. Search Insert Position.cpp (100%) rename 389. Find the Difference => 389. Find the Difference.cpp (100%) rename 407. Trapping Rain Water II => 407. Trapping Rain Water II.cpp (100%) rename 48. Rotate image => 48. Rotate image.cpp (100%) rename 543. Diameter of Binary Tree => 543. Diameter of Binary Tree.cpp (100%) rename 557. Reverse Words in a String III => 557. Reverse Words in a String III.cpp (100%) rename 61. Rotate List => 61. Rotate List.cpp (100%) rename 653. Two Sum IV - Input is a BST => 653. Two Sum IV - Input is a BST.cpp (100%) rename 70. Climbing Stairs => 70. Climbing Stairs.cpp (100%) rename 724. Find Pivot Index => 724. Find Pivot Index.cpp (100%) rename 725. Split Linked list in parts => 725. Split Linked list in parts.cpp (100%) rename 763. Partition Labels => 763. Partition Labels.cpp (100%) rename 83. Remove Duplicates from Sorted List => 83. Remove Duplicates from Sorted List.cpp (100%) rename 84. Largest Rectangle in Histogram => 84. Largest Rectangle in Histogram.cpp (100%) rename 852. peak Index in a Mountain Array => 852. peak Index in a Mountain Array.cpp (100%) rename 853. Car Fleet I => 853. Car Fleet I.cpp (100%) rename 867. Transpose Matrix => 867. Transpose Matrix.cpp (100%) rename 875.Koko Eating Bananas => 875.Koko Eating Bananas.cpp (100%) rename 89. Grey Code => 89. Grey Code.cpp (100%) rename 896.Monotonic Array => 896.Monotonic Array.cpp (100%) rename 92. Reverse Linked List II => 92. Reverse Linked List II.cpp (100%) rename 98. Validate Binary Search Tree => 98. Validate Binary Search Tree.cpp (100%) 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/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/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/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/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/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/155. Min Stack b/155. Min Stack.cpp similarity index 100% rename from 155. Min Stack rename to 155. Min Stack.cpp diff --git a/160. Intersection of Two Linked List b/160. Intersection of Two Linked List.cpp similarity index 100% rename from 160. Intersection of Two Linked List rename to 160. Intersection of Two Linked List.cpp diff --git a/1605. Find valid matrix Given Row and Coloumn Sums b/1605. Find valid matrix Given Row and Coloumn Sums.cpp similarity index 100% rename from 1605. Find valid matrix Given Row and Coloumn Sums rename to 1605. Find valid matrix Given Row and Coloumn Sums.cpp diff --git a/162. Find Peak Element b/162. Find Peak Element.cpp similarity index 100% rename from 162. Find Peak Element rename to 162. Find Peak Element.cpp diff --git a/1662. Check if Two String Arrays are Equivalent b/1662. Check if Two String Arrays are Equivalent.cpp similarity index 100% rename from 1662. Check if Two String Arrays are Equivalent rename to 1662. Check if Two String Arrays are Equivalent.cpp diff --git a/1716. Calculate Money in Leetcode bank b/1716. Calculate Money in Leetcode bank.cpp similarity index 100% rename from 1716. Calculate Money in Leetcode bank rename to 1716. Calculate Money in Leetcode bank.cpp 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/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/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/2210. count Hills and valleys in an Array b/2210. count Hills and valleys in an Array.cpp similarity index 100% rename from 2210. count Hills and valleys in an Array rename to 2210. count Hills and valleys in an Array.cpp diff --git a/225.Implement Stack Using Queues b/225.Implement Stack Using Queues.cpp similarity index 100% rename from 225.Implement Stack Using Queues rename to 225.Implement Stack Using Queues.cpp 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/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/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/3. Longest Substring Without Repeating Characters b/3. Longest Substring Without Repeating Characters.cpp similarity index 100% rename from 3. Longest Substring Without Repeating Characters rename to 3. Longest Substring Without Repeating Characters.cpp 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/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/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/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/48. Rotate image b/48. Rotate image.cpp similarity index 100% rename from 48. Rotate image rename to 48. Rotate image.cpp 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/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/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/70. Climbing Stairs b/70. Climbing Stairs.cpp similarity index 100% rename from 70. Climbing Stairs rename to 70. Climbing Stairs.cpp diff --git a/724. Find Pivot Index b/724. Find Pivot Index.cpp similarity index 100% rename from 724. Find Pivot Index rename to 724. Find Pivot Index.cpp diff --git a/725. Split Linked list in parts b/725. Split Linked list in parts.cpp similarity index 100% rename from 725. Split Linked list in parts rename to 725. Split Linked list in parts.cpp 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/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/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/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 From 51c1825b4b217b38656305e85e7a1dadee25467f Mon Sep 17 00:00:00 2001 From: subho Date: Thu, 16 Oct 2025 18:46:16 +0530 Subject: [PATCH 075/135] Implement solution for maximum task assignment problem --- ...Maximum Number of Tasks You Can Assign.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 2071. Maximum Number of Tasks You Can Assign.cpp 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; + + + } +}; From 0be5dfa6f199cabee4f7161d3c5762b0b4538970 Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Thu, 16 Oct 2025 18:57:12 +0530 Subject: [PATCH 076/135] Rename FloydCycle.cpp to 141. FloydCycle.cpp --- FloydCycle.cpp => 141. FloydCycle.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename FloydCycle.cpp => 141. FloydCycle.cpp (100%) diff --git a/FloydCycle.cpp b/141. FloydCycle.cpp similarity index 100% rename from FloydCycle.cpp rename to 141. FloydCycle.cpp From cdd35b2451aa63d98608d43de10f1a91465d84f3 Mon Sep 17 00:00:00 2001 From: Rajbir Singh Date: Thu, 16 Oct 2025 20:42:37 +0530 Subject: [PATCH 077/135] Rename Type of Triangle.cpp to 3024.Type of Triangle.cpp --- Type of Triangle.cpp => 3024.Type of Triangle.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Type of Triangle.cpp => 3024.Type of Triangle.cpp (100%) diff --git a/Type of Triangle.cpp b/3024.Type of Triangle.cpp similarity index 100% rename from Type of Triangle.cpp rename to 3024.Type of Triangle.cpp From f6c49252a882cb5cb426653ae171ddcd3ea71ac4 Mon Sep 17 00:00:00 2001 From: subho Date: Thu, 16 Oct 2025 23:15:45 +0530 Subject: [PATCH 078/135] Add subsets function to generate power set Implement a solution to generate all subsets of a given set. --- 78. Subsets.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 78. Subsets.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 Date: Fri, 17 Oct 2025 23:06:23 +0530 Subject: [PATCH 079/135] Implement solution for maximizing partitions in string --- ... Number of Partitions After Operations.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 3003. Maximize the Number of Partitions After Operations.cpp diff --git a/3003. Maximize the Number of Partitions After Operations.cpp b/3003. Maximize the Number of Partitions After Operations.cpp new file mode 100644 index 0000000..2e3c2c9 --- /dev/null +++ b/3003. Maximize the Number of Partitions After Operations.cpp @@ -0,0 +1,55 @@ +class Solution { +public: + typedef long long ll; + unordered_map 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); + } +}; From 97e8fd2f7d4573ba8601bc82666f4ae3b89b5425 Mon Sep 17 00:00:00 2001 From: sunidhi Date: Sat, 18 Oct 2025 00:21:13 +0530 Subject: [PATCH 080/135] Added C++ solution for Maximum Sum of Node Values (Binary Tree) --- Maximum sum of node values.cpp | 65 ++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Maximum sum of node values.cpp diff --git a/Maximum sum of node values.cpp b/Maximum sum of node values.cpp new file mode 100644 index 0000000..b91d489 --- /dev/null +++ b/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; +} From 4be27871a9428bea0001498cf91bc235331dd991 Mon Sep 17 00:00:00 2001 From: Ayush Sharma Date: Sat, 18 Oct 2025 13:31:12 +0530 Subject: [PATCH 081/135] Add solution for 8. String to Integer (atoi) in C++ --- 8. String to Integer (atoi).cpp | 38 +++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 8. String to Integer (atoi).cpp diff --git a/8. String to Integer (atoi).cpp b/8. String to Integer (atoi).cpp new file mode 100644 index 0000000..6616f7b --- /dev/null +++ b/8. String to Integer (atoi).cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int myAtoi(string s) { + int l = s.length(); + int sign = 1, i = 0; + long long ans = 0; + + // trimming leading spaces + while (i < l && s[i] == ' ') i++; + + + // sign check condition + if (i == l) + return 0; + if (s[i] == '-') { + sign = -1; + i++; + } else if (s[i] == '+') + i++; + + // converting characters to integer + while (i < l && isdigit(s[i])) { + int digit = s[i] - '0'; + ans = ans * 10 + digit; + + // overflow condition handling + if (sign == 1 && ans > 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 From 34bc22ec5477e785d080c93d72decb5c4d3ef38a Mon Sep 17 00:00:00 2001 From: Pralayesh Mukherjee <132552681+PralayeshMukherjee@users.noreply.github.com> Date: Sat, 18 Oct 2025 13:39:57 +0530 Subject: [PATCH 082/135] Implement solution for max consecutive ones problem --- 485. Max Consecutive Ones.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 485. Max Consecutive Ones.cpp diff --git a/485. Max Consecutive Ones.cpp b/485. Max Consecutive Ones.cpp new file mode 100644 index 0000000..2b77a15 --- /dev/null +++ b/485. Max Consecutive Ones.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + int max = 0; + int count = 0; + for(int i=0;i Date: Sat, 18 Oct 2025 18:06:11 +0530 Subject: [PATCH 083/135] 838. Push Dominoes.cpp --- 838. Push Dominoes.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 838. Push Dominoes.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; + } +}; From b78f5161f99a3e8714e68bfd080c2ee114eb062c Mon Sep 17 00:00:00 2001 From: Ayush Sharma Date: Sat, 18 Oct 2025 22:03:21 +0530 Subject: [PATCH 084/135] Add solution for 20. Valid Parentheses in C++ --- 20. Valid Parentheses.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 20. Valid Parentheses.cpp 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 From 7daacfef41499310d605cc2b88879b9e8a990ef2 Mon Sep 17 00:00:00 2001 From: Once-1296 Date: Sun, 19 Oct 2025 11:32:06 +0530 Subject: [PATCH 085/135] Added LC 3720 --- ...allest Permutation Greater Than Target.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 3720. Lexicographically Smallest Permutation Greater Than Target.cpp 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 From 7022013d3ab9a7e0b449af97ca8739d93f898f68 Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Sun, 19 Oct 2025 13:04:22 +0530 Subject: [PATCH 086/135] Add workflow to comment on merged pull requests --- .../workflows/pr-merged-automate-message.yml | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 .github/workflows/pr-merged-automate-message.yml 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 + }); From 88e542063c9e9f5781923835574d747ea22cc228 Mon Sep 17 00:00:00 2001 From: sarang80040 Date: Sun, 19 Oct 2025 13:34:07 +0530 Subject: [PATCH 087/135] Added solution for 2273. Find Resultant Array After Removing Anagrams --- ...esultant Array After Removing Anagrams.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 2273. Find Resultant Array After Removing Anagrams.cpp diff --git a/2273. Find Resultant Array After Removing Anagrams.cpp b/2273. Find Resultant Array After Removing Anagrams.cpp new file mode 100644 index 0000000..9b05e65 --- /dev/null +++ b/2273. Find Resultant Array After Removing Anagrams.cpp @@ -0,0 +1,23 @@ +class Solution +{ +public: + vector 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 From 351baa761b7e0b1b5b83b1ea3892e5e4574343f7 Mon Sep 17 00:00:00 2001 From: Samya-Agg Date: Sun, 19 Oct 2025 22:24:19 +0530 Subject: [PATCH 088/135] 1857_Largest_Color_Value_in_a_Directed_Graph.cpp --- ...argest_Color_Value_in_a_Directed_Graph.cpp | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 1857. Largest_Color_Value_in_a_Directed_Graph.cpp 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..fc468a0 --- /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; + +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 < n; i++) + if (indegree[i] == 0) + q.push(i); + + vector> count(n, vector(26, 0)); + int visited = 0, ans = 0; + + while (!q.empty()) { + int u = q.front(); + q.pop(); + visited++; + + 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 (visited == n) ? ans : -1; +} + +int main() { + string colors = "abaca"; + vector> edges = {{0,1}, {0,2}, {2,3}, {3,4}}; + cout << largestPathValue(colors, edges) << endl; + return 0; +} From 6541893ac5cd122d64b268b6b09cd1cfe0a28ac6 Mon Sep 17 00:00:00 2001 From: Samya-Agg Date: Sun, 19 Oct 2025 22:37:12 +0530 Subject: [PATCH 089/135] Updated solution for 1857 --- ...argest_Color_Value_in_a_Directed_Graph.cpp | 72 +++++++++---------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/1857. Largest_Color_Value_in_a_Directed_Graph.cpp b/1857. Largest_Color_Value_in_a_Directed_Graph.cpp index fc468a0..ac30f89 100644 --- a/1857. Largest_Color_Value_in_a_Directed_Graph.cpp +++ b/1857. Largest_Color_Value_in_a_Directed_Graph.cpp @@ -18,47 +18,47 @@ #include using namespace std; -int largestPathValue(string colors, vector>& edges) { - int n = colors.size(); - vector> graph(n); - vector indegree(n, 0); +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]]++; - } + + for (auto &e:edges) { + graph[e[0]].push_back(e[1]); + indegree[e[1]]++; + } - queue q; - for (int i = 0; i < n; i++) - if (indegree[i] == 0) - q.push(i); + + queue q; + for (int i=0;i> count(n, vector(26, 0)); - int visited = 0, ans = 0; + vector> count(n,vector(26, 0)); + int visited=0; + int ans=0; - while (!q.empty()) { - int u = q.front(); - q.pop(); - visited++; + while (!q.empty()) { + int u=q.front(); + q.pop(); + visited++; - 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); - } - } + int colorIdx=colors[u]-'a'; + count[u][colorIdx]++; + ans=max(ans,count[u][colorIdx]); - return (visited == n) ? ans : -1; -} + 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); + } + } -int main() { - string colors = "abaca"; - vector> edges = {{0,1}, {0,2}, {2,3}, {3,4}}; - cout << largestPathValue(colors, edges) << endl; - return 0; -} + return (visited==n)?ans:-1; + } +}; From 5f2b277375b92e5f1b15ff0d01dd1eb72349398d Mon Sep 17 00:00:00 2001 From: Samya-Agg Date: Sun, 19 Oct 2025 22:39:50 +0530 Subject: [PATCH 090/135] Updated solution for 1857 --- 1857. Largest_Color_Value_in_a_Directed_Graph.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/1857. Largest_Color_Value_in_a_Directed_Graph.cpp b/1857. Largest_Color_Value_in_a_Directed_Graph.cpp index ac30f89..beb8aa7 100644 --- a/1857. Largest_Color_Value_in_a_Directed_Graph.cpp +++ b/1857. Largest_Color_Value_in_a_Directed_Graph.cpp @@ -38,13 +38,13 @@ class Solution { q.push(i); vector> count(n,vector(26, 0)); - int visited=0; + int vis=0; int ans=0; while (!q.empty()) { int u=q.front(); q.pop(); - visited++; + vis++; int colorIdx=colors[u]-'a'; @@ -59,6 +59,6 @@ class Solution { } } - return (visited==n)?ans:-1; + return (vis==n)?ans:-1; } }; From 153b6d1a49f1d0cee1b4488ac6dad3ddd72e9f73 Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Mon, 20 Oct 2025 10:48:56 +0530 Subject: [PATCH 091/135] Rename Maximum sum of node values.cpp to 3068. Find the Maximum Sum of Node Values.cpp --- ...de values.cpp => 3068. Find the Maximum Sum of Node Values.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Maximum sum of node values.cpp => 3068. Find the Maximum Sum of Node Values.cpp (100%) diff --git a/Maximum sum of node values.cpp b/3068. Find the Maximum Sum of Node Values.cpp similarity index 100% rename from Maximum sum of node values.cpp rename to 3068. Find the Maximum Sum of Node Values.cpp From 5f0592b98839dcfb0a6760e69fa774485914ef16 Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Mon, 20 Oct 2025 10:53:25 +0530 Subject: [PATCH 092/135] Rename max_target_nodes.cpp to 99.Maximize the Number of Target Nodes After Connecting Trees.cpp --- ...ximize the Number of Target Nodes After Connecting Trees.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename max_target_nodes.cpp => 99.Maximize the Number of Target Nodes After Connecting Trees.cpp (99%) diff --git a/max_target_nodes.cpp b/99.Maximize the Number of Target Nodes After Connecting Trees.cpp similarity index 99% rename from max_target_nodes.cpp rename to 99.Maximize the Number of Target Nodes After Connecting Trees.cpp index 49c2c2a..389385f 100644 --- a/max_target_nodes.cpp +++ b/99.Maximize the Number of Target Nodes After Connecting Trees.cpp @@ -47,4 +47,4 @@ class Solution { } return count; } -}; \ No newline at end of file +}; From 3349499c8179fb6b140a3dbd3c6b20e4e0432201 Mon Sep 17 00:00:00 2001 From: aastikdas Date: Mon, 20 Oct 2025 11:09:13 +0530 Subject: [PATCH 093/135] contributed a question --- 123. Best time to buy or sell stock iii .cpp | 62 ++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 123. Best time to buy or sell stock iii .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..b461a1b --- /dev/null +++ b/123. Best time to buy or sell stock iii .cpp @@ -0,0 +1,62 @@ +/* +Problem + +You are given an array prices where prices[i] is the price of a given stock on day i. + +You can complete at most two transactions (a buy and a sell count as one transaction). You cannot hold more than one stock at a time. + +Return the maximum profit you can achieve. + +Approach + +We can use Dynamic Programming with states. + +We define four variables to track maximum profit in each state: + +firstBuy – Maximum profit after buying the first stock (negative because we spent money). + +firstSell – Maximum profit after selling the first stock. + +secondBuy – Maximum profit after buying the second stock (taking profit from firstSell into account). + +secondSell – Maximum profit after selling the second stock. + +We iterate over each price and update these states as we go: + +firstBuy = max(firstBuy, -price) +firstSell = max(firstSell, firstBuy + price) +secondBuy = max(secondBuy, firstSell - price) +secondSell = max(secondSell, secondBuy + price) + + +firstBuy → we want the lowest price for first buy. + +firstSell → we want to maximize profit from firstSell. + +secondBuy → we “reinvest” profit from firstSell. + +secondSell → maximize total profit after second sell. +*/ + +#include +using namespace std; + +int maxProfit(vector& prices) { + int firstBuy = INT_MIN, firstSell = 0; + int secondBuy = INT_MIN, secondSell = 0; + + for(int price : prices){ + firstBuy = max(firstBuy, -price); + firstSell = max(firstSell, firstBuy + price); + secondBuy = max(secondBuy, firstSell - price); + secondSell = max(secondSell, secondBuy + price); + } + + return secondSell; +} + +int main() { + vector prices = {3,3,5,0,0,3,1,4}; + cout << "Max Profit: " << maxProfit(prices) << endl; + return 0; +} From 2bfc69dd8ec2d197f09a6c5d9dedd69b7362ac36 Mon Sep 17 00:00:00 2001 From: "Dr.Dread" <135847306+DrDread746@users.noreply.github.com> Date: Mon, 20 Oct 2025 11:37:10 +0530 Subject: [PATCH 094/135] Added 1094.Car Pooling Solution --- 1094.Car Pooling.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 1094.Car Pooling.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; + } +}; From eef1c741f6094f445c7997c93de3eb519202c88f Mon Sep 17 00:00:00 2001 From: Tannu Singh Date: Mon, 20 Oct 2025 15:06:41 +0530 Subject: [PATCH 095/135] Rename file to match PR name --- ...e the Number of Target Nodes After Connecting Trees.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) 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 index 389385f..56b7f08 100644 --- a/99.Maximize the Number of Target Nodes After Connecting Trees.cpp +++ b/99.Maximize the Number of Target Nodes After Connecting Trees.cpp @@ -1,3 +1,8 @@ +#include +#include +#include +using namespace std; + class Solution { public: vector maxTargetNodes(vector>& edges1, vector>& edges2, int k) { @@ -47,4 +52,4 @@ class Solution { } return count; } -}; +}; \ No newline at end of file From 57be3201aba43bdc4fbf789d4c2cb568dd4ef6db Mon Sep 17 00:00:00 2001 From: star-arpit12 Date: Tue, 21 Oct 2025 01:00:03 +0530 Subject: [PATCH 096/135] Added leetcode 26 --- 26. Remove Duplicates from Sorted Array.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 26. Remove Duplicates from Sorted Array.cpp 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; + } +}; From e569d71db1d0a93c8ddd045554594b9fb0ac6e19 Mon Sep 17 00:00:00 2001 From: aastikdas Date: Wed, 22 Oct 2025 08:14:02 +0530 Subject: [PATCH 097/135] modified 123.Best time to buy or sell stock iii.cpp --- 123. Best time to buy or sell stock iii .cpp | 84 ++++++-------------- 1 file changed, 23 insertions(+), 61 deletions(-) diff --git a/123. Best time to buy or sell stock iii .cpp b/123. Best time to buy or sell stock iii .cpp index b461a1b..21027dd 100644 --- a/123. Best time to buy or sell stock iii .cpp +++ b/123. Best time to buy or sell stock iii .cpp @@ -1,62 +1,24 @@ -/* -Problem - -You are given an array prices where prices[i] is the price of a given stock on day i. - -You can complete at most two transactions (a buy and a sell count as one transaction). You cannot hold more than one stock at a time. - -Return the maximum profit you can achieve. - -Approach - -We can use Dynamic Programming with states. - -We define four variables to track maximum profit in each state: - -firstBuy – Maximum profit after buying the first stock (negative because we spent money). - -firstSell – Maximum profit after selling the first stock. - -secondBuy – Maximum profit after buying the second stock (taking profit from firstSell into account). - -secondSell – Maximum profit after selling the second stock. - -We iterate over each price and update these states as we go: - -firstBuy = max(firstBuy, -price) -firstSell = max(firstSell, firstBuy + price) -secondBuy = max(secondBuy, firstSell - price) -secondSell = max(secondSell, secondBuy + price) - - -firstBuy → we want the lowest price for first buy. - -firstSell → we want to maximize profit from firstSell. - -secondBuy → we “reinvest” profit from firstSell. - -secondSell → maximize total profit after second sell. -*/ - -#include -using namespace std; - -int maxProfit(vector& prices) { - int firstBuy = INT_MIN, firstSell = 0; - int secondBuy = INT_MIN, secondSell = 0; - - for(int price : prices){ - firstBuy = max(firstBuy, -price); - firstSell = max(firstSell, firstBuy + price); - secondBuy = max(secondBuy, firstSell - price); - secondSell = max(secondSell, secondBuy + price); +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]; } - - return secondSell; -} - -int main() { - vector prices = {3,3,5,0,0,3,1,4}; - cout << "Max Profit: " << maxProfit(prices) << endl; - return 0; -} +}; \ No newline at end of file From 7c5c1aa522fa923d999be620c13ed90411c1b948 Mon Sep 17 00:00:00 2001 From: aastikdas Date: Wed, 22 Oct 2025 08:16:16 +0530 Subject: [PATCH 098/135] Contributed Best time to buy or sell stock iv.cpp --- 188 Best time to buy and sell iv.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 188 Best time to buy and sell iv.cpp diff --git a/188 Best time to buy and sell iv.cpp b/188 Best time to buy and sell iv.cpp new file mode 100644 index 0000000..a137002 --- /dev/null +++ b/188 Best time to buy and sell iv.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int maxProfit(int k, vector& a) { + int n=a.size(); + int cap=k; + vector>>dp(n+1,vector>(2,vector(k+1,0))); + for(int i=n-1;i>=0;i--) + { + for(int buy=0;buy<2;buy++) + { + for(int cap=1;cap<=k;cap++) + { + if(buy==1) + { + dp[i][buy][cap]=max(-a[i]+dp[i+1][0][cap], dp[i+1][1][cap]); + } + else{ + dp[i][buy][cap]= max(a[i]+dp[i+1][1][cap-1], dp[i+1][0][cap]); + } + } + } + } + return dp[0][1][k]; + } +}; \ No newline at end of file From 4bda1bf4a3fbe1e15fc28ff4a8aa1d8db58e8e7e Mon Sep 17 00:00:00 2001 From: aastikdas Date: Wed, 22 Oct 2025 11:58:07 +0530 Subject: [PATCH 099/135] removed --- 188 Best time to buy and sell iv.cpp | 25 ------------------------- 1 file changed, 25 deletions(-) delete mode 100644 188 Best time to buy and sell iv.cpp diff --git a/188 Best time to buy and sell iv.cpp b/188 Best time to buy and sell iv.cpp deleted file mode 100644 index a137002..0000000 --- a/188 Best time to buy and sell iv.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { -public: - int maxProfit(int k, vector& a) { - int n=a.size(); - int cap=k; - vector>>dp(n+1,vector>(2,vector(k+1,0))); - for(int i=n-1;i>=0;i--) - { - for(int buy=0;buy<2;buy++) - { - for(int cap=1;cap<=k;cap++) - { - if(buy==1) - { - dp[i][buy][cap]=max(-a[i]+dp[i+1][0][cap], dp[i+1][1][cap]); - } - else{ - dp[i][buy][cap]= max(a[i]+dp[i+1][1][cap-1], dp[i+1][0][cap]); - } - } - } - } - return dp[0][1][k]; - } -}; \ No newline at end of file From c7564092e2d6cea76f3a7fd0e5ef01d51a550494 Mon Sep 17 00:00:00 2001 From: "lovesikka062@gmail.com" Date: Wed, 22 Oct 2025 13:52:41 +0530 Subject: [PATCH 100/135] Added Leetcode 242 --- 242. Valid Anagram.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 242. Valid Anagram.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; + } +}; From 8dc9f4da842dfef3eeed616ce649bf248fd4856e Mon Sep 17 00:00:00 2001 From: purrvax Date: Thu, 23 Oct 2025 15:31:37 +0530 Subject: [PATCH 101/135] 51 solution added --- 51.N-Queens.cpp | 64 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 51.N-Queens.cpp diff --git a/51.N-Queens.cpp b/51.N-Queens.cpp new file mode 100644 index 0000000..dd26bcb --- /dev/null +++ b/51.N-Queens.cpp @@ -0,0 +1,64 @@ +#include +using namespace std; + +class Solution { +public: + // Function to check if placing a queen at (row, col) is safe + bool isSafe(int row, int col, vector &temp, int n) { + int duprow = row; + int dupcol = col; + // Check all columns to the left in the same row + for (int j = 0; j < col; j++) { + if (temp[row][j] == 'Q') return false; + } + + // Check upper-left diagonal + while(row >= 0 && col >= 0){ + if(temp[row][col] == 'Q') return false; + row--; + col--; + } + row = duprow; + col = dupcol; + // Check lower-left diagonal + while(row < n && col >= 0){ + if(temp[row][col] == 'Q') return false; + row++; + col--; + } + + return true; + } + + // Backtracking function to place queens column by column + void solve(int col, vector temp, vector> &ans, int n) { + // If all columns are filled, add current board to answer + if (col == n) { + ans.push_back(temp); + return; + } + + for (int row = 0; row < n; row++) { + if (isSafe(row, col, temp, n)) { + // Place queen + temp[row][col] = 'Q'; + // Recurse for next column + solve(col + 1, temp, ans, n); + // Backtrack and remove queen + temp[row][col] = '.'; + } + } + } + + // Main function to call backtracking + vector> solveNQueens(int n) { + vector> ans; + vector temp; + string s(n, '.'); + for(int i = 0 ; i < n ; i++) temp.push_back(s); // FIXED + + solve(0, temp, ans, n); + return ans; +} + +}; \ No newline at end of file From db786253dcc69859a4f6e1a7097430b2af3f227e Mon Sep 17 00:00:00 2001 From: purrvax Date: Thu, 23 Oct 2025 17:32:47 +0530 Subject: [PATCH 102/135] N-queen added --- 51.N-Queens.cpp | 74 ++++++++++++++++++------------------------------- 1 file changed, 27 insertions(+), 47 deletions(-) diff --git a/51.N-Queens.cpp b/51.N-Queens.cpp index dd26bcb..1c75b86 100644 --- a/51.N-Queens.cpp +++ b/51.N-Queens.cpp @@ -3,62 +3,42 @@ using namespace std; class Solution { public: - // Function to check if placing a queen at (row, col) is safe - bool isSafe(int row, int col, vector &temp, int n) { - int duprow = row; - int dupcol = col; - // Check all columns to the left in the same row - for (int j = 0; j < col; j++) { - if (temp[row][j] == 'Q') return false; - } - - // Check upper-left diagonal - while(row >= 0 && col >= 0){ - if(temp[row][col] == 'Q') return false; - row--; - col--; - } - row = duprow; - col = dupcol; - // Check lower-left diagonal - while(row < n && col >= 0){ - if(temp[row][col] == 'Q') return false; - row++; - col--; - } - - return true; - } - - // Backtracking function to place queens column by column - void solve(int col, vector temp, vector> &ans, int n) { - // If all columns are filled, add current board to answer + void solve(int col, int n, vector &board, + vector> &ans, + vector &leftrow, vector &upperdiag, vector &lowerdiag) { + if (col == n) { - ans.push_back(temp); + ans.push_back(board); return; } for (int row = 0; row < n; row++) { - if (isSafe(row, col, temp, n)) { - // Place queen - temp[row][col] = 'Q'; - // Recurse for next column - solve(col + 1, temp, ans, n); - // Backtrack and remove queen - temp[row][col] = '.'; + 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; } } } - // Main function to call backtracking vector> solveNQueens(int n) { - vector> ans; - vector temp; - string s(n, '.'); - for(int i = 0 ; i < n ; i++) temp.push_back(s); // FIXED + vector> ans; + vector board(n, string(n, '.')); - solve(0, temp, ans, n); - return ans; -} + vector leftrow(n, 0); + vector lowerdiag(2 * n - 1, 0); + vector upperdiag(2 * n - 1, 0); -}; \ No newline at end of file + solve(0, n, board, ans, leftrow, upperdiag, lowerdiag); + return ans; + } +}; From 0996b59eb16e9ebb016f7e31e2a0119ce9ef8ded Mon Sep 17 00:00:00 2001 From: yippee-arp12 Date: Thu, 23 Oct 2025 21:12:29 +0530 Subject: [PATCH 103/135] Added Leetcode 283 --- 283. Move Zeroes.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 283. Move Zeroes.cpp 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; + } +}; From 8a89085ca4fbcce760d9b95c4da8bb5369a969a8 Mon Sep 17 00:00:00 2001 From: AsparkArcane Date: Thu, 23 Oct 2025 21:43:29 +0530 Subject: [PATCH 104/135] 3461. Check if Digits Are Equal in String After Operations I --- ...its Are Equal in String After Operations I.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 3461. Check If Digits Are Equal in String After Operations I.cpp diff --git a/3461. Check If Digits Are Equal in String After Operations I.cpp b/3461. Check If Digits Are Equal in String After Operations I.cpp new file mode 100644 index 0000000..ef55ef4 --- /dev/null +++ b/3461. Check If Digits Are Equal in String After Operations I.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + bool hasSameDigits(string s) { + while(s.length() > 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 From 96f48cd47409b7de6c524eaf7b7061269867823a Mon Sep 17 00:00:00 2001 From: Poorvika Date: Thu, 23 Oct 2025 22:44:32 +0530 Subject: [PATCH 105/135] add leetcode hard- binary tree max path sum --- 124. Binary Tree Maximum Path Sum.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 124. Binary Tree Maximum Path Sum.cpp diff --git a/124. Binary Tree Maximum Path Sum.cpp b/124. Binary Tree Maximum Path Sum.cpp new file mode 100644 index 0000000..e69de29 From 739c49dff0ca79d3652eae3031211e0bfd799663 Mon Sep 17 00:00:00 2001 From: Poorvika Date: Thu, 23 Oct 2025 23:08:05 +0530 Subject: [PATCH 106/135] include file --- 124. Binary Tree Maximum Path Sum.cpp | 30 +++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/124. Binary Tree Maximum Path Sum.cpp b/124. Binary Tree Maximum Path Sum.cpp index e69de29..7c71148 100644 --- a/124. Binary Tree Maximum Path Sum.cpp +++ b/124. Binary Tree Maximum Path Sum.cpp @@ -0,0 +1,30 @@ +/** + * 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: + int solve(TreeNode* root, int &maxSum){ + if(!root) return 0; + + int leftHeight = max(0, solve(root->left, maxSum)); + int rightHeight = max(0, solve(root->right, maxSum)); + + maxSum = max(maxSum, leftHeight + rightHeight + root->val); + return max(leftHeight, rightHeight) + root->val; + } + + int maxPathSum(TreeNode* root) { + int maxSum = INT_MIN; + solve(root, maxSum); + + return maxSum; + } +}; \ No newline at end of file From c6d8d1f3fe40bb3ebafeff84d43478f781e311f9 Mon Sep 17 00:00:00 2001 From: Poorvika Date: Thu, 23 Oct 2025 23:27:55 +0530 Subject: [PATCH 107/135] vertical order traversal of a binary tree --- ...tical Order Traversal of a Binary Tree.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 987. Vertical Order Traversal of a Binary Tree.cpp diff --git a/987. Vertical Order Traversal of a Binary Tree.cpp b/987. Vertical Order Traversal of a Binary Tree.cpp new file mode 100644 index 0000000..cc276b0 --- /dev/null +++ b/987. Vertical Order Traversal of a Binary Tree.cpp @@ -0,0 +1,45 @@ +/** + * 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> verticalTraversal(TreeNode* root) { + map>> nodes; + queue>> todo; + + todo.push({root, {0, 0}}); + + while(!todo.empty()) { + auto p = todo.front(); + todo.pop(); + + TreeNode* node = p.first; + int x = p.second.first, y = p.second.second; + + nodes[x][y].insert(node->val); + + if(node->left) + todo.push({node->left, {x-1, y+1}}); + if(node->right) + todo.push({node->right, {x+1, y+1}}); + } + + vector> ans; + for(auto &p: nodes) { + vector col; + for(auto &q: p.second) + col.insert(col.end(), q.second.begin(), q.second.end()); + ans.push_back(col); + } + + return ans; + } +}; From 48eeaf2fce4b9ef4ca5329519a30588a3e48003c Mon Sep 17 00:00:00 2001 From: Poorvika <152640996+poorvikaa08@users.noreply.github.com> Date: Fri, 24 Oct 2025 00:07:11 +0530 Subject: [PATCH 108/135] Delete 987. Vertical Order Traversal of a Binary Tree.cpp --- ...tical Order Traversal of a Binary Tree.cpp | 45 ------------------- 1 file changed, 45 deletions(-) delete mode 100644 987. Vertical Order Traversal of a Binary Tree.cpp diff --git a/987. Vertical Order Traversal of a Binary Tree.cpp b/987. Vertical Order Traversal of a Binary Tree.cpp deleted file mode 100644 index cc276b0..0000000 --- a/987. Vertical Order Traversal of a Binary Tree.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 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> verticalTraversal(TreeNode* root) { - map>> nodes; - queue>> todo; - - todo.push({root, {0, 0}}); - - while(!todo.empty()) { - auto p = todo.front(); - todo.pop(); - - TreeNode* node = p.first; - int x = p.second.first, y = p.second.second; - - nodes[x][y].insert(node->val); - - if(node->left) - todo.push({node->left, {x-1, y+1}}); - if(node->right) - todo.push({node->right, {x+1, y+1}}); - } - - vector> ans; - for(auto &p: nodes) { - vector col; - for(auto &q: p.second) - col.insert(col.end(), q.second.begin(), q.second.end()); - ans.push_back(col); - } - - return ans; - } -}; From 4027bac87018130c4b9e4ea687e26cc6780c55fc Mon Sep 17 00:00:00 2001 From: Poorvika <152640996+poorvikaa08@users.noreply.github.com> Date: Fri, 24 Oct 2025 00:09:17 +0530 Subject: [PATCH 109/135] Delete 124. Binary Tree Maximum Path Sum.cpp --- 124. Binary Tree Maximum Path Sum.cpp | 30 --------------------------- 1 file changed, 30 deletions(-) delete mode 100644 124. Binary Tree Maximum Path Sum.cpp diff --git a/124. Binary Tree Maximum Path Sum.cpp b/124. Binary Tree Maximum Path Sum.cpp deleted file mode 100644 index 7c71148..0000000 --- a/124. Binary Tree Maximum Path Sum.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 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: - int solve(TreeNode* root, int &maxSum){ - if(!root) return 0; - - int leftHeight = max(0, solve(root->left, maxSum)); - int rightHeight = max(0, solve(root->right, maxSum)); - - maxSum = max(maxSum, leftHeight + rightHeight + root->val); - return max(leftHeight, rightHeight) + root->val; - } - - int maxPathSum(TreeNode* root) { - int maxSum = INT_MIN; - solve(root, maxSum); - - return maxSum; - } -}; \ No newline at end of file From 9b3d283ef7caa880ea7489efe115f793879ebf84 Mon Sep 17 00:00:00 2001 From: Poorvika Date: Fri, 24 Oct 2025 00:33:56 +0530 Subject: [PATCH 110/135] leetcode 23 --- 23. Merge k Sorted Lists.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 23. Merge k Sorted Lists.cpp 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 From d9556fb0b151fb2df3fce6da7f47ad8a6feda0ca Mon Sep 17 00:00:00 2001 From: jyothsnasharma7 Date: Fri, 24 Oct 2025 17:46:15 +0530 Subject: [PATCH 111/135] Added 50 to list --- 50.Pow(x,n).cpp | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 50.Pow(x,n).cpp diff --git a/50.Pow(x,n).cpp b/50.Pow(x,n).cpp new file mode 100644 index 0000000..52a8aa6 --- /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; // Divide n by 2 + } + + return result; + } +}; + \ No newline at end of file From 5fe6a89fbf19447b5360c2ff127efb750eecbb1e Mon Sep 17 00:00:00 2001 From: jyothsnasharma7 Date: Fri, 24 Oct 2025 17:50:48 +0530 Subject: [PATCH 112/135] Added 50 to list --- 50.Pow(x,n).cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/50.Pow(x,n).cpp b/50.Pow(x,n).cpp index 52a8aa6..6dd63b6 100644 --- a/50.Pow(x,n).cpp +++ b/50.Pow(x,n).cpp @@ -35,7 +35,7 @@ Return the accumulated result. */ result *= x; } x *= x; // Square x - N /= 2; // Divide n by 2 + N /= 2; } return result; From 072c2ea06f814db05303f652592b3cd38f6101a9 Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 24 Oct 2025 19:15:25 +0530 Subject: [PATCH 113/135] Added Soln to 292. Nim Game --- 292.NimGame.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 292.NimGame.cpp 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 From 9248cb4161920e0dfe62f13b9e2fb1eeae6eae6b Mon Sep 17 00:00:00 2001 From: akshatj-05 <905jainakshat@gmail.com> Date: Mon, 27 Oct 2025 18:22:17 +0530 Subject: [PATCH 114/135] Added 2561. Rearranging Fruits --- 2561. Rearranging Fruits.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 2561. Rearranging Fruits.cpp 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; + } +}; From 0a462f448d84f5946c1bf056b047e3af4792b08d Mon Sep 17 00:00:00 2001 From: subho Date: Tue, 28 Oct 2025 23:12:14 +0530 Subject: [PATCH 115/135] Implement isPowerOfTwo function in Solution class --- 231. Power of Two.cpp | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 231. Power of Two.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; + } +}; From 7e165b3e81fd470c7990877879db6352634917a3 Mon Sep 17 00:00:00 2001 From: "Dr.Dread" <135847306+DrDread746@users.noreply.github.com> Date: Wed, 29 Oct 2025 09:31:53 +0530 Subject: [PATCH 116/135] 3208. Alternating Groups II --- 3208.Alternating Groups II.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 3208.Alternating Groups II.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; + } +}; From d743284636136593cf76acdc11fd35c6f3a48e55 Mon Sep 17 00:00:00 2001 From: "Dr.Dread" <135847306+DrDread746@users.noreply.github.com> Date: Wed, 29 Oct 2025 09:48:13 +0530 Subject: [PATCH 117/135] 3297. Count Substrings That Can Be Rearranged to Contain a String I --- ...an Be Rearranged to Contain a String I.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 3297. Count Substrings That Can Be Rearranged to Contain a String I.cpp 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; + } +}; From 90556cd95125738edd9b7a9dd3ed4f2af4589f05 Mon Sep 17 00:00:00 2001 From: "Dr.Dread" <135847306+DrDread746@users.noreply.github.com> Date: Wed, 29 Oct 2025 09:57:36 +0530 Subject: [PATCH 118/135] 3298. Count Substrings That Can Be Rearranged to Contain a String II --- ...n Be Rearranged to Contain a String II.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 3298. Count Substrings That Can Be Rearranged to Contain a String II.cpp 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; + } +}; From 9d15a2f4b07df47d57304d792355bee0f6dea950 Mon Sep 17 00:00:00 2001 From: Gargi Gupta Date: Wed, 29 Oct 2025 14:56:03 +0530 Subject: [PATCH 119/135] Add solution for LeetCode 3350: Adjacent Increasing Subarrays Detection II --- ...cent Increasing Subarrays Detection II.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 3350. Adjacent Increasing Subarrays Detection II.cpp 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; +} From bb8eae01fee8799eb4c1b3b973ac00d26fcbf5ab Mon Sep 17 00:00:00 2001 From: Ajith Date: Wed, 29 Oct 2025 15:47:28 +0530 Subject: [PATCH 120/135] Add merge intervals solution in merge_intervals.cpp Implement merge intervals solution using sorting. --- merge_intervals.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 merge_intervals.cpp diff --git a/merge_intervals.cpp b/merge_intervals.cpp new file mode 100644 index 0000000..271e14c --- /dev/null +++ b/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; + } +}; From 87aad686a3d0b0b6d035ca364d3055cd0f80ead8 Mon Sep 17 00:00:00 2001 From: Ajith Date: Wed, 29 Oct 2025 15:48:58 +0530 Subject: [PATCH 121/135] Add merge intervals cpp solution --- merge_intervals.cpp => 56. Merge intervals.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename merge_intervals.cpp => 56. Merge intervals.cpp (100%) diff --git a/merge_intervals.cpp b/56. Merge intervals.cpp similarity index 100% rename from merge_intervals.cpp rename to 56. Merge intervals.cpp From a923298d95fd7d5ca2adfa9fb0be8364aa43ac24 Mon Sep 17 00:00:00 2001 From: Ajith Date: Wed, 29 Oct 2025 15:50:32 +0530 Subject: [PATCH 122/135] Add insert function for merging intervals Implement the insert function to add a new interval into a list of intervals, merging overlapping intervals as necessary. --- 57. Insert Interval.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 57. Insert Interval.cpp diff --git a/57. Insert Interval.cpp b/57. Insert Interval.cpp new file mode 100644 index 0000000..030e7b7 --- /dev/null +++ b/57. Insert Interval.cpp @@ -0,0 +1,28 @@ +// 57. Insert Interval solution + +class Solution { + public: + vector> insert(vector>& intervals, + vector& newInterval) { + const int n = intervals.size(); + vector> ans; + int i = 0; + + while (i < n && intervals[i][1] < newInterval[0]) + ans.push_back(intervals[i++]); + + // Merge overlapping intervals. + while (i < n && intervals[i][0] <= newInterval[1]) { + newInterval[0] = min(newInterval[0], intervals[i][0]); + newInterval[1] = max(newInterval[1], intervals[i][1]); + ++i; + } + + ans.push_back(newInterval); + + while (i < n) + ans.push_back(intervals[i++]); + + return ans; + } +}; From 1e3215ba2b639948759e566ab98c3c7e5286ddea Mon Sep 17 00:00:00 2001 From: Ajith Date: Wed, 29 Oct 2025 15:51:34 +0530 Subject: [PATCH 123/135] Add solution for length of last word problem Implement function to calculate length of last word in a string. --- 58. Length of Last Word.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 58. Length of Last Word.cpp diff --git a/58. Length of Last Word.cpp b/58. Length of Last Word.cpp new file mode 100644 index 0000000..bbc7c46 --- /dev/null +++ b/58. Length of Last Word.cpp @@ -0,0 +1,16 @@ +// 58. Length of Last Word solution + +class Solution { + public: + int lengthOfLastWord(string s) { + int i = s.length() - 1; + + while (i >= 0 && s[i] == ' ') + --i; + const int lastIndex = i; + while (i >= 0 && s[i] != ' ') + --i; + + return lastIndex - i; + } +}; From 9ce0d5f676ea8d49c361709bddcd5ae8ba544d4e Mon Sep 17 00:00:00 2001 From: kaif969 Date: Wed, 29 Oct 2025 17:17:00 +0530 Subject: [PATCH 124/135] Implement candy distribution algorithm in Solution class --- 135. Candy.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 135. Candy.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); + } +}; From 8b415fb0a495ee4ae58ad9273c75db34bc45845a Mon Sep 17 00:00:00 2001 From: kaif969 Date: Wed, 29 Oct 2025 21:46:05 +0530 Subject: [PATCH 125/135] Implement numTrees function to calculate unique binary search trees --- 96. Unique Binary Search Trees.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 96. Unique Binary Search Trees.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 From 1c4505d6c4294a74be245efaf340463f89b290d9 Mon Sep 17 00:00:00 2001 From: Tannu Singh Date: Wed, 29 Oct 2025 22:52:31 +0530 Subject: [PATCH 126/135] feat(11): add Container With Most Water solution (two pointers) --- 11. Container With Most Water.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 11. Container With Most Water.cpp 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; + } +}; From 92c4e9ef76c23ca2893d4e4c90557ad407b258a6 Mon Sep 17 00:00:00 2001 From: Ajith Date: Wed, 29 Oct 2025 23:56:10 +0530 Subject: [PATCH 127/135] Delete 57. Insert Interval.cpp --- 57. Insert Interval.cpp | 28 ---------------------------- 1 file changed, 28 deletions(-) delete mode 100644 57. Insert Interval.cpp diff --git a/57. Insert Interval.cpp b/57. Insert Interval.cpp deleted file mode 100644 index 030e7b7..0000000 --- a/57. Insert Interval.cpp +++ /dev/null @@ -1,28 +0,0 @@ -// 57. Insert Interval solution - -class Solution { - public: - vector> insert(vector>& intervals, - vector& newInterval) { - const int n = intervals.size(); - vector> ans; - int i = 0; - - while (i < n && intervals[i][1] < newInterval[0]) - ans.push_back(intervals[i++]); - - // Merge overlapping intervals. - while (i < n && intervals[i][0] <= newInterval[1]) { - newInterval[0] = min(newInterval[0], intervals[i][0]); - newInterval[1] = max(newInterval[1], intervals[i][1]); - ++i; - } - - ans.push_back(newInterval); - - while (i < n) - ans.push_back(intervals[i++]); - - return ans; - } -}; From 564febc700c7fadcbc3aeb6c23ad47c4962eb855 Mon Sep 17 00:00:00 2001 From: Ajith Date: Wed, 29 Oct 2025 23:56:29 +0530 Subject: [PATCH 128/135] Delete 58. Length of Last Word.cpp --- 58. Length of Last Word.cpp | 16 ---------------- 1 file changed, 16 deletions(-) delete mode 100644 58. Length of Last Word.cpp diff --git a/58. Length of Last Word.cpp b/58. Length of Last Word.cpp deleted file mode 100644 index bbc7c46..0000000 --- a/58. Length of Last Word.cpp +++ /dev/null @@ -1,16 +0,0 @@ -// 58. Length of Last Word solution - -class Solution { - public: - int lengthOfLastWord(string s) { - int i = s.length() - 1; - - while (i >= 0 && s[i] == ' ') - --i; - const int lastIndex = i; - while (i >= 0 && s[i] != ' ') - --i; - - return lastIndex - i; - } -}; From b4381b2e6f9281cfd96e71438d8ccb37382974ca Mon Sep 17 00:00:00 2001 From: SjxSubham Date: Thu, 30 Oct 2025 00:00:58 +0530 Subject: [PATCH 129/135] Delete 99.Maximize the Number of Target Nodes After Connecting Trees.cpp --- ...of Target Nodes After Connecting Trees.cpp | 55 ------------------- 1 file changed, 55 deletions(-) delete mode 100644 99.Maximize the Number of Target Nodes After Connecting Trees.cpp 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 56b7f08..0000000 --- a/99.Maximize the Number of Target Nodes After Connecting Trees.cpp +++ /dev/null @@ -1,55 +0,0 @@ -#include -#include -#include -using namespace std; - -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; - } -}; \ No newline at end of file From e661a7277eab8472327fdbe76fac66b4bfe49ad0 Mon Sep 17 00:00:00 2001 From: Ajith Date: Thu, 30 Oct 2025 00:29:02 +0530 Subject: [PATCH 130/135] Add 57. Insert Interval solution --- 57. Insert Interval.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 57. Insert Interval.cpp 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; + } +}; From b2949933f339490abc7eba21870255c73475caf9 Mon Sep 17 00:00:00 2001 From: subho Date: Thu, 30 Oct 2025 00:52:54 +0530 Subject: [PATCH 131/135] Implement right side view of binary tree --- 199. Binary Tree Right Side View.cpp | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 199. Binary Tree Right Side View.cpp 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); + } +}; From b9dd743b2b5b066350d280ec1d7eb6d92ce4c722 Mon Sep 17 00:00:00 2001 From: subho Date: Thu, 30 Oct 2025 00:58:39 +0530 Subject: [PATCH 132/135] Implement diagonal sorting for a matrix --- 3446. Sort Matrix by Diagonals.cpp | 70 ++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 3446. Sort Matrix by Diagonals.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 Date: Thu, 30 Oct 2025 01:03:12 +0530 Subject: [PATCH 133/135] Implement dynamic programming solution for Best Time to Buy and Sell Stock IV --- 188. Best Time to Buy and Sell Stock IV.cpp | 27 +++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 188. Best Time to Buy and Sell Stock IV.cpp diff --git a/188. Best Time to Buy and Sell Stock IV.cpp b/188. Best Time to Buy and Sell Stock IV.cpp new file mode 100644 index 0000000..b516804 --- /dev/null +++ b/188. Best Time to Buy and Sell Stock IV.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector>> dp; + + int profit(vector& prices, int i, int isBuy, int k) { + if (i == prices.size() || k == 0) return 0; + + if (dp[i][isBuy][k] != -1) return dp[i][isBuy][k]; + + int a, b; + if (isBuy) { + a = profit(prices, i + 1, 1, k); + b = profit(prices, i + 1, 0, k) - prices[i]; + } else { + a = profit(prices, i + 1, 0, k); + b = profit(prices, i + 1, 1, k - 1) + prices[i]; + } + + return dp[i][isBuy][k] = max(a, b); + } + + int maxProfit(int k, vector& prices) { + int n = prices.size(); + dp = vector>>(n, vector>(2, vector(k + 1, -1))); + return profit(prices, 0, 1, k); + } +}; \ No newline at end of file From 561ac97843f3a7822143bb88f9f394d353b05c02 Mon Sep 17 00:00:00 2001 From: Sk Kaif Uddin <116540325+kaif969@users.noreply.github.com> Date: Thu, 30 Oct 2025 14:00:48 +0530 Subject: [PATCH 134/135] Delete 135. Candy.cpp --- 135. Candy.cpp | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 135. Candy.cpp diff --git a/135. Candy.cpp b/135. Candy.cpp deleted file mode 100644 index f276999..0000000 --- a/135. Candy.cpp +++ /dev/null @@ -1,24 +0,0 @@ -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); - } -}; From 10d3957436f4f83ffb1de9ea98a548b2ef2cb7d3 Mon Sep 17 00:00:00 2001 From: Sk Kaif Uddin <116540325+kaif969@users.noreply.github.com> Date: Thu, 30 Oct 2025 14:01:26 +0530 Subject: [PATCH 135/135] Delete 188. Best Time to Buy and Sell Stock IV.cpp --- 188. Best Time to Buy and Sell Stock IV.cpp | 27 --------------------- 1 file changed, 27 deletions(-) delete mode 100644 188. Best Time to Buy and Sell Stock IV.cpp diff --git a/188. Best Time to Buy and Sell Stock IV.cpp b/188. Best Time to Buy and Sell Stock IV.cpp deleted file mode 100644 index b516804..0000000 --- a/188. Best Time to Buy and Sell Stock IV.cpp +++ /dev/null @@ -1,27 +0,0 @@ -class Solution { -public: - vector>> dp; - - int profit(vector& prices, int i, int isBuy, int k) { - if (i == prices.size() || k == 0) return 0; - - if (dp[i][isBuy][k] != -1) return dp[i][isBuy][k]; - - int a, b; - if (isBuy) { - a = profit(prices, i + 1, 1, k); - b = profit(prices, i + 1, 0, k) - prices[i]; - } else { - a = profit(prices, i + 1, 0, k); - b = profit(prices, i + 1, 1, k - 1) + prices[i]; - } - - return dp[i][isBuy][k] = max(a, b); - } - - int maxProfit(int k, vector& prices) { - int n = prices.size(); - dp = vector>>(n, vector>(2, vector(k + 1, -1))); - return profit(prices, 0, 1, k); - } -}; \ No newline at end of file