diff --git a/Day 13/Q2: Akansha--C.cpp b/Day 13/q2: Longest Palindromic Substring/Akansha--C.md similarity index 98% rename from Day 13/Q2: Akansha--C.cpp rename to Day 13/q2: Longest Palindromic Substring/Akansha--C.md index 274a3f46..b082aaba 100644 --- a/Day 13/Q2: Akansha--C.cpp +++ b/Day 13/q2: Longest Palindromic Substring/Akansha--C.md @@ -1,3 +1,4 @@ +``` class Solution { public: string longestPalindrome(string s) { @@ -31,4 +32,5 @@ class Solution { return ans; } -}; \ No newline at end of file +}; +``` diff --git a/Day 13/q2: Longest Palindromic Substring/kalpana--cpp.md b/Day 13/q2: Longest Palindromic Substring/kalpana--cpp.md new file mode 100644 index 00000000..594e1721 --- /dev/null +++ b/Day 13/q2: Longest Palindromic Substring/kalpana--cpp.md @@ -0,0 +1,19 @@ +``` +class Solution { +public: + string longestPalindrome(string s) { + if (s == string(s.rbegin(), s.rend())) { + return s; + } + + string left = longestPalindrome(s.substr(1)); + string right = longestPalindrome(s.substr(0, s.size() - 1)); + + if (left.length() > right.length()) { + return left; + } else { + return right; + } + } +}; +``` diff --git a/Day 13/Q2: Longest Palindromic Substring b/Day 13/q2: Longest Palindromic Substring/question.md similarity index 92% rename from Day 13/Q2: Longest Palindromic Substring rename to Day 13/q2: Longest Palindromic Substring/question.md index 132040c4..1f98c602 100644 --- a/Day 13/Q2: Longest Palindromic Substring +++ b/Day 13/q2: Longest Palindromic Substring/question.md @@ -1,13 +1,18 @@ Given a string s, return the longest palindromic substring in s. +``` Example 1: Input: s = "babad" Output: "bab" + Example 2: Input: s = "cbbd" Output: "bb" - +``` + +``` Constraints: 1 <= s.length <= 1000 s consist of only digits and English letters. +``` diff --git a/Day 13/Q2: Solutions b/Day 13/q2: Longest Palindromic Substring/solution.cpp similarity index 100% rename from Day 13/Q2: Solutions rename to Day 13/q2: Longest Palindromic Substring/solution.cpp diff --git a/Day 13/q3: Permutation in String/kalpana--c++.cpp b/Day 13/q3: Permutation in String/kalpana--c++.cpp deleted file mode 100644 index a8f32418..00000000 --- a/Day 13/q3: Permutation in String/kalpana--c++.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution { - bool areVectorsEqual(vector a, vector b){ - for(int i=0; i<26; i++){ - if(a[i]!=b[i]) return false; - } - return true; - } -public: - bool checkInclusion(string s1, string s2) { - if(s2.size() freqS1(26, 0); - for(char c: s1) freqS1[c-'a']++; - - vector freqS2(26, 0); - int i=0, j=0; - - while(j right.length()) { + return left; + } else { + return right; + } + } +}; +``` diff --git a/Day 18/q1: Maximum Difference Between Node and Ancestor/question.md b/Day 18/q1: Maximum Difference Between Node and Ancestor/question.md deleted file mode 100644 index 9a63c5ff..00000000 --- a/Day 18/q1: Maximum Difference Between Node and Ancestor/question.md +++ /dev/null @@ -1,33 +0,0 @@ -Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b. - -A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b. - - - -Example 1: - -Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] -Output: 7 - -![tmp-tree](https://github.com/SnowScriptWinterOfCode/LeetCode_Q/assets/97434896/108fd5df-8e90-4f6c-bbfc-f2e1e08b4503) - -Explanation: We have various ancestor-node differences, some of which are given below : -|8 - 3| = 5 -|3 - 7| = 4 -|8 - 1| = 7 -|10 - 13| = 3 -Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7. - -Example 2: - -Input: root = [1,null,2,null,0,3] -Output: 3 - -![tmp-tree-1](https://github.com/SnowScriptWinterOfCode/LeetCode_Q/assets/97434896/bedf5d7f-cf61-40ee-bdcf-3a4a066abbc0) - -Constraints: - - The number of nodes in the tree is in the range [2, 5000]. - 0 <= Node.val <= 105 - Problem link: https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/description/?envType=daily-question&envId=2024-01-11 - diff --git a/Day-15/q1-Lowest Common Ancestor of a Binary Tree/Akansha--C.cpp b/Day-15/q1-Lowest Common Ancestor of a Binary Tree/Akansha--C.cpp new file mode 100644 index 00000000..d2416185 --- /dev/null +++ b/Day-15/q1-Lowest Common Ancestor of a Binary Tree/Akansha--C.cpp @@ -0,0 +1,18 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (!root || root == p || root == q) return root; + TreeNode* left = lowestCommonAncestor(root->left, p, q); + TreeNode* right = lowestCommonAncestor(root->right, p, q); + return !left ? right : !right ? left : root; + } +}; \ No newline at end of file diff --git a/Day-17/Q1:Determine if two strings are close/namita0210_java.java b/Day-17/Q1:Determine if two strings are close/namita0210_java.java new file mode 100644 index 00000000..a6ae14ea --- /dev/null +++ b/Day-17/Q1:Determine if two strings are close/namita0210_java.java @@ -0,0 +1,28 @@ +import java.util.HashMap; +import java.util.Map; + +public class namita0210_java { + public boolean closeStrings(String word1, String word2) { + if (word1.length() != word2.length()) { + return false; + } + + Map count1 = new HashMap<>(); + Map count2 = new HashMap<>(); + + // Count occurrences of characters in word1 + for (char ch : word1.toCharArray()) { + count1.put(ch, count1.getOrDefault(ch, 0) + 1); + } + + // Count occurrences of characters in word2 + for (char ch : word2.toCharArray()) { + count2.put(ch, count2.getOrDefault(ch, 0) + 1); + } + + // Check if the character counts are the same + return count1.keySet().equals(count2.keySet()) && count1.values().equals(count2.values()); + } + + +} diff --git a/Day-17/q3: Jump Game/kalpana--c.md b/Day-17/q3: Jump Game/kalpana--c.md new file mode 100644 index 00000000..a89e6008 --- /dev/null +++ b/Day-17/q3: Jump Game/kalpana--c.md @@ -0,0 +1,32 @@ +bool canJump(int* nums, int numsSize){ + int zero=0; + int len=1; + int mark=1; + for(int i=numsSize-1;i>=0;i--){ + if(nums[i]==0){ + if(i==numsSize-1) mark=0; + zero++; + len++; + } + else if(zero>0){ + if(mark==0 &&nums[i]>=len-1){ + zero=0; + len=1; + mark=1; + } + else if(nums[i]>=len){ + zero=0; + len=1; + } + else{ + len++; + } + } + + + } + if(numsSize==1) return true; + else if(zero>0 ) return false; + + else return true; +} \ No newline at end of file diff --git a/Day-17/q3: Jump Game/namita0210_python.py b/Day-17/q3: Jump Game/namita0210_python.py new file mode 100644 index 00000000..038c654d --- /dev/null +++ b/Day-17/q3: Jump Game/namita0210_python.py @@ -0,0 +1,19 @@ +def can_jump(nums): + n = len(nums) + max_reach = 0 + + for i in range(n): + # If the current index is beyond the furthest position reachable, return false + if i > max_reach: + return False + + # Update the furthest position reachable from the current index + max_reach = max(max_reach, i + nums[i]) + + # If the furthest position is greater than or equal to the last index, return true + if max_reach >= n - 1: + return True + + return False + + diff --git a/Day 18/q1: Maximum Difference Between Node and Ancestor/Anushreebasics--java.md b/Day-18/q1: Maximum Difference Between Node and Ancestor/Anushreebasics--java.md similarity index 100% rename from Day 18/q1: Maximum Difference Between Node and Ancestor/Anushreebasics--java.md rename to Day-18/q1: Maximum Difference Between Node and Ancestor/Anushreebasics--java.md diff --git a/Day 18/q1: Maximum Difference Between Node and Ancestor/Tech-neophyte--c.md b/Day-18/q1: Maximum Difference Between Node and Ancestor/Tech-neophyte--c.md similarity index 100% rename from Day 18/q1: Maximum Difference Between Node and Ancestor/Tech-neophyte--c.md rename to Day-18/q1: Maximum Difference Between Node and Ancestor/Tech-neophyte--c.md diff --git a/Day-18/q1: Maximum Difference Between Node and Ancestor/question.md b/Day-18/q1: Maximum Difference Between Node and Ancestor/question.md index c38037d3..a813fa24 100644 --- a/Day-18/q1: Maximum Difference Between Node and Ancestor/question.md +++ b/Day-18/q1: Maximum Difference Between Node and Ancestor/question.md @@ -2,11 +2,14 @@ Given the root of a binary tree, find the maximum value v for which there exist A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b. + + Example 1: Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] Output: 7 -tmp-tree + +![tmp-tree](https://github.com/SnowScriptWinterOfCode/LeetCode_Q/assets/97434896/108fd5df-8e90-4f6c-bbfc-f2e1e08b4503) Explanation: We have various ancestor-node differences, some of which are given below : |8 - 3| = 5 @@ -19,11 +22,11 @@ Example 2: Input: root = [1,null,2,null,0,3] Output: 3 -tmp-tree-1 -Constraints: +![tmp-tree-1](https://github.com/SnowScriptWinterOfCode/LeetCode_Q/assets/97434896/bedf5d7f-cf61-40ee-bdcf-3a4a066abbc0) -The number of nodes in the tree is in the range [2, 5000]. -0 <= Node.val <= 105 -Problem link: https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/description/?envType=daily-question&envId=2024-01-11 +Constraints: + The number of nodes in the tree is in the range [2, 5000]. + 0 <= Node.val <= 105 + Problem link: https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/description/?envType=daily-question&envId=2024-01-11 \ No newline at end of file diff --git a/Day-18/q1: Maximum Difference Between Node and Ancestor/solution.md b/Day-18/q1: Maximum Difference Between Node and Ancestor/solution.md new file mode 100644 index 00000000..f97f4b3d --- /dev/null +++ b/Day-18/q1: Maximum Difference Between Node and Ancestor/solution.md @@ -0,0 +1,32 @@ +``` +class Solution { +public: + void inorder(TreeNode* root, int mini, int maxi, int &diff) { + if(root==NULL) + return; + + int tmp = root->val; + diff = max(diff, max(abs(mini-tmp), abs(maxi-tmp))); + if(root->val < mini) { + inorder(root->left, tmp, maxi, diff); + inorder(root->right, tmp, maxi, diff); + } + else if(root->val > maxi) { + inorder(root->left, mini, tmp, diff); + inorder(root->right, mini, tmp, diff); + } + else { + inorder(root->left, mini, maxi, diff); + inorder(root->right, mini, maxi, diff); + } + } + + int maxAncestorDiff(TreeNode* root) { + int mini = root->val; + int maxi = mini; + int diff = 0; + inorder(root,mini, maxi, diff); + return diff; + } +}; +``` diff --git a/Day-18/q2: Search in Rotated Sorted Array/Anushreebasics--java.md b/Day-18/q2: Search in Rotated Sorted Array/Anushreebasics--java.md similarity index 100% rename from Day-18/q2: Search in Rotated Sorted Array/Anushreebasics--java.md rename to Day-18/q2: Search in Rotated Sorted Array/Anushreebasics--java.md diff --git a/Day-18/q2: Search in Rotated Sorted Array/Karnankita04--c.md b/Day-18/q2: Search in Rotated Sorted Array/Karnankita04--c.md new file mode 100644 index 00000000..55e74b0b --- /dev/null +++ b/Day-18/q2: Search in Rotated Sorted Array/Karnankita04--c.md @@ -0,0 +1,32 @@ +``` +class Solution { +public: + int search(vector& nums, int target) { + int low=0, high=nums.size()-1,mid = low+(high-low)/2 ; + + while(low<=high) + { + if(nums[mid] == target) + return mid ; + + else if(nums[low]<= nums[mid]) // left is sorted + { + if(target>=nums[low] && target<=nums[mid]) // target lies b/w left half/sorted half + high = mid-1 ; + else // target lies b/w right half + low = mid+1 ; + } + + else // right half is sorted + { + if(target>=nums[mid] && target<=nums[high]) // target lies b/w right half + low = mid+1 ; + else // target lies b/w left half + high = mid-1 ; + } + mid = low+(high-low)/2 ; + } + return -1 ; + } +}; +``` diff --git a/Day-18/q2: Search in Rotated Sorted Array/avanimathur--C.cpp b/Day-18/q2: Search in Rotated Sorted Array/avanimathur--C.cpp new file mode 100644 index 00000000..44eec40c --- /dev/null +++ b/Day-18/q2: Search in Rotated Sorted Array/avanimathur--C.cpp @@ -0,0 +1,44 @@ +#include +using namespace std; + +class Solution { +public: + + int search(const vector& nums, int target) { + + if (nums.empty()) { + return -1; + } + + int left = 0, right = nums.size() - 1; + while (left < right) { + int mid = (left + right) / 2; + + if (nums[mid] > nums[right]) { + left = mid + 1; + } else { + right = mid; + } + } + + int pivot = left; + + left = 0; + right = nums.size() - 1; + + while (left <= right) { + int mid = (left + right) / 2; + int midVal = nums[(mid + pivot) % nums.size()]; + + if (midVal == target) { + return (mid + pivot) % nums.size(); + } else if (midVal < target) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return -1; + } +}; diff --git a/Day-18/q2: Search in Rotated Sorted Array/question.md b/Day-18/q2: Search in Rotated Sorted Array/question.md similarity index 100% rename from Day-18/q2: Search in Rotated Sorted Array/question.md rename to Day-18/q2: Search in Rotated Sorted Array/question.md diff --git a/Day-18/q2: Search in Rotated Sorted Array/solution.md b/Day-18/q2: Search in Rotated Sorted Array/solution.md new file mode 100644 index 00000000..011447f6 --- /dev/null +++ b/Day-18/q2: Search in Rotated Sorted Array/solution.md @@ -0,0 +1,49 @@ +### Intuition +The idea is to use a modified binary search algorithm to find the target element in the rotated sorted array. + +### Approach - Binary Search +1. Initialize start and end indices for the array. +2. Perform a binary search in each iteration. +3. Check the middle element (mid) of the current search range. +4. If `mid==target`, return its index. +5. Check if the left half (arr[start] to arr[mid]) or the right half (arr[mid] to arr[end]) is sorted. +6. Adjust the search range accordingly based on the sorted half and the target element. + +### Complexity Analysis +`Time complexity`: O(log n) + +`Space complexity`: O(1) + +### C++ Code + +``` +class Solution { +public: + int search(vector& nums, int target) { + int n=nums.size(); + int s=0; + int e=n-1; + while(s<=e){ + int mid=s+(e-s)/2; + if(nums[mid]==target)return mid; + if(nums[s]<=nums[mid]){ + if(nums[s]<=target and nums[mid]>=target){ + e=mid-1; + } + else{ + s=mid+1; + } + } + else{ + if (nums[mid] <= target && target <= nums[e]) + s=mid+1; + else{ + e=mid-1; + } + + } + } + return -1; + } +}; +``` diff --git a/Day-18/q3: Palindrome Linked List/Shubh-Krishna--c.md b/Day-18/q3: Palindrome Linked List/Shubh-Krishna--c.md new file mode 100644 index 00000000..219c6bd9 --- /dev/null +++ b/Day-18/q3: Palindrome Linked List/Shubh-Krishna--c.md @@ -0,0 +1,35 @@ +``` +/** + * 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: + bool isPalindrome(ListNode* head) { + ListNode *s=head; + int i=0; + while (s != nullptr){ + i++; + s=s->next; + } + s = head; + int arr[i]; + for (int j=0;jval; + s=s->next; + } + for (int a = 0, b = i - 1; a < b; a++, b--) { + if (arr[a] != arr[b]) { + return false; + } + } + return true; + } +}; +``` diff --git a/Day-18/q3: Palindrome Linked List/Question.md b/Day-18/q3: Palindrome Linked List/question.md similarity index 68% rename from Day-18/q3: Palindrome Linked List/Question.md rename to Day-18/q3: Palindrome Linked List/question.md index 35ae34ad..ec27792e 100644 --- a/Day-18/q3: Palindrome Linked List/Question.md +++ b/Day-18/q3: Palindrome Linked List/question.md @@ -1,10 +1,15 @@ +# Palindrome Linked List Given the head of a singly linked list, return true if it is a palindrome or false otherwise. -Example 1: +## Example 1: Input: head = [1,2,2,1] + Output: true -Example 2: + + +## Example 2: Input: head = [1,2] -Output: false \ No newline at end of file + +Output: false diff --git a/Day-19/q1 Find Players With Zero or One Losses/Anushreebasics--java.md b/Day-19/q1 Find Players With Zero or One Losses/Anushreebasics--java.md new file mode 100644 index 00000000..81525c98 --- /dev/null +++ b/Day-19/q1 Find Players With Zero or One Losses/Anushreebasics--java.md @@ -0,0 +1,35 @@ +``` +import java.util.*; +class Solution { + public List> findWinners(int[][] matches) { + HashMap played= new HashMap<>(); + HashMap won= new HashMap<>(); + + for(int i=0;i l1=new ArrayList<>(); + List l2=new ArrayList<>(); + for(int k:played.keySet()){ + if(won.containsKey(k) && played.get(k)==won.get(k)){ + l1.add(k); + } + else if((!won.containsKey(k) && (played.get(k)==1)) || (won.containsKey(k) && (played.get(k)-won.get(k))==1)){ + l2.add(k); + } + } + Collections.sort(l1); + Collections.sort(l2); + List> l= new ArrayList<>(); + l.add(l1); + l.add(l2); + return l; + } +} +``` diff --git a/Day-19/q1 Find Players With Zero or One Losses/Shubh-Krishna--c.md b/Day-19/q1 Find Players With Zero or One Losses/Shubh-Krishna--c.md new file mode 100644 index 00000000..1280976f --- /dev/null +++ b/Day-19/q1 Find Players With Zero or One Losses/Shubh-Krishna--c.md @@ -0,0 +1,18 @@ +``` +class Solution { +public: + vector> findWinners(vector>& matches) { + map> mp; + for(auto i : matches){ + mp[i[0]].first++; + mp[i[1]].second++; + } + vector> ans(2); + for(auto [i, v] : mp){ + if(v.second == 0) ans[0].push_back(i); + else if(v.second == 1) ans[1].push_back(i); + } + return ans; + } +}; +``` diff --git a/Day-19/q1 Find Players With Zero or One Losses/Tech-neophyte--p.md b/Day-19/q1 Find Players With Zero or One Losses/Tech-neophyte--p.md new file mode 100644 index 00000000..8337b5dd --- /dev/null +++ b/Day-19/q1 Find Players With Zero or One Losses/Tech-neophyte--p.md @@ -0,0 +1,18 @@ +## Python code: (Using dict) +``` +class Solution: + def findWinners(self, matches: List[List[int]]) -> List[List[int]]: + loss={} + for p in matches: + x, y=p + if x not in loss: loss[x]=0 + if y in loss: loss[y]+=1 + else: loss[y]=1 + ans=[[], []] + for i, f in loss.items(): + if f==0: + ans[0].append(i) + elif f==1: + ans[1].append(i) + return [sorted(ans[0]), sorted(ans[1])] +``` diff --git a/Day-19/q1 Find Players With Zero or One Losses/avanimathur--C.cpp b/Day-19/q1 Find Players With Zero or One Losses/avanimathur--C.cpp new file mode 100644 index 00000000..1be23c09 --- /dev/null +++ b/Day-19/q1 Find Players With Zero or One Losses/avanimathur--C.cpp @@ -0,0 +1,30 @@ +#include +using namespace std; + +class Solution { +public: + vector> findPlayers(vector>& matches) { + + unordered_map lossesCount; + + for (const auto& match : matches) { + lossesCount[match[1]]++; + } + + vector zeroLosses; + vector oneLoss; + + for (const auto& entry : lossesCount) { + if (entry.second == 0) { + zeroLosses.push_back(entry.first); + } else if (entry.second == 1) { + oneLoss.push_back(entry.first); + } + } + + sort(zeroLosses.begin(), zeroLosses.end()); + sort(oneLoss.begin(), oneLoss.end()); + + return {zeroLosses, oneLoss}; + } +}; diff --git a/Day-19/q1 Find Players With Zero or One Losses/namita0210_java.java b/Day-19/q1 Find Players With Zero or One Losses/namita0210_java.java new file mode 100644 index 00000000..5b2f13be --- /dev/null +++ b/Day-19/q1 Find Players With Zero or One Losses/namita0210_java.java @@ -0,0 +1,43 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class namita0210_java { + + public static List> findPlayers(int[][] matches) { + Map losses = new HashMap<>(); + Map played = new HashMap<>(); + + for (int[] match : matches) { + int winner = match[0]; + int loser = match[1]; + + played.put(winner, true); + played.put(loser, true); + + losses.put(loser, losses.getOrDefault(loser, 0) + 1); + } + + List zeroLossPlayers = new ArrayList<>(); + List oneLossPlayers = new ArrayList<>(); + + for (int player : played.keySet()) { + int lossCount = losses.getOrDefault(player, 0); + + if (lossCount == 0) { + zeroLossPlayers.add(player); + } else if (lossCount == 1) { + oneLossPlayers.add(player); + } + } + + List> answer = new ArrayList<>(); + answer.add(zeroLossPlayers); + answer.add(oneLossPlayers); + + return answer; + } + + +} diff --git a/Day-19/q1 Find Players With Zero or One Losses/solution.md b/Day-19/q1 Find Players With Zero or One Losses/solution.md new file mode 100644 index 00000000..5c85dd44 --- /dev/null +++ b/Day-19/q1 Find Players With Zero or One Losses/solution.md @@ -0,0 +1,50 @@ +## Find Players With Zero or One Losses + +### Approach: + +1. Initialize an unordered map `lost` to keep track of the number of matches lost by each player. +2. Iterate through the given `matches` array to populate the `lost` map. +3. Create 2D vector in which `answer[0]` and `answer[1]` store players who have not lost any matches and those who have lost exactly one match, respectively. +4. Iterate through the `matches` array again: + - For each match, check if the loser (`matches[i][1]`) has lost exactly one match. If so, add them to `answer[1]`. + - Check if the winner (`matches[i][0]`) is not present in the `lost` map, which means they have not lost any matches. Add them to `answer[0]` and mark their status in the `lost` map as -1. +5. Sort both `answer[0]` and `answer[1]` in increasing order. +6. Return the `answer` vector containing the two lists. + + + +### C++ code +```cpp +class Solution { +public: + vector> findWinners(vector>& matches) { + vector> answer(2); + unordered_map lost; + + // Populate the 'lost' map + for (int i = 0; i < matches.size(); i++) { + lost[matches[i][1]]++; + } + + // Process the matches + for (int i = 0; i < matches.size(); i++) { + // Check for players who lost exactly one match + if (lost[matches[i][1]] == 1) { + answer[1].push_back(matches[i][1]); + } + + // Check for players who have not lost any matches + if (lost.find(matches[i][0]) == lost.end()) { + answer[0].push_back(matches[i][0]); + lost[matches[i][0]] = -1; + } + } + + // Sort the result vectors in increasing order + sort(begin(answer[0]), end(answer[0])); + sort(begin(answer[1]), end(answer[1])); + + return answer; + } +}; +``` diff --git a/Day-19/q3-Letter Combinations of a Phone Number/Shubh-Krishna--c.md b/Day-19/q3-Letter Combinations of a Phone Number/Shubh-Krishna--c.md new file mode 100644 index 00000000..a479b228 --- /dev/null +++ b/Day-19/q3-Letter Combinations of a Phone Number/Shubh-Krishna--c.md @@ -0,0 +1,19 @@ +``` + vector res; + string key[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + public: + vector letterCombinations(string digits) { + if(digits.empty()) return res_; + recur(digits, "", 0); + return res; + } + void recur(string s, string cur, int index){ + if(index == s.length()) res_.emplace_back(cur); + else{ + string letters = key[s[index] - '0']; + for(const char c: letters){ + recur(s, cur + c, index + 1); + } + } + } +``` diff --git a/Day-19/q3-Letter Combinations of a Phone Number/namita0210_java.java b/Day-19/q3-Letter Combinations of a Phone Number/namita0210_java.java new file mode 100644 index 00000000..3310dcb3 --- /dev/null +++ b/Day-19/q3-Letter Combinations of a Phone Number/namita0210_java.java @@ -0,0 +1,44 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class namita0210_java { + + public static List letterCombinations(String digits) { + List result = new ArrayList<>(); + if (digits == null || digits.length() == 0) { + return result; + } + + Map digitToLetters = new HashMap<>(); + digitToLetters.put('2', "abc"); + digitToLetters.put('3', "def"); + digitToLetters.put('4', "ghi"); + digitToLetters.put('5', "jkl"); + digitToLetters.put('6', "mno"); + digitToLetters.put('7', "pqrs"); + digitToLetters.put('8', "tuv"); + digitToLetters.put('9', "wxyz"); + + generateCombinations(result, digits, digitToLetters, "", 0); + + return result; + } + + private static void generateCombinations(List result, String digits, Map digitToLetters, String current, int index) { + if (index == digits.length()) { + result.add(current); + return; + } + + char digit = digits.charAt(index); + String letters = digitToLetters.get(digit); + + for (char letter : letters.toCharArray()) { + generateCombinations(result, digits, digitToLetters, current + letter, index + 1); + } + } + + +} diff --git a/Day-19/q3-Letter Combinations of a Phone Number/solution.md b/Day-19/q3-Letter Combinations of a Phone Number/solution.md new file mode 100644 index 00000000..66009da0 --- /dev/null +++ b/Day-19/q3-Letter Combinations of a Phone Number/solution.md @@ -0,0 +1,32 @@ +## Letter Combinations of a Phone Number + +C++ Code +``` +cpp +class Solution { +public: + vector str={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; + + void solve(vector &ans,string digits,int index,string st){ + if(index==digits.size()){ + ans.push_back(st); + return; + } + + int idx=digits[index]-'0'; + + for(auto it:str[idx]){ + st.push_back(it); + solve(ans,digits,index+1,st); + st.pop_back(); + } + + } + vector letterCombinations(string digits) { + vector ans; + if(digits.size()==0) return ans; + solve(ans,digits,0,""); + return ans; + + } +}; diff --git a/Day-21/Q2:Container With Most Water/namita0210_java.java b/Day-21/q2 : Container With Most Water/namita0210--j.md similarity index 98% rename from Day-21/Q2:Container With Most Water/namita0210_java.java rename to Day-21/q2 : Container With Most Water/namita0210--j.md index 505a97d8..448113b4 100644 --- a/Day-21/Q2:Container With Most Water/namita0210_java.java +++ b/Day-21/q2 : Container With Most Water/namita0210--j.md @@ -1,3 +1,4 @@ +``` public class namita0210_java { public static int maxArea(int[] height) { @@ -22,3 +23,5 @@ public static int maxArea(int[] height) { } + +``` diff --git a/Day-21/q2 : Container With Most Water/question.md b/Day-21/q2 : Container With Most Water/question.md new file mode 100644 index 00000000..2a354734 --- /dev/null +++ b/Day-21/q2 : Container With Most Water/question.md @@ -0,0 +1,20 @@ +You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). + +Find two lines that together with the x-axis form a container, such that the container contains the most water. + +Return the maximum amount of water a container can store. + +Notice that you may not slant the container. + +Example 1: +Input: height = [1,8,6,2,5,4,8,3,7] +Output: 49 + +Example 2: +Input: height = [1,1] +Output: 1 + +Constraints: +n == height.length +2 <= n <= 105 +0 <= height[i] <= 104 diff --git a/Day-21/q3: Unique Paths/question.md b/Day-21/q3: Unique Paths/question.md new file mode 100644 index 00000000..b3a0d834 --- /dev/null +++ b/Day-21/q3: Unique Paths/question.md @@ -0,0 +1,24 @@ +# Unique Paths + +There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. + +Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. + +The test cases are generated so that the answer will be less than or equal to 2 * 109. + +### Example 1: +Input: m = 3, n = 7 +Output: 28 + +### Example 2: +Input: m = 3, n = 2 +Output: 3 + + +Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: +1. Right -> Down -> Down +2. Down -> Down -> Right +3. Down -> Right -> Down + +### Constraints: +1 <= m, n <= 100 \ No newline at end of file diff --git a/Day-22/q1: Minimum Number of Operations to Make Array Empty/question.md b/Day-22/q1: Minimum Number of Operations to Make Array Empty/question.md new file mode 100644 index 00000000..fe32a58f --- /dev/null +++ b/Day-22/q1: Minimum Number of Operations to Make Array Empty/question.md @@ -0,0 +1,36 @@ +You are given a 0-indexed array nums consisting of positive integers. + +There are two types of operations that you can apply on the array any number of times: + + Choose two elements with equal values and delete them from the array. + Choose three elements with equal values and delete them from the array. + +Return the minimum number of operations required to make the array empty, or -1 if it is not possible. + + + +Example 1: + +Input: nums = [2,3,3,2,2,4,2,3,4] +Output: 4 +Explanation: We can apply the following operations to make the array empty: +- Apply the first operation on the elements at indices 0 and 3. The resulting array is nums = [3,3,2,4,2,3,4]. +- Apply the first operation on the elements at indices 2 and 4. The resulting array is nums = [3,3,4,3,4]. +- Apply the second operation on the elements at indices 0, 1, and 3. The resulting array is nums = [4,4]. +- Apply the first operation on the elements at indices 0 and 1. The resulting array is nums = []. +It can be shown that we cannot make the array empty in less than 4 operations. + +Example 2: + +Input: nums = [2,1,2,2,3,3] +Output: -1 +Explanation: It is impossible to empty the array. + + + +Constraints: + + 2 <= nums.length <= 105 + 1 <= nums[i] <= 106 + +problem link: https://leetcode.com/problems/minimum-number-of-operations-to-make-array-empty/description/?envType=daily-question&envId=2024-01-04 diff --git a/Day-22/q2: Sum of Left Leaves/question.md b/Day-22/q2: Sum of Left Leaves/question.md new file mode 100644 index 00000000..4008e171 --- /dev/null +++ b/Day-22/q2: Sum of Left Leaves/question.md @@ -0,0 +1,26 @@ +Given the `root` of a binary tree, return the sum of all left leaves. + +A **leaf** is a node with no children. +A **left leaf** is a leaf that is the left child of another node. + +### **_Example 1_** + +![image](https://github.com/SnowScriptWinterOfCode/LeetCode_Q/assets/112773734/82f26aff-30a7-4d6e-91ad-dd0cdc562ff6) + +**Input**: root = [3,9,20,null,null,15,7] +**Output**: 24 +**Explanation**: There are two left leaves in the binary tree, with values 9 and 15 respectively. + +### **_Example 2_** + +**Input**: root = [1] +**Output**: 0 + + +### Constraints: + +- The number of nodes in the tree is in the range `[1, 1000]`. +- `1000` <= Node.val <= `1000` + +### problem link: +https://leetcode.com/problems/sum-of-left-leaves/ diff --git a/Day-23/q1: Minimum falling path sum/question.md b/Day-23/q1: Minimum falling path sum/question.md new file mode 100644 index 00000000..58921be2 --- /dev/null +++ b/Day-23/q1: Minimum falling path sum/question.md @@ -0,0 +1,26 @@ +# Minimum Falling Path Sum + +Given an n x n array of integers `matrix`, return the minimum sum of any falling path through matrix. +A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. +Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1). + +## Example 1: + +![image](https://github.com/SonaVarshney/LeetCode_Q/assets/99477385/b787b266-1f22-4ad1-b7a6-4376852984da) +`Input`: matrix = [[2,1,3],[6,5,4],[7,8,9]] +`Output`: 13 +`Explanation`: There are two falling paths with a minimum sum as shown. + +## Example 2: + +![image](https://github.com/SonaVarshney/LeetCode_Q/assets/99477385/eeb0da0d-f130-40b0-aee8-9b483b49b39d) + +`Input`: matrix = [[-19,57],[-40,-5]] +`Output`: -59 +`Explanation`: The falling path with a minimum sum is shown. + + ## Constraints: + +- n == matrix.length == matrix[i].length +- 1 <= n <= 100 +- -100 <= matrix[i][j] <= 100 diff --git a/Day-23/q1: Minimum falling path sum/solution.md b/Day-23/q1: Minimum falling path sum/solution.md new file mode 100644 index 00000000..48528030 --- /dev/null +++ b/Day-23/q1: Minimum falling path sum/solution.md @@ -0,0 +1,73 @@ +# Approach: + +- Recursive Approach: +The recursive function helper is designed to calculate the minimum falling path sum from the current cell (i, j) to the bottom row of the matrix. +The base cases are defined for the top row, where the falling path sum is simply the value of the cell. + +- Memoization: +To avoid redundant calculations, a 2D array dp is used to memoize the results of subproblems. The dp array is initialized with a large value (e.g., INT_MAX). +Before calculating the falling path sum for the current cell, the algorithm checks if the result for the current cell is already calculated and stored in dp. If yes, it returns the memoized result. + +- Calculate Minimum Falling Path Sum: +For the current cell (i, j), the algorithm calculates the falling path sum considering three possible paths: + - Straight down: s = matrix[i][j] + helper(matrix, i - 1, j) + - Down-left: ld = matrix[i][j] + helper(matrix, i - 1, j - 1) + - Down-right: rd = matrix[i][j] + helper(matrix, i - 1, j + 1) +The minimum falling path sum is then calculated as min(s, min(ld, rd)). + +- Iterate Over Starting Points: +The main function iterates over all possible starting points in the bottom row (the last row of the matrix). +It finds the minimum falling path sum among these starting points. + +- Return the Result: +The final result is the minimum falling path sum among all starting points in the bottom row. + +- Time Complexity: +The time complexity is improved by memoization, reducing redundant calculations. The overall time complexity is O(n * m), where n is the number of rows and m is the number of columns in the matrix. + +- Space Complexity: +The space complexity is O(n * m) due to the memoization array dp. + + +## C++ code + +``` + + int dp[101][101]; + + int helper(vector>& matrix, int i, int j) { + if (i == 0 && j < matrix[0].size() && j >= 0) { + return matrix[0][j]; + } + if (j < 0 || j >= matrix[0].size()) { + return 1e7; + } + + if (dp[i][j] != INT_MAX) { + return dp[i][j]; + } + + int s = matrix[i][j] + helper(matrix, i - 1, j); + int ld = matrix[i][j] + helper(matrix, i - 1, j - 1); + int rd = matrix[i][j] + helper(matrix, i - 1, j + 1); + return dp[i][j] = min(s, min(ld, rd)); + } + + int minFallingPathSum(vector>& matrix) { + int n = matrix.size(); + int m = matrix[0].size(); + + // Initialize dp array + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + dp[i][j] = INT_MAX; + } + } + + int mini = INT_MAX; + for (int j = 0; j < m; j++) { + mini = min(mini, helper(matrix, n - 1, j)); + } + return mini; + } +``` diff --git a/Day-23/q1:Minimum falling path sum/namita0210_java.java b/Day-23/q1:Minimum falling path sum/namita0210_java.java new file mode 100644 index 00000000..c4081807 --- /dev/null +++ b/Day-23/q1:Minimum falling path sum/namita0210_java.java @@ -0,0 +1,40 @@ +public class MinimumFallingPathSum { + public int minFallingPathSum(int[][] matrix) { + int n = matrix.length; + + // Create a DP array to store minimum falling path sum + int[][] dp = new int[n][n]; + + // Copy the first row of the matrix to the DP array + for (int i = 0; i < n; i++) { + dp[0][i] = matrix[0][i]; + } + + // Iterate through the matrix to fill the DP array + for (int i = 1; i < n; i++) { + for (int j = 0; j < n; j++) { + // Find the minimum value from the three possible paths + int minPath = dp[i - 1][j]; + if (j > 0) { + minPath = Math.min(minPath, dp[i - 1][j - 1]); + } + if (j < n - 1) { + minPath = Math.min(minPath, dp[i - 1][j + 1]); + } + + // Update the DP array with the minimum falling path sum + dp[i][j] = matrix[i][j] + minPath; + } + } + + // Find the minimum falling path sum in the last row of the DP array + int minSum = dp[n - 1][0]; + for (int i = 1; i < n; i++) { + minSum = Math.min(minSum, dp[n - 1][i]); + } + + return minSum; + } + + +} diff --git a/Day-27/q1: Maximum Length of a Concatenated String with Unique Characters/question.md b/Day-27/q1: Maximum Length of a Concatenated String with Unique Characters/question.md new file mode 100644 index 00000000..b13c6fc7 --- /dev/null +++ b/Day-27/q1: Maximum Length of a Concatenated String with Unique Characters/question.md @@ -0,0 +1,40 @@ +# Maximum Length of a Concatenated String with Unique Characters + +You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters. Return the maximum possible length of s. + +A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. + + + +## Example 1: + +`Input`: arr = ["un","iq","ue"] +`Output`: 4 +`Explanation`: All the valid concatenations are: +- "" +- "un" +- "iq" +- "ue" +- "uniq" ("un" + "iq") +- "ique" ("iq" + "ue") +Maximum length is 4. + +## Example 2: + +`Input`: arr = ["cha","r","act","ers"] +`Output`: 6 +`Explanation`: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers"). + + +## Example 3: + +`Input`: arr = ["abcdefghijklmnopqrstuvwxyz"] +`Output`: 26 +`Explanation`: The only string in arr has all 26 characters. + + +## Constraints: + +- 1 <= arr.length <= 16 +- 1 <= arr[i].length <= 26 +- arr[i] contains only lowercase English letters.