├── Easy Problems ├── 028 Power of Two.cpp ├── 027 Number of 1 Bits.cpp ├── 019 Single Number.cpp ├── 054 Single Number.cpp ├── 007 Remove Duplicates from Sorted array.cpp ├── 022 Contains Duplicate.cpp ├── 029 Same Tree.cpp ├── 052 Missing Numbers.cpp ├── 042 Reverse Integer.cpp ├── 046 Invert Binary Tree.cpp ├── 031 Ugly Number.cpp ├── 040 Greatest Common Divisor of Strings.cpp ├── 011 Length of Last Word.cpp ├── 033 Add Digits.cpp ├── 051 Move Zeroes.cpp ├── 003 Palindrome Number.cpp ├── 038 Merge Sorted Array.cpp ├── Reverse Bits.cpp ├── 036 InOrder Traversal.cpp ├── 057 Valid Anagram.cpp ├── 061 Find the Highest Altitude.cpp ├── 035 Height of Tree.cpp ├── 014 SQRT(x).cpp ├── 024 Reverse Linkedlist.cpp ├── 008 Remove Element.cpp ├── 047 Single Element in a sorted Array.cpp ├── 055 Can Make Arithmetic Progression From Sequence .cpp ├── 018 Best Time to Buy and Sell Stocks.cpp ├── 030 Binary Search.cpp ├── 016 Remove Duplicates from Sorted List.cpp ├── 053 Max Consecutive Ones.cpp ├── 058 Longest Palindrome.cpp ├── 009 Search Insert Position.cpp ├── Symmetric Tree.cpp ├── 026 Remove Linkedlist Elements.cpp ├── 034 First Bad Version.cpp ├── 010 Longest Common prefix.cpp ├── 059 Count Negative Numbers in a Sorted Matrix.cpp ├── 043 Toeplitz Matrix.cpp ├── 004 Integer to Roman.cpp ├── Reverse Words in a String III.cpp ├── 021 Happy Number.cpp ├── 025 Contains Duplicate II.cpp ├── 012 Plus One.cpp ├── 005 Roman to Integer.cpp ├── 020 Valid Palindrome.cpp ├── 023 LinkedList Cycle.cpp ├── 015 Climbing Stairs.cpp ├── Range Sum of BST.cpp ├── 060 Minimum Absolute Difference in BST.cpp ├── 032 Number Complement.cpp ├── Minimum Changes To Make Alternating Binary String.cpp ├── Subtree of Another Tree.cpp ├── 039 Diameter of Binary Tree.cpp ├── 001 Two Sums.cpp ├── 050 Kids With the Greatest Number of Candies.cpp ├── 017 Majority Element.cpp ├── 013 Add Binary.cpp ├── 045 Minimum Distance Between BST Nodes.cpp ├── 062 Valid Pallindrome.cpp ├── Convert Sorted Array to Binary Search Tree.cpp ├── 044 Strong Password Checker II.cpp ├── Unique Number of Occurrences.cpp ├── 006 Merge Two Sorted Linked Lists.cpp ├── Determine if String Halves Are Alike.cpp ├── 048 Implement Queue using Stack.cpp ├── Island Perimeter.cpp ├── 056 Middle of the Linked List.cpp ├── Assign Cookies.cpp ├── 041 Verifying an Alien Dictionary.cpp ├── 037 Inorder Using Stack.cpp ├── 049 Implement Stack using Queues.cpp └── 002 Valid Parenthesis.cpp ├── Medium Problems ├── Search in Rotated Sorted Array.cpp ├── Number of Substrings With Only 1s.cpp ├── Maximum Subarray.cpp ├── Integer Break.cpp ├── Minimize Maximum of Array.cpp ├── Rotate Image.cpp ├── Subarray Sum Equals K.cpp ├── Number of Laser Beams in a Bank.cpp ├── Majority Element II.cpp ├── Min Stack.cpp ├── Container With Most Water.cpp ├── Next Greater Element II.cpp ├── Longest Increasing Subsequence.cpp ├── 001 Longest Substring Without Repeating Characters.cpp ├── Word Break.cpp ├── Permutations.cpp ├── Permutation in String.cpp ├── Removing Stars From a String.cpp ├── Boats to Save People.cpp ├── Lowest Common Ancestor of a Binary Tree.cpp ├── Minimum Number of Steps to Make Two Strings Anagram.cpp ├── Equal Row and Column Pairs.cpp ├── Jump Game II.cpp ├── Minimum Number of Operations to Make Array.cpp ├── Linked List Cycle II.cpp ├── Unique Paths.cpp ├── Search a 2D Matrix.cpp ├── Fruit into Basket.cpp ├── Partition Equal Subset Sum.cpp ├── Sum of Absolute Differences in a Sorted Array.cpp ├── ZigZag Conversion.cpp ├── Combination Sum.cpp ├── Convert an Array Into a 2D Array With Conditions.cpp ├── Set Matrix Zeroes.cpp ├── Validate Binary Search.cpp ├── Implement Trie (Prefix Tree).cpp ├── Maximum Length of a Concatenated String with Unique Characters.cpp ├── 3Sum.cpp ├── Binary Tree Zigzag Level Order Traversal.cpp ├── Successful Pairs of Spells and Potions.cpp ├── Find All Anagrams in a String.cpp ├── Insert Delete GetRandom O(1).cpp ├── Find Players With Zero or One Losses.cpp ├── Sum Root to leaf Number.cpp ├── Simplify Path.cpp ├── Smallest String Starting From Leaf.cpp ├── Longest Palindromic Substring.cpp ├── Rotting Oranges.cpp ├── Evaluate Reverse Polish Notation.cpp ├── Accounts Merge.cpp ├── Number of Islands.cpp ├── Valid Sudoku.cpp ├── Spiral Matrix.cpp ├── Amount of Time for Binary Tree to Be Infected.cpp └── Number of Enclaves.cpp ├── readme.md ├── Hard Problems ├── 001 Naming a Company.cpp ├── 003 Trapping Rain Water.cpp ├── Subarrays with K Different Integers.cpp ├── Arithmetic Slices II - Subsequence.cpp ├── Serialize and Deserialize Binary Tree.cpp ├── Word Ladder.cpp ├── Maximal Rectangle.cpp ├── 002 Largest Rectangle in Histogram.cpp ├── Maximum Profit in Job Scheduling.cpp └── 004 Count of Smaller Numbers After Self.cpp └── LICENSE /Easy Problems/028 Power of Two.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/power-of-two/ 2 | 3 | class Solution { 4 | public: 5 | bool isPowerOfTwo(int n) { 6 | if(n==0) return 0; 7 | 8 | while(n%2==0) 9 | n /=2; 10 | 11 | return n==1; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Easy Problems/027 Number of 1 Bits.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/number-of-1-bits/ 2 | 3 | class Solution { 4 | public: 5 | int hammingWeight(uint32_t n) { 6 | int count=0; 7 | while(n){ 8 | n &= (n-1); 9 | count++; 10 | } 11 | return count; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Easy Problems/019 Single Number.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/single-number/ 2 | 3 | class Solution { 4 | public: 5 | int singleNumber(vector& nums) { 6 | int ans=0; 7 | for(int i=0; i& nums) { 6 | int ans=0; 7 | for(int i=0; i& nums) { 5 | int answer=1; 6 | for(int i=1; i& nums) { 6 | set elements; 7 | elements.insert(nums.begin(),nums.end()); 8 | 9 | return nums.size() != elements.size(); 10 | return false; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Easy Problems/029 Same Tree.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/same-tree 2 | 3 | class Solution { 4 | public: 5 | bool isSameTree(TreeNode* p, TreeNode* q) { 6 | if (p == NULL || q == NULL) 7 | return (p == q); 8 | 9 | return (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right)); 10 | } 11 | 12 | }; 13 | -------------------------------------------------------------------------------- /Easy Problems/052 Missing Numbers.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/missing-number/description/ 2 | 3 | class Solution { 4 | public: 5 | int missingNumber(vector& nums) { 6 | int ans=0; 7 | for(int i=0;i& nums, int target) { 6 | for(int i=0; iINT_MAX || numleft, root->right); 9 | invertTree(root->left); 10 | invertTree(root->right); 11 | 12 | return root; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Easy Problems/031 Ugly Number.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/ugly-number/ 2 | 3 | class Solution { 4 | public: 5 | bool isUgly(int n) { 6 | if(n<=0) return false; 7 | 8 | while(n>1){ 9 | if(n%2==0) n = n/2; 10 | else if(n%3==0) n=n/3; 11 | else if(n%5==0) n=n/5; 12 | else break; 13 | } 14 | 15 | return n==1; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Easy Problems/040 Greatest Common Divisor of Strings.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/greatest-common-divisor-of-strings/description/ 2 | 3 | class Solution { 4 | public: 5 | string gcdOfStrings(string str1, string str2) { 6 | if(str1 + str2 == str2 + str1){ 7 | return str1.substr(0, gcd(str1.length(), str2.length())); 8 | } 9 | return ""; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /Easy Problems/011 Length of Last Word.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/length-of-last-word/ 2 | 3 | class Solution{ 4 | public: 5 | int lengthOfLastWord(string s){ 6 | int ans=0; 7 | for(int i=s.size()-1; i>=0; i--){ 8 | if(s[i] != ' ') ans++; 9 | else if(s[i] == ' ' && ans>0) return ans; 10 | } 11 | 12 | return ans; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Easy Problems/033 Add Digits.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/add-digits/description/ 2 | 3 | class Solution { 4 | public: 5 | int addDigits(int num) { 6 | int sum=0; 7 | while(num) 8 | { 9 | sum+=(num%10); 10 | num/=10; 11 | } 12 | if(sum<10) 13 | return sum; 14 | else 15 | return addDigits(sum); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Easy Problems/051 Move Zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void moveZeroes(vector& nums) { 4 | int n = nums.size(); 5 | int lastNonZeroFoundAt = 0; 6 | for (int i = 0; i < n; i++) { 7 | if (nums[i] != 0) { 8 | swap(nums[i], nums[lastNonZeroFoundAt]); 9 | lastNonZeroFoundAt++; 10 | } 11 | } 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Easy Problems/003 Palindrome Number.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/palindrome-number/ 2 | 3 | class Solution { 4 | public: 5 | bool isPalindrome(int x) { 6 | if(x<0|| (x!=0 &&x%10==0)) 7 | return false; 8 | int sum=0; 9 | while(x>sum) 10 | { 11 | sum = sum*10+x%10; 12 | x = x/10; 13 | } 14 | return (x==sum)||(x==sum/10); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Easy Problems/038 Merge Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/merge-sorted-array/ 2 | 3 | class Solution { 4 | public: 5 | void merge(vector& nums1, int m, vector& nums2, int n) { 6 | int j=0; 7 | for(int i=m; i> 1; 13 | } 14 | 15 | return res; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Easy Problems/036 InOrder Traversal.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/binary-tree-inorder-traversal/description/ 2 | 3 | vector vec; 4 | void order(TreeNode* root){ 5 | if(!root) 6 | return; 7 | order(root->left); 8 | vec.push_back(root->val); 9 | order(root->right); 10 | } 11 | 12 | 13 | vector inorderTraversal(TreeNode* root){ 14 | order(root); 15 | return vec; 16 | 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Easy Problems/057 Valid Anagram.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/valid-anagram/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isAnagram(string s, string t) { 6 | if(s.size() != t.size()){ 7 | return false; 8 | } 9 | 10 | sort(s.begin(), s.end()); 11 | sort(t.begin(), t.end()); 12 | 13 | if(s == t) return true; 14 | 15 | return false; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Easy Problems/061 Find the Highest Altitude.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/find-the-highest-altitude/ 2 | 3 | class Solution { 4 | public: 5 | int largestAltitude(vector& gain) { 6 | int max_altitude = 0; 7 | int current = 0; 8 | for(auto i:gain){ 9 | current += i; 10 | max_altitude = max(max_altitude,current); 11 | } 12 | return max_altitude; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Easy Problems/035 Height of Tree.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/maximum-depth-of-binary-tree/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxDepth(TreeNode* root) { 6 | if(root == NULL ) 7 | return 0; 8 | int maxLeft = maxDepth(root->left); //cause height is starting from 1 9 | int maxRight = maxDepth(root->right); 10 | return max(maxLeft, maxRight)+1; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Medium Problems/Number of Substrings With Only 1s.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/number-of-substrings-with-only-1s/description/ 2 | 3 | class Solution { 4 | public: 5 | int numSub(string s) { 6 | unsigned int result=0, streak=0; 7 | for(int i=0; i= mid) low = mid+1; 12 | else high = mid; 13 | } 14 | return high-1; 15 | 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Easy Problems/024 Reverse Linkedlist.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/reverse-linked-list/submissions/ 2 | 3 | class Solution { 4 | public: 5 | ListNode* reverseList(ListNode* head) { 6 | ListNode *prev = NULL, *cur=head, *tmp; 7 | while(cur){ 8 | tmp = cur->next; 9 | cur->next = prev; 10 | prev = cur; 11 | cur = tmp; 12 | } 13 | return prev; 14 | 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Easy Problems/008 Remove Element.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/remove-element/ 2 | 3 | class Solution { 4 | public: 5 | int removeElement(vector& nums, int val) { 6 | int index = 0; 7 | for (int i = 0; i < nums.size(); ++i) { 8 | if (nums[i] != val) { 9 | nums[index++] = nums[i]; 10 | } 11 | } 12 | return index; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Easy Problems/047 Single Element in a sorted Array.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/single-element-in-a-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int singleNonDuplicate(vector& nums) { 6 | map mp; 7 | for(auto i: nums){ 8 | mp[i]++; 9 | } 10 | 11 | for(auto i: mp){ 12 | if(i.second==1) return i.first; 13 | } 14 | return -1; 15 | 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Easy Problems/055 Can Make Arithmetic Progression From Sequence .cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canMakeArithmeticProgression(std::vector& arr) { 4 | sort(arr.begin(), arr.end()); 5 | int diff = arr[1] - arr[0]; 6 | 7 | for (int i = 2; i < arr.size(); i++) { 8 | if (arr[i] - arr[i-1] != diff) { 9 | return false; 10 | } 11 | } 12 | 13 | return true; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Easy Problems/018 Best Time to Buy and Sell Stocks.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 2 | 3 | class Solution { 4 | public: 5 | int maxProfit(vector& prices) { 6 | int mini=INT_MAX; 7 | int maxi=INT_MIN; 8 | for(int i=0; i& nums, int target) { 6 | int low=0, high=nums.size()-1; 7 | 8 | while(low<=high){ 9 | int mid=high-low/2; 10 | if(nums[mid]==target) return mid; 11 | else if(nums[mid]>target) high=mid-1; 12 | else low = mid+1; 13 | } 14 | 15 | return -1; 16 | } 17 | 18 | }; 19 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ## Welcome 2 | In this repo I upload solution of problems and contest that I have given on Leetcode, if you wanna help with any these solution you can ask me on [Twitter](https://twitter.com/its_aman_yadav) 3 | if you like this repo please give it a star ⭐ 4 | 5 | ## Connect with me 6 | 7 | * [Linkedin](https://www.linkedin.com/in/itsamanyadav18/) 8 | * [Twitter](https://twitter.com/its_aman_yadav) 9 | * [Instagram](https://instagram.com/its_aman_yadav) 10 | 11 | -------------------------------------------------------------------------------- /Easy Problems/016 Remove Duplicates from Sorted List.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/remove-duplicates-from-sorted-list/ 2 | 3 | class Solution { 4 | public: 5 | ListNode* deleteDuplicates(ListNode* head) { 6 | ListNode* cur = head; 7 | while(cur) { 8 | while(cur->next && cur->val == cur->next->val) { 9 | cur->next = cur->next->next; 10 | } 11 | cur = cur->next; 12 | } 13 | return head; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Medium Problems/Maximum Subarray.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/maximum-subarray/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxSubArray(vector& nums) { 6 | int n = nums.size(); 7 | int sum = 0; 8 | int maxi = INT_MIN; 9 | 10 | for(int i=0; imaxi) maxi = sum; 13 | 14 | if(sum<0) sum = 0; 15 | } 16 | return maxi; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Easy Problems/053 Max Consecutive Ones.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/max-consecutive-ones/ 2 | 3 | class Solution { 4 | public: 5 | int findMaxConsecutiveOnes(vector& nums) { 6 | int ans=0; 7 | int count=0; 8 | for(int i=0; i4){ 11 | result *= 3; 12 | n -= 3; 13 | } 14 | 15 | result *= n; 16 | return result; 17 | 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Medium Problems/Minimize Maximum of Array.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/minimize-maximum-of-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int minimizeArrayValue(vector& nums) { 6 | long long sum = 0; 7 | long long result = 0; 8 | for (int index = 0; index < nums.size(); ++index) { 9 | sum += nums[index]; 10 | result = max(result, (sum + index) / (index + 1)); 11 | } 12 | return (int) result; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Medium Problems/Rotate Image.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/rotate-image/description/ 2 | 3 | class Solution { 4 | public: 5 | void rotate(vector>& matrix) { 6 | int n = matrix.size(); 7 | for(int i=0; i mp; 8 | for(char ch: s){ 9 | mp[ch]++; 10 | 11 | if(mp[ch] % 2 == 1) oddCount++; 12 | else oddCount--; 13 | } 14 | 15 | if(oddCount > 1) return s.size()-oddCount+1; 16 | return s.size(); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Medium Problems/Subarray Sum Equals K.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/subarray-sum-equals-k/ 2 | 3 | class Solution { 4 | public: 5 | int subarraySum(vector& nums, int k) { 6 | unordered_map map; 7 | 8 | int sum = 0, result = 0; 9 | map[sum] = 1; 10 | 11 | for (int n : nums) { 12 | sum += n; 13 | result += map[sum - k]; 14 | map[sum]++; 15 | } 16 | 17 | return result; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Easy Problems/009 Search Insert Position.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/search-insert-position/submissions/ 2 | 3 | class Solution { 4 | public: 5 | int searchInsert(vector& nums, int target) { 6 | int lo = 0, hi = nums.size()-1, mid; 7 | while (lo <= hi) { 8 | mid = (lo + hi) / 2; 9 | if (nums[mid] == target) return mid; 10 | else if (nums[mid] < target) lo = mid + 1; 11 | else hi = mid - 1; 12 | } 13 | return lo; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Medium Problems/Number of Laser Beams in a Bank.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/number-of-laser-beams-in-a-bank/?envType=daily-question&envId=2024-01-03 2 | 3 | class Solution { 4 | public: 5 | int numberOfBeams(vector& bank) { 6 | int ans=0; int temp=0; 7 | for(int i=0; ival == right->val) && isMirror(left->left, right->right) && isMirror(left->right, right->left); 9 | } 10 | 11 | bool isSymmetric(TreeNode* root) { 12 | if (!root) return true; 13 | return isMirror(root->left, root->right); 14 | } 15 | 16 | }; 17 | -------------------------------------------------------------------------------- /Medium Problems/Majority Element II.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/majority-element-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | vector majorityElement(vector& nums) { 6 | map mp; 7 | vector ans; 8 | for(int i=0; inums.size()/3){ 14 | ans.push_back(i.first); 15 | } 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Medium Problems/Min Stack.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/min-stack/description/ 2 | 3 | class MinStack { 4 | public: 5 | vector< pair > s; 6 | 7 | MinStack() { } 8 | 9 | void push(int val) { 10 | if(s.empty()) 11 | s.push_back({val,val}); 12 | else 13 | s.push_back({val,min(s.back().second,val)}); 14 | } 15 | 16 | void pop() { s.pop_back(); } 17 | 18 | int top() { return s.back().first; } 19 | 20 | int getMin() { return s.back().second; } 21 | }; 22 | -------------------------------------------------------------------------------- /Easy Problems/026 Remove Linkedlist Elements.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/remove-linked-list-elements/ 2 | 3 | class Solution { 4 | public: 5 | ListNode* removeElements(ListNode* head, int val) { 6 | while(head && head->val == val) head = head->next; 7 | 8 | ListNode* cur = head; 9 | while(cur){ 10 | if(cur->next && cur->next->val == val) 11 | cur->next = cur->next->next; 12 | else cur = cur->next; 13 | 14 | } 15 | return head; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Easy Problems/034 First Bad Version.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/first-bad-version/description/ 2 | 3 | class Solution { 4 | public: 5 | int firstBadVersion(int n) { 6 | int left=0; 7 | int right = n; 8 | int ans=0; 9 | 10 | while(left<=right){ 11 | long long mid = left + (right-left)/2; 12 | if(isBadVersion(mid)==true){ 13 | right = mid-1; 14 | ans = mid; 15 | } 16 | 17 | else left = mid+1; 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Easy Problems/010 Longest Common prefix.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/longest-common-prefix/ 2 | 3 | class Solution { 4 | public: 5 | string longestCommonPrefix(vector& strs){ 6 | int n =strs.size(); 7 | string ans; 8 | sort(strs.begin(), strs.end()); 9 | string a = strs[0]; 10 | string b = strs[n-1]; 11 | for(int i =0; i< a.size(); i++){ 12 | if(a[i] == b[i]){ 13 | ans += a[i]; 14 | }else break; 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Easy Problems/059 Count Negative Numbers in a Sorted Matrix.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/description/ 2 | 3 | class Solution { 4 | public: 5 | int countNegatives(vector>& grid) { 6 | int count = 0; 7 | for (int i = 0; i < grid.size(); i++) { 8 | for (int j = 0; j < grid[i].size(); j++) { 9 | if (grid[i][j] < 0) { 10 | count++; 11 | } 12 | } 13 | } 14 | 15 | return count; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Easy Problems/043 Toeplitz Matrix.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/toeplitz-matrix/ 2 | 3 | class Solution { 4 | public: 5 | bool isToeplitzMatrix(vector>& matrix) { 6 | int row = matrix.size(); 7 | int col = matrix[0].size(); 8 | 9 | for(int i = 0; i < row-1; i++){ 10 | for(int j = 0; j < col-1; j++){ 11 | if(matrix[i][j] != matrix[i+1][j+1]) 12 | return false; 13 | } 14 | } 15 | 16 | return true; 17 | 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Easy Problems/004 Integer to Roman.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/integer-to-roman/ 2 | 3 | class Solution { 4 | public: 5 | string intToRoman(int num) { 6 | string ones[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"}; 7 | string tens[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}; 8 | string hrns[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}; 9 | string ths[]={"","M","MM","MMM"}; 10 | 11 | return ths[num/1000] + hrns[(num%1000)/100] + tens[(num%100)/10] + ones[num%10]; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Easy Problems/Reverse Words in a String III.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/reverse-words-in-a-string-iii/description/ 2 | 3 | class Solution { 4 | public: 5 | string reverseWords(string s) { 6 | int n = s.size(); 7 | int i=0; 8 | int j = 0; 9 | while(j us; 7 | int ans=n; 8 | while(true){ 9 | int temp=0; 10 | while(ans){ 11 | temp+=pow(ans%10,2); 12 | ans/=10; 13 | } 14 | ans=temp; 15 | if(ans==1) return true; 16 | if(us.count(ans)) 17 | return false; 18 | us.insert(ans); 19 | } 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Easy Problems/025 Contains Duplicate II.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/contains-duplicate-ii/ 2 | 3 | class Solution { 4 | public: 5 | bool containsNearbyDuplicate(vector& nums, int k) { 6 | unordered_map Map; 7 | int n = nums.size(); 8 | for(int i=0; i& height) { 6 | int i=0, j = height.size()-1; 7 | int ans=0; 8 | while(iheight[j]){ 10 | ans = max(ans, (j-i)*height[j]); 11 | j--; 12 | } 13 | 14 | else{ 15 | ans = max(ans, (j-i)*height[i]); 16 | i++; 17 | } 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Easy Problems/012 Plus One.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/plus-one/ 2 | 3 | class Solution{ 4 | public: 5 | 6 | vector plusOne(vector& digits) { 7 | for(int i=digits.size()-1; i>=0; i--){ 8 | if(digits[i]!=9){ 9 | digits[i]++; 10 | return digits; 11 | } 12 | 13 | else 14 | digits[i]=0; 15 | 16 | 17 | } 18 | 19 | digits.insert(digits.begin(),1); 20 | return digits; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Easy Problems/005 Roman to Integer.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/roman-to-integer/ 2 | 3 | class Solution { 4 | public: 5 | int romanToInt(string s) { 6 | unordered_map mp{ 7 | {'I',1}, 8 | {'V',5}, 9 | {'X',10}, 10 | {'L',50}, 11 | {'C',100}, 12 | {'D',500}, 13 | {'M',1000}, 14 | }; 15 | int ans =0; 16 | for(int i=0;inext != NULL){ 13 | fast=fast->next->next; 14 | slow=slow->next; 15 | 16 | if(slow==fast) 17 | return true; 18 | } 19 | 20 | return false; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Easy Problems/015 Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/climbing-stairs/ 2 | 3 | class Solution { 4 | public: 5 | public: 6 | int climbStairs(int n) { 7 | // base cases 8 | if(n <= 0) return 0; 9 | if(n == 1) return 1; 10 | if(n == 2) return 2; 11 | 12 | int one_step_before = 2; 13 | int two_steps_before = 1; 14 | int all_ways = 0; 15 | 16 | for(int i=2; ival >= low && root->val <= high) ? root->val : 0; 11 | 12 | int leftSum = rangeSumBST(root->left, low, high); 13 | int rightSum = rangeSumBST(root->right, low, high); 14 | 15 | return currentVal + leftSum + rightSum; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Medium Problems/Next Greater Element II.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/next-greater-element-ii/ 2 | 3 | class Solution { 4 | public: 5 | vector nextGreaterElements(vector& nums) { 6 | int n = nums.size(); 7 | vector < int > nge(n, -1); 8 | stack < int > st; 9 | for (int i = 2 * n - 1; i >= 0; i--) { 10 | while (!st.empty() && st.top() <= nums[i % n]) { 11 | st.pop(); 12 | } 13 | 14 | if (i < n) { 15 | if (!st.empty()) nge[i] = st.top(); 16 | } 17 | st.push(nums[i % n]); 18 | } 19 | return nge; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Easy Problems/060 Minimum Absolute Difference in BST.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/minimum-absolute-difference-in-bst/ 2 | 3 | class Solution { 4 | public: 5 | vectorv; 6 | 7 | void inorder(TreeNode* root){ 8 | 9 | if(root == NULL) 10 | return ; 11 | 12 | inorder(root->left); 13 | v.push_back(root->val); 14 | inorder(root->right); 15 | 16 | } 17 | int getMinimumDifference(TreeNode* root) { 18 | 19 | inorder(root); 20 | 21 | int ans=INT_MAX; 22 | for(int i=1;i& nums) { 6 | if(nums.empty()) return 0; 7 | 8 | int n = nums.size(); 9 | vector dp(n, 1); 10 | 11 | for(int i=0; i nums[j]){ 14 | dp[i] = max(dp[i], dp[j]+1); 15 | } 16 | } 17 | } 18 | 19 | return *max_element(dp.begin(), dp.end()); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Easy Problems/032 Number Complement.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/number-complement/ 2 | 3 | class Solution { 4 | public: 5 | int findComplement(int num) { 6 | vector temp; 7 | while( num != 0 ){ 8 | temp.push_back( num % 2 ); 9 | num /= 2; 10 | } 11 | 12 | for(int i=0; i-1; i--) 19 | res = res * 2 + temp[i]; 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Easy Problems/Minimum Changes To Make Alternating Binary String.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/description/?envType=daily-question&envId=2024-01-03 2 | 3 | class Solution { 4 | public: 5 | int minOperations(string s) { 6 | int c0 = 0; 7 | int c1 = 0; 8 | 9 | for(int i=0; imp(128,0); 9 | for(int i=0;i1){ 14 | mp[s[j]]--; 15 | j++; 16 | } 17 | ans=max(ans,i-j+1); 18 | } 19 | return ans; 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Medium Problems/Word Break.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/word-break/description/ 2 | 3 | class Solution { 4 | public: 5 | bool wordBreak(string s, vector& wordDict) { 6 | int n = s.size(); 7 | vector dp(n+1, false); 8 | dp[0] = true; 9 | 10 | for (int i = 0; i < n; i++) { 11 | if (dp[i]) { 12 | for (int j = 0; j < wordDict.size(); j++) { 13 | int wSize = wordDict[j].size(); 14 | if (wSize + i <= n) { 15 | string compairS = s.substr(i, wSize); 16 | if (compairS == wordDict[j]) 17 | dp[i+wSize] = true; 18 | } 19 | } 20 | } 21 | } 22 | 23 | return dp[n]; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Medium Problems/Permutations.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/permutations/description/ 2 | 3 | class Solution { 4 | public: 5 | vector>v; 6 | void solve(vector&a,int idx) 7 | { 8 | if(idx >= a.size()) 9 | { 10 | v.push_back(a); 11 | return; 12 | } 13 | for(int i = idx; i < a.size(); i++) 14 | { 15 | swap(a[i],a[idx]); 16 | solve(a,idx+1); 17 | swap(a[i],a[idx]); 18 | } 19 | } 20 | 21 | vector> permute(vector& a) { 22 | vectorp; 23 | solve(a,0); 24 | return v; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Easy Problems/Subtree of Another Tree.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subtree-of-another-tree/ 2 | 3 | 4 | class Solution { 5 | public: 6 | bool check(TreeNode* p, TreeNode* q) { 7 | if (!p || !q) { 8 | return !p && !q; 9 | } 10 | return p->val == q->val && check(p->left, q->left) && 11 | check(p->right, q->right); 12 | } 13 | bool isSubtree(TreeNode* root, TreeNode* subRoot) { 14 | if (!root) 15 | return false; 16 | if (check(root, subRoot)) 17 | return true; 18 | return isSubtree(root->left, subRoot) || 19 | isSubtree(root->right, subRoot); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Medium Problems/Permutation in String.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/permutation-in-string/ 2 | 3 | class Solution { 4 | public: 5 | bool checkInclusion(string s1, string s2) { 6 | int s1_len=s1.size(); 7 | int s2_len=s2.size(); 8 | if(s1_len>s2_len) 9 | { 10 | return false; 11 | } 12 | sort(s1.begin(),s1.end()); 13 | for(int i=0;i<=(s2_len-s1_len);i++) 14 | { 15 | string wd=s2.substr(i,s1_len); 16 | sort(wd.begin(),wd.end()); 17 | if(wd==s1) 18 | { 19 | return true; 20 | } 21 | } 22 | return false; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Medium Problems/Removing Stars From a String.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/removing-stars-from-a-string/description/ 2 | 3 | class Solution { 4 | public: 5 | string removeStars(string s) { 6 | stack st; 7 | for (char c : s) { 8 | 9 | if (c == '*' && !st.empty()) { 10 | st.pop(); 11 | } else { 12 | st.push(c); 13 | } 14 | } 15 | 16 | string ans; 17 | 18 | while (!st.empty()) { 19 | ans += st.top(); 20 | st.pop(); 21 | } 22 | 23 | reverse(ans.begin(), ans.end()); 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Medium Problems/Boats to Save People.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/boats-to-save-people/description/ 2 | 3 | class Solution { 4 | public: 5 | int numRescueBoats(vector& people, int limit) { 6 | sort(people.begin(), people.end()); 7 | int count=0; 8 | int left=0; 9 | int right = people.size()-1; 10 | while(left<=right){ 11 | if(people[left]+people[right]<=limit){ 12 | left++; 13 | right--; 14 | count++; 15 | } 16 | 17 | else{ 18 | right--; 19 | count++; 20 | } 21 | } 22 | return count; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Medium Problems/Lowest Common Ancestor of a Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/ 2 | 3 | class Solution { 4 | public: 5 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 6 | 7 | if(root==NULL) return root; 8 | if(root==p || root==q ) return root; 9 | 10 | TreeNode* leftans = lowestCommonAncestor(root->left, p, q); 11 | 12 | TreeNode* rightans = lowestCommonAncestor(root->right, p, q); 13 | 14 | if(leftans==NULL) return rightans; 15 | else if(rightans==NULL) return leftans; 16 | 17 | else return root; 18 | 19 | 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Medium Problems/Minimum Number of Steps to Make Two Strings Anagram.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/description/ 2 | 3 | class Solution { 4 | public: 5 | int minSteps(string s, string t) { 6 | vector count_s(26, 0); 7 | vector count_t(26, 0); 8 | 9 | for (char ch : s) { 10 | count_s[ch - 'a']++; 11 | } 12 | 13 | for (char ch : t) { 14 | count_t[ch - 'a']++; 15 | } 16 | 17 | int steps = 0; 18 | for (int i = 0; i < 26; i++) { 19 | steps += abs(count_s[i] - count_t[i]); 20 | } 21 | 22 | return steps / 2; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Easy Problems/039 Diameter of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/diameter-of-binary-tree/description/ 2 | 3 | class Solution { 4 | public: 5 | int height(TreeNode* root){ 6 | if(root == NULL) return 0; 7 | int ans = max(height(root->left),height(root->right)) +1; 8 | return ans; 9 | } 10 | 11 | int diameterOfBinaryTree(TreeNode* root) { 12 | if(root == NULL) return 0; 13 | int left = diameterOfBinaryTree(root->left); 14 | int right = diameterOfBinaryTree(root->right); 15 | int sum_of_height= height(root->left) + height(root->right); 16 | 17 | int ans = max(sum_of_height,max(left,right)); 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Medium Problems/Equal Row and Column Pairs.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/equal-row-and-column-pairs/description/ 2 | 3 | class Solution { 4 | public: 5 | int equalPairs(vector>& grid) { 6 | map, int> counter; 7 | int row = grid.size(), col = grid[0].size(), ans = 0; 8 | for (vector row : grid) { 9 | counter[row] += 1; 10 | } 11 | for (int i = 0; i < row; i++) { 12 | vector column_list = {}; 13 | for (int j = 0; j < col; j++) { 14 | column_list.push_back(grid[j][i]); 15 | } 16 | ans += counter[column_list]; 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Easy Problems/001 Two Sums.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/two-sum/ 2 | 3 | class Solution { 4 | public: 5 | 6 | vector twoSum(vector& nums, int target) { 7 | vector index; 8 | int size=nums.size(); 9 | for(int i=0;i kidsWithCandies(vector& candies, int extraCandies) { 6 | int max_candies = *max_element(candies.begin(), candies.end()); 7 | 8 | vector result(candies.size()); 9 | 10 | for (int i = 0; i < candies.size(); i++) { 11 | if (candies[i] + extraCandies >= max_candies) { 12 | result[i] = true; 13 | } else { 14 | result[i] = false; 15 | } 16 | } 17 | 18 | return result; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Medium Problems/Jump Game II.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/jump-game-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | int jump(vector& nums) { 6 | int reachfar=0; 7 | int jumps=0; 8 | int current=0; 9 | if(nums.size()==1){ 10 | return 0; 11 | } 12 | 13 | 14 | for(int i=0;i=nums.size()-1){ 17 | break; 18 | } 19 | 20 | if(i==current){ 21 | current=reachfar; 22 | jumps++; 23 | } 24 | 25 | } 26 | return jumps; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Medium Problems/Minimum Number of Operations to Make Array.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/minimum-number-of-operations-to-make-array-empty/description/?envType=daily-question&envId=2024-01-04 2 | 3 | class Solution { 4 | public: 5 | int minOperations(vector& nums) { 6 | sort(nums.begin(), nums.end()); 7 | int res = 0; 8 | int s = 0; 9 | while(s < nums.size()){ 10 | int e=s; 11 | while( e< nums.size() && nums[e] ==nums[s]){ 12 | e++; 13 | } 14 | 15 | int count = e-s; 16 | if(count == 1) return -1; 17 | res += count/3; 18 | 19 | if(count%3 != 0) res++; 20 | s=e; 21 | 22 | } 23 | return res; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Medium Problems/Linked List Cycle II.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/linked-list-cycle-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | ListNode *detectCycle(ListNode *head) { 6 | ListNode* fast = head; 7 | ListNode* slow = head; 8 | ListNode* cur = head; 9 | 10 | while(fast != NULL && fast->next != NULL && slow != NULL){ 11 | fast = fast->next->next; 12 | slow = slow->next; 13 | 14 | if(fast==slow){ 15 | while(cur != fast){ 16 | cur= cur->next; 17 | fast = fast->next; 18 | } 19 | return cur; 20 | } 21 | } 22 | 23 | return NULL; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Medium Problems/Unique Paths.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/unique-paths/description/ 2 | 3 | class Solution { 4 | public: 5 | int uniquePaths(int m, int n) { 6 | vectorprev(n,0); 7 | for(int i=0;itemp(n,0); 9 | for(int j=0;j0) 17 | l=prev[j]; 18 | if(j>0) 19 | r=temp[j-1]; 20 | temp[j]=l+r; 21 | } 22 | } 23 | prev=temp; 24 | } 25 | return prev[n-1]; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Medium Problems/Search a 2D Matrix.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/search-a-2d-matrix/description/ 2 | 3 | class Solution { 4 | public: 5 | bool searchMatrix(vector>& matrix, int target) { 6 | int n=matrix.size(); 7 | int m=matrix[0].size(); 8 | int st=0; 9 | int end=(n*m)-1; 10 | while(st<=end){ 11 | int mid=st+(end-st)/2; 12 | if(matrix[mid / matrix[0].size()][mid % matrix[0].size() ]== target){ 13 | return true; 14 | } 15 | if(matrix[mid/matrix[0].size()][mid%matrix[0].size() ]< target){st=mid+1;} 16 | else { 17 | end=mid-1; 18 | } 19 | } 20 | return false; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Easy Problems/017 Majority Element.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/majority-element/ 2 | 3 | class Solution { 4 | public: 5 | int majorityElement(vector& nums) { 6 | sort(nums.begin(), nums.end()); 7 | 8 | int count = 1; 9 | int size = nums.size(); 10 | 11 | if(size == 1 || size == 2){ 12 | return nums[0]; 13 | } 14 | 15 | for(int i = 0; i < size; i++){ 16 | if(nums[i] == nums[i+1]){ 17 | count++; 18 | }else{ 19 | 20 | if(count > (size/2)){ 21 | return nums[i]; 22 | } 23 | count = 1; 24 | } 25 | } 26 | 27 | return -1; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Easy Problems/013 Add Binary.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/add-binary/ 2 | 3 | class Solution { 4 | public: 5 | string addBinary(string a, string b) { 6 | int i = a.length()-1; 7 | int j = b.length()-1; 8 | string ans; 9 | int carry = 0; 10 | 11 | while(i>=0 || j>=0 || carry){ 12 | if(i>=0){ 13 | carry += a[i] - '0'; 14 | i--; 15 | } 16 | if(j>=0){ 17 | carry += b[j] - '0'; 18 | j--; 19 | } 20 | 21 | ans += (carry%2 + '0'); 22 | carry = carry/2; 23 | } 24 | reverse(ans.begin(),ans.end()); 25 | return ans; 26 | 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Medium Problems/Fruit into Basket.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/fruit-into-baskets/description/ 2 | 3 | class Solution { 4 | public: 5 | int totalFruit(vector& fruits) { 6 | map fruit_count; 7 | 8 | int i=0,j=0,ans=0; 9 | while (i2) 14 | { 15 | fruit_count[fruits[j]]--; 16 | 17 | if (fruit_count[fruits[j]]==0) { 18 | fruit_count.erase(fruits[j]); 19 | } 20 | j++; 21 | } 22 | 23 | ans=max(ans,i-j+1); 24 | i++; 25 | } 26 | return ans; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Easy Problems/045 Minimum Distance Between BST Nodes.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/ 2 | 3 | class Solution { 4 | public: 5 | vectorInorder; 6 | 7 | void inorder(TreeNode* root){ 8 | if(!root) 9 | return; 10 | else{ 11 | inorder(root->left); 12 | Inorder.push_back(root->val); 13 | inorder(root->right); 14 | } 15 | } 16 | 17 | int minDiffInBST(TreeNode* root) { 18 | if(!root) 19 | return 0; 20 | inorder(root); 21 | int res = INT_MAX; 22 | for(auto i=1;i& nums) { 6 | int sum = accumulate(nums.begin(), nums.end(), 0); 7 | vector dp(sum + 1, 0); 8 | if (sum&1) return false; 9 | dp[sum/2] = true; 10 | for (int i = 1; i < nums.size(); i++){ 11 | for (int currsum = sum; currsum >= sum/2; currsum--){ 12 | bool notTake = dp[currsum]; 13 | bool take = false; 14 | if (currsum >= nums[i]) take = dp[currsum - nums[i]]; 15 | dp[currsum] = notTake || take; 16 | } 17 | } 18 | return dp[sum]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Easy Problems/Convert Sorted Array to Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ 2 | 3 | class Solution { 4 | public: 5 | TreeNode* sortedArrayToBST(vector& nums) { 6 | return sortedArrayToBSTHelper(nums, 0, nums.size() - 1); 7 | } 8 | 9 | private: 10 | TreeNode* sortedArrayToBSTHelper(const vector& nums, int start, int end) { 11 | if (start > end) { 12 | return nullptr; 13 | } 14 | int mid = start + (end - start) / 2; 15 | TreeNode* root = new TreeNode(nums[mid]); 16 | root->left = sortedArrayToBSTHelper(nums, start, mid - 1); 17 | root->right = sortedArrayToBSTHelper(nums, mid + 1, end); 18 | return root; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Medium Problems/Sum of Absolute Differences in a Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/description/?envType=daily-question&envId=2024-01-04 2 | 3 | class Solution { 4 | public: 5 | vector getSumAbsoluteDifferences(vector& nums) { 6 | ios_base::sync_with_stdio(0), cout.tie(0), cin.tie(0); 7 | vector ans; 8 | int sum=0, cur=0, n = nums.size(); 9 | 10 | for(auto &it: nums){ 11 | sum += it; 12 | } 13 | 14 | for(int i=0; i& ideas) { 6 | long long ans = 0; 7 | vector> arr(26); 8 | for (string s : ideas) 9 | arr[s[0] - 'a'].insert(s.substr(1)); 10 | 11 | for (int i = 0; i < 25; i++) { 12 | for (int j = i + 1; j < 26; j++) { 13 | unordered_set set; 14 | set.insert(arr[i].begin(), arr[i].end()); 15 | set.insert(arr[j].begin(), arr[j].end()); 16 | ans += (arr[i].size() - set.size()) * (arr[j].size() - set.size()); 17 | } 18 | } 19 | return ans * 2; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Medium Problems/ZigZag Conversion.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/zigzag-conversion/description/ 2 | 3 | class Solution { 4 | public: 5 | string convert(string s, int numRows) { 6 | if(numRows<2) return s; 7 | int t[numRows][s.size()]; 8 | memset(t,-1, sizeof(t)); 9 | string ans; 10 | 11 | for(int i=0, changer=1, row=0; i='a' and c<='z') low = true; 10 | else if(c>='A' and c <='Z') upper = true; 11 | else if(isdigit(c)) digit = true; 12 | else special = true; 13 | } 14 | 15 | for(int i=0;i+1& arr) { 6 | sort(arr.begin(), arr.end()); 7 | vector v; 8 | 9 | for (int i = 0; i < arr.size(); i++) { 10 | int cnt = 1; 11 | 12 | // Count occurrences of the current element 13 | while (i + 1 < arr.size() && arr[i] == arr[i + 1]) { 14 | cnt++; 15 | i++; 16 | } 17 | 18 | v.push_back(cnt); 19 | } 20 | 21 | sort(v.begin(), v.end()); 22 | 23 | for (int i = 1; i < v.size(); i++) { 24 | if (v[i] == v[i - 1]) { 25 | return false; 26 | } 27 | } 28 | 29 | return true; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Easy Problems/006 Merge Two Sorted Linked Lists.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/merge-two-sorted-lists/ 2 | 3 | class Solution { 4 | public: 5 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 6 | 7 | ListNode *head = new ListNode(-1); 8 | ListNode *cur = head; 9 | 10 | while(l1 != nullptr && l2 != nullptr){ 11 | if(l1->val <= l2->val){ 12 | cur->next = l1; 13 | l1 = l1->next; 14 | } 15 | 16 | else{ 17 | cur->next = l2; 18 | l2 = l2->next; 19 | } 20 | 21 | cur = cur->next; 22 | } 23 | 24 | if (l1 != nullptr) 25 | cur->next = l1; 26 | 27 | else if (l2 != nullptr) 28 | cur->next = l2; 29 | 30 | return head->next; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Easy Problems/Determine if String Halves Are Alike.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/determine-if-string-halves-are-alike/description/?envType=daily-question&envId=2024-01-12 2 | 3 | 4 | class Solution { 5 | public: 6 | bool halvesAreAlike(string s) { 7 | auto countVowels = [](const string& str) { 8 | unordered_set vowels{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; 9 | int count = 0; 10 | for (char c : str) { 11 | if (vowels.count(c) > 0) { 12 | count++; 13 | } 14 | } 15 | return count; 16 | }; 17 | 18 | int length = s.length(); 19 | int midPoint = length / 2; 20 | 21 | string firstHalf = s.substr(0, midPoint); 22 | string secondHalf = s.substr(midPoint); 23 | 24 | return countVowels(firstHalf) == countVowels(secondHalf); 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Medium Problems/Combination Sum.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/combination-sum/description/ 2 | 3 | class Solution { 4 | public: 5 | vector> ans; 6 | void solve(int i, vector& arr, vector& temp, int target) 7 | { 8 | if(target == 0) 9 | { 10 | ans.push_back(temp); 11 | return; 12 | } 13 | 14 | if(target < 0) 15 | return; 16 | 17 | if(i == arr.size()) 18 | return; 19 | 20 | solve(i + 1, arr, temp, target); 21 | 22 | temp.push_back(arr[i]); 23 | solve(i, arr, temp, target - arr[i]); 24 | temp.pop_back(); 25 | 26 | } 27 | 28 | vector> combinationSum(vector& arr, int target) { 29 | ans.clear(); 30 | vector temp; 31 | solve(0, arr, temp, target); 32 | 33 | return ans; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Medium Problems/Convert an Array Into a 2D Array With Conditions.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/convert-an-array-into-a-2d-array-with-conditions/description/ 2 | 3 | class Solution { 4 | public: 5 | vector> findMatrix(vector& nums) { 6 | vector> ans; 7 | unordered_map mp; 8 | 9 | for (auto i : nums) { 10 | mp[i]++; 11 | } 12 | 13 | while (!mp.empty()) { 14 | vector temp; 15 | for (auto it = mp.begin(); it != mp.end();) { 16 | temp.push_back(it->first); 17 | it->second--; 18 | 19 | if (it->second == 0) { 20 | it = mp.erase(it); 21 | } else { 22 | it++; 23 | } 24 | } 25 | 26 | ans.push_back(temp); 27 | } 28 | 29 | return ans; 30 | } 31 | }; 32 | 33 | -------------------------------------------------------------------------------- /Easy Problems/048 Implement Queue using Stack.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/implement-queue-using-stacks/description/ 2 | 3 | #include 4 | 5 | class MyQueue { 6 | public: 7 | stack s1; 8 | stack s2; 9 | 10 | MyQueue() {} 11 | 12 | void push(int x) { 13 | s1.push(x); 14 | } 15 | 16 | int pop() { 17 | if (s2.empty()) { 18 | while (!s1.empty()) { 19 | s2.push(s1.top()); 20 | s1.pop(); 21 | } 22 | } 23 | 24 | int ans = s2.top(); 25 | s2.pop(); 26 | return ans; 27 | } 28 | 29 | int peek() { 30 | if (s2.empty()) { 31 | while (!s1.empty()) { 32 | s2.push(s1.top()); 33 | s1.pop(); 34 | } 35 | } 36 | 37 | return s2.top(); 38 | } 39 | 40 | bool empty() { 41 | return s1.empty() && s2.empty(); 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Medium Problems/Set Matrix Zeroes.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/set-matrix-zeroes/description/ 2 | 3 | class Solution { 4 | public: 5 | void setZeroes(vector>& matrix) { 6 | map m1; 7 | map m2; 8 | for(int i=0;i &nodes) 8 | { 9 | if(!root) 10 | return; 11 | 12 | inorder(root -> left, nodes); 13 | nodes.push_back(root -> val); 14 | inorder(root -> right, nodes); 15 | } 16 | 17 | bool isValidBST(TreeNode* root) 18 | { 19 | if(!root) 20 | return true; 21 | 22 | vector nodes; 23 | inorder(root, nodes); 24 | 25 | set s(nodes.begin(), nodes.end()); 26 | 27 | if(s.size() != nodes.size()) 28 | return false; 29 | 30 | for(int i = 0; i < nodes.size()-1; i++) 31 | { 32 | if(nodes[i] > nodes[i+1]) 33 | return false; 34 | } 35 | 36 | return true; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Hard Problems/003 Trapping Rain Water.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/trapping-rain-water/description/ 2 | 3 | class Solution { 4 | public: 5 | int trap(vector& height) { 6 | int n = height.size(); 7 | int left = 0, right = n - 1; 8 | int leftmax = 0, rightmax = 0; 9 | int res = 0; 10 | 11 | while (left <= right) { 12 | if (height[left] <= height[right]) { 13 | if (height[left] >= leftmax) { 14 | leftmax = height[left]; 15 | } else { 16 | res += leftmax - height[left]; 17 | } 18 | left++; 19 | } else { 20 | if (height[right] >= rightmax) { 21 | rightmax = height[right]; 22 | } else { 23 | res += rightmax - height[right]; 24 | } 25 | right--; 26 | } 27 | } 28 | return res; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Medium Problems/Implement Trie (Prefix Tree).cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/implement-trie-prefix-tree/description/ 2 | 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | class Trie { 9 | public: 10 | unordered_map> mp; 11 | unordered_map src; 12 | 13 | Trie() { 14 | unordered_map> ip; 15 | mp = ip; 16 | } 17 | 18 | void insert(string word) { 19 | mp[word[0]].push_back(word); 20 | src[word]++; 21 | } 22 | 23 | bool search(string word) { 24 | return src[word] > 0; 25 | } 26 | 27 | bool startsWith(string prefix) { 28 | if (mp.find(prefix[0]) == mp.end()) { 29 | return false; 30 | } 31 | for (auto x : mp[prefix[0]]) { 32 | if (x.find(prefix) == 0) { 33 | return true; 34 | } 35 | } 36 | return false; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Medium Problems/Maximum Length of a Concatenated String with Unique Characters.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxLength(vector& arr) { 6 | vector dp = {0}; 7 | int res = 0; 8 | 9 | for (const string& s : arr) { 10 | int a = 0, dup = 0; 11 | for (char c : s) { 12 | dup |= a & (1 << (c - 'a')); 13 | a |= 1 << (c - 'a'); 14 | } 15 | 16 | if (dup > 0) 17 | continue; 18 | 19 | for (int i = dp.size() - 1; i >= 0; i--) { 20 | if ((dp[i] & a) > 0) 21 | continue; 22 | dp.push_back(dp[i] | a); 23 | res = max(res, __builtin_popcount(dp[i] | a)); 24 | } 25 | } 26 | 27 | return res; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Medium Problems/3Sum.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/3sum/description/ 2 | 3 | class Solution { 4 | public: 5 | vector> threeSum(vector& nums) { 6 | int target = 0; 7 | sort(nums.begin(), nums.end()); 8 | set> s; 9 | vector> output; 10 | for (int i = 0; i < nums.size(); i++){ 11 | int j = i + 1; 12 | int k = nums.size() - 1; 13 | while (j < k) { 14 | int sum = nums[i] + nums[j] + nums[k]; 15 | if (sum == target) { 16 | s.insert({nums[i], nums[j], nums[k]}); 17 | j++; 18 | k--; 19 | } else if (sum < target) { 20 | j++; 21 | } else { 22 | k--; 23 | } 24 | } 25 | } 26 | for(auto triplets : s) 27 | output.push_back(triplets); 28 | return output; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Easy Problems/Island Perimeter.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/island-perimeter/description/?envType=daily-question&envId=2024-04-18 2 | 3 | class Solution { 4 | public: 5 | int islandPerimeter(vector>& grid) { 6 | 7 | int n = grid.size(); 8 | int m = grid[0].size(); 9 | int cnt = 0; 10 | for (int i = 0; i < n; i++) { 11 | for (int j = 0; j < m; j++) { 12 | if (grid[i][j] == 1) { 13 | if ((j > 0 && grid[i][j - 1] == 0) || j == 0) 14 | cnt++; 15 | 16 | if ((i > 0 && grid[i - 1][j] == 0) || i == 0) 17 | cnt++; 18 | 19 | if ((j < m - 1 && grid[i][j + 1] == 0) || j == m - 1) 20 | cnt++; 21 | 22 | if ((i < n - 1 && grid[i + 1][j] == 0) || i == n - 1) 23 | cnt++; 24 | } 25 | } 26 | } 27 | return cnt; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Easy Problems/056 Middle of the Linked List.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/middle-of-the-linked-list/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode() : val(0), next(nullptr) {} 9 | * ListNode(int x) : val(x), next(nullptr) {} 10 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | 16 | int length(ListNode* head){ 17 | int size=0; 18 | while(head != NULL){ 19 | size++; 20 | head = head->next; 21 | } 22 | 23 | return size; 24 | } 25 | 26 | ListNode* middleNode(ListNode* head) { 27 | int len = length(head); 28 | int ans = len/2; 29 | int cnt=0; 30 | while(cnt < ans){ 31 | head=head->next; 32 | cnt++; 33 | } 34 | 35 | return head; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /Medium Problems/Binary Tree Zigzag Level Order Traversal.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/ 2 | 3 | class Solution { 4 | public: 5 | vector> zigzagLevelOrder(TreeNode* root) { 6 | vector> ans; 7 | if (root==NULL)return ans; 8 | queue q; 9 | q.push(root); 10 | bool chk=0; 11 | while (!q.empty()){ 12 | int size= q.size(); 13 | vector temp; 14 | for (int i=0; ival); 18 | if (ele->left) q.push(ele->left); 19 | if (ele->right) q.push(ele->right); 20 | } 21 | 22 | if (chk){ 23 | reverse(temp.begin(),temp.end()); 24 | } 25 | ans.push_back(temp); 26 | chk= !chk; 27 | } 28 | return ans; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Hard Problems/Subarrays with K Different Integers.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/subarrays-with-k-different-integers/description/?envType=daily-question&envId=2024-03-30 2 | 3 | 4 | class Solution { 5 | public: 6 | 7 | int countSubarraysWithAtMostKDistinct(vector& nums, int k){ 8 | int n=nums.size(); 9 | 10 | unordered_map mp; 11 | 12 | int i=0, j=0; 13 | 14 | int c=0; 15 | 16 | while(jk){ 20 | if(--mp[nums[i]] == 0) mp.erase(nums[i]); 21 | i++; 22 | } 23 | 24 | c += (j-i+1); 25 | 26 | j++; 27 | } 28 | 29 | return c; 30 | } 31 | 32 | int subarraysWithKDistinct(vector& nums, int k) { 33 | return countSubarraysWithAtMostKDistinct(nums,k)-countSubarraysWithAtMostKDistinct(nums,k-1); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Medium Problems/Successful Pairs of Spells and Potions.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/successful-pairs-of-spells-and-potions/description/ 2 | 3 | class Solution { 4 | public: 5 | vector successfulPairs(vector& spells, vector& potions, long long success) { 6 | int n = spells.size(); 7 | int m = potions.size(); 8 | vector pairs(n, 0); 9 | sort(potions.begin(), potions.end()); 10 | for (int i = 0; i < n; i++) { 11 | int spell = spells[i]; 12 | int left = 0; 13 | int right = m - 1; 14 | while (left <= right) { 15 | int mid = left + (right - left) / 2; 16 | long long product = (long long)spell * (long long)potions[mid]; 17 | if (product >= success) { 18 | right = mid - 1; 19 | } else { 20 | left = mid + 1; 21 | } 22 | } 23 | pairs[i] = m - left; 24 | } 25 | return pairs; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Medium Problems/Find All Anagrams in a String.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/find-all-anagrams-in-a-string/description/ 2 | 3 | class Solution { 4 | public: 5 | bool checkEqual(vector &m1, vector &m2) { 6 | for(int i = 0; i < 26; i++) { 7 | if(m1[i] != m2[i]) return false; 8 | } 9 | return true; 10 | } 11 | vector findAnagrams(string s, string p) { 12 | vector m1(26, 0), m2(26, 0); 13 | for(int i = 0; i < p.length(); i++) { 14 | m2[p[i] - 'a']++; 15 | } 16 | int i = 0; 17 | int j = 0; 18 | vector ans; 19 | while(j < s.length()) { 20 | m1[s[j]-'a']++; 21 | if(j-i+1 < p.length()) { 22 | j++; 23 | } 24 | else if(j-i+1 == p.length()) { 25 | if(checkEqual(m1, m2)) ans.push_back(i); 26 | m1[s[i]-'a']--; 27 | i++; 28 | j++; 29 | } 30 | } 31 | return ans; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Medium Problems/Insert Delete GetRandom O(1).cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/insert-delete-getrandom-o1/description/ 2 | 3 | class RandomizedSet { 4 | vector v; 5 | unordered_map mp; 6 | public: 7 | 8 | RandomizedSet() { 9 | } 10 | 11 | bool search(int val){ 12 | 13 | if(mp.find(val)!=mp.end()) 14 | return true; 15 | return false; 16 | 17 | } 18 | 19 | 20 | bool insert(int val) { 21 | 22 | if(search(val)) 23 | return false; 24 | 25 | v.push_back(val); 26 | mp[val] = v.size()-1; 27 | return true; 28 | } 29 | 30 | 31 | bool remove(int val) { 32 | 33 | if(!search(val)) 34 | return false; 35 | 36 | 37 | auto it = mp.find(val); 38 | v[it->second] = v.back(); 39 | v.pop_back(); 40 | mp[v[it->second]] = it->second; 41 | mp.erase(val); 42 | return true; 43 | } 44 | 45 | 46 | int getRandom() { 47 | 48 | return v[rand()%v.size()]; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /Easy Problems/Assign Cookies.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/assign-cookies/description/ 2 | 3 | class Solution { 4 | public: 5 | int findContentChildren(std::vector& g, std::vector& s) { 6 | // Sort the arrays 7 | std::sort(g.begin(), g.end()); 8 | std::sort(s.begin(), s.end()); 9 | 10 | // Initialize count for tracking assignments of cookies 11 | int count = 0; 12 | // Initialize two pointers i and j to iterate on g and s 13 | int i = 0, j = 0; 14 | 15 | // Iterate through the arrays 16 | while (i < g.size() && j < s.size()) { 17 | // If the size of the cookie is greater than or equal to the child's greed, 18 | // assign the cookie to the child and move both pointers 19 | if (g[i] <= s[j]) { 20 | count++; 21 | i++; 22 | } 23 | // Move the cookie pointer to the next cookie, regardless of assignment 24 | j++; 25 | } 26 | 27 | return count; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Easy Problems/041 Verifying an Alien Dictionary.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/verifying-an-alien-dictionary/ 2 | 3 | class Solution { 4 | public: 5 | bool wordCompare(vector&mp, string& word1, string& word2) 6 | { 7 | int i = 0, j = 0; 8 | while(i < word1.size() && j < word2.size()) 9 | { 10 | int pos1 = mp[word1[i] - 'a']; 11 | int pos2 = mp[word2[j] - 'a']; 12 | if (pos1 < pos2) return true; 13 | else if (pos2 < pos1) return false; 14 | 15 | i++; 16 | j++; 17 | } 18 | 19 | return (word1.size() <= word2.size()); 20 | } 21 | bool isAlienSorted(vector& words, string order) 22 | { 23 | vectormp(26); 24 | for (int i = 0; i < order.size(); i++) mp[order[i] - 'a'] = i; 25 | 26 | for (int i = 0; i < words.size() - 1; i++) 27 | { 28 | if (!wordCompare(mp, words[i], words[i + 1])) 29 | return false; 30 | } 31 | return true; 32 | 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Medium Problems/Find Players With Zero or One Losses.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/find-players-with-zero-or-one-losses/description/ 2 | 3 | class Solution { 4 | public: 5 | vector> findWinners(vector>& matches) { 6 | unordered_maplost_map; 7 | for(int i=0;inotLost; 14 | vectoronceLost; 15 | 16 | for(int i=0;ileft== NULL && root->right==NULL){ 21 | tmp = tmp*10 + root->val; 22 | ans+=tmp; 23 | return; 24 | } 25 | tmp = tmp*10 + root->val; 26 | if(root->left) dfs(root->left,ans,tmp); 27 | if(root->right) dfs(root->right,ans,tmp); 28 | } 29 | 30 | int sumNumbers(TreeNode* root) { 31 | ll ans =0; 32 | dfs(root,ans,0); 33 | return int(ans); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Hard Problems/Arithmetic Slices II - Subsequence.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/arithmetic-slices-ii-subsequence/description/?envType=daily-question&envId=2024-01-07 2 | 3 | class Solution { 4 | public: 5 | int numberOfArithmeticSlices(std::vector& nums) { 6 | int n = nums.size(); 7 | int total_count = 0; 8 | 9 | std::vector> dp(n); 10 | 11 | for (int i = 1; i < n; ++i) { 12 | for (int j = 0; j < i; ++j) { 13 | long long diff = static_cast(nums[i]) - nums[j]; //type casting to long long 14 | 15 | if (diff > INT_MAX || diff < INT_MIN) 16 | continue; 17 | 18 | int diff_int = static_cast(diff); 19 | 20 | dp[i][diff_int] += 1; 21 | 22 | if (dp[j].count(diff_int)) { 23 | dp[i][diff_int] += dp[j][diff_int]; 24 | total_count += dp[j][diff_int]; 25 | } 26 | } 27 | } 28 | 29 | return total_count; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Easy Problems/037 Inorder Using Stack.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/binary-tree-inorder-traversal/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | vector inorderTraversal(TreeNode* root){ 17 | vector ans; 18 | stack s; 19 | if(root) s.push(root); 20 | 21 | while(!s.empty()){ 22 | TreeNode* temp = s.top(); 23 | if(temp->left){ 24 | s.push(temp->left); 25 | temp -> left = NULL; 26 | } 27 | 28 | else{ 29 | ans.push_back(temp->val); 30 | s.pop(); 31 | if(temp->right) s.push(temp->right); 32 | } 33 | } 34 | return ans; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Medium Problems/Simplify Path.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/simplify-path/description/ 2 | 3 | class Solution { 4 | public: 5 | string simplifyPath(string path) { 6 | 7 | stack st; 8 | string res; 9 | 10 | for(int i = 0; i q1; 6 | queue q2; 7 | 8 | MyStack() { 9 | 10 | } 11 | 12 | void push(int x) { 13 | while(!q1.empty()){ 14 | int temp = q1.front(); 15 | q1.pop(); 16 | q2.push(temp); 17 | } 18 | 19 | q1.push(x); 20 | 21 | while(!q2.empty()){ 22 | int temp = q2.front(); 23 | q2.pop(); 24 | q1.push(temp); 25 | } 26 | 27 | } 28 | 29 | int pop() { 30 | int ans = q1.front(); 31 | q1.pop(); 32 | return ans; 33 | } 34 | 35 | int top() { 36 | return q1.front(); 37 | } 38 | 39 | bool empty() { 40 | return q1.empty(); 41 | } 42 | }; 43 | 44 | /** 45 | * Your MyStack object will be instantiated and called as such: 46 | * MyStack* obj = new MyStack(); 47 | * obj->push(x); 48 | * int param_2 = obj->pop(); 49 | * int param_3 = obj->top(); 50 | * bool param_4 = obj->empty(); 51 | */ 52 | -------------------------------------------------------------------------------- /Hard Problems/Serialize and Deserialize Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/ 2 | 3 | class Codec { 4 | public: 5 | string serialize(TreeNode* root) { 6 | ostringstream temp; 7 | ToString(root, temp); 8 | return temp.str(); 9 | } 10 | 11 | TreeNode* deserialize(string data) { 12 | istringstream temp(data); 13 | return ToStructure(temp); 14 | } 15 | 16 | private: 17 | void ToString(TreeNode* root, ostringstream& temp) { 18 | if (root == NULL) { 19 | temp << "N "; 20 | return; 21 | } 22 | temp << root->val << " "; 23 | ToString(root->left, temp); 24 | ToString(root->right, temp); 25 | } 26 | 27 | TreeNode* ToStructure(istringstream& temp) { 28 | string value = ""; 29 | temp >> value; 30 | if (value == "N") { 31 | return NULL; 32 | } 33 | TreeNode* root = new TreeNode(stoi(value)); 34 | root->left = ToStructure(temp); 35 | root->right = ToStructure(temp); 36 | return root; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Hard Problems/Word Ladder.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/word-ladder/description/ 2 | 3 | class Solution { 4 | public: 5 | int ladderLength(string beginWord, string endWord, vector& wordList) { 6 | unordered_set dict(wordList.begin(), wordList.end()); 7 | queue todo; 8 | todo.push(beginWord); 9 | int ladder = 1; 10 | while (!todo.empty()) { 11 | int n = todo.size(); 12 | for (int i = 0; i < n; i++) { 13 | string word = todo.front(); 14 | todo.pop(); 15 | if (word == endWord) { 16 | return ladder; 17 | } 18 | dict.erase(word); 19 | for (int j = 0; j < word.size(); j++) { 20 | char c = word[j]; 21 | for (int k = 0; k < 26; k++) { 22 | word[j] = 'a' + k; 23 | if (dict.find(word) != dict.end()) { 24 | todo.push(word); 25 | } 26 | } 27 | word[j] = c; 28 | } 29 | } 30 | ladder++; 31 | } 32 | return 0; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Hard Problems/Maximal Rectangle.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/maximal-rectangle/description/ 2 | 3 | class Solution { 4 | public: 5 | int maximalRectangle(vector>& matrix) { 6 | if (matrix.empty() || matrix[0].empty()) 7 | return 0; 8 | 9 | int rows = matrix.size(); 10 | int cols = matrix[0].size(); 11 | vector heights(cols + 1, 0); // Include an extra element for easier calculation 12 | int maxArea = 0; 13 | 14 | for (const auto& row : matrix) { 15 | for (int i = 0; i < cols; i++) { 16 | heights[i] = (row[i] == '1') ? heights[i] + 1 : 0; 17 | } 18 | 19 | // Calculate max area using histogram method 20 | int n = heights.size(); // Number of bars in the histogram 21 | 22 | for (int i = 0; i < n; i++) { 23 | for (int j = i, minHeight = INT_MAX; j < n; j++) { 24 | minHeight = min(minHeight, heights[j]); 25 | int area = minHeight * (j - i + 1); 26 | maxArea = max(maxArea, area); 27 | } 28 | } 29 | } 30 | 31 | return maxArea; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Medium Problems/Smallest String Starting From Leaf.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/smallest-string-starting-from-leaf/description/?envType=daily-question&envId=2024-04-17 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 12 | * }; 13 | */ 14 | class Solution { 15 | public: 16 | string smallestFromLeaf(TreeNode* root) { 17 | string ans; 18 | dfs(root, "", ans); 19 | return ans; 20 | } 21 | 22 | void dfs(TreeNode* root, string path, string& ans) { 23 | if (!root) return; 24 | 25 | path += char('a' + root->val); 26 | 27 | if (!root->left && !root->right) { 28 | reverse(path.begin(), path.end()); 29 | if (ans.empty() || path < ans) { 30 | ans = path; 31 | } 32 | reverse(path.begin(), path.end()); 33 | } 34 | 35 | dfs(root->left, path, ans); 36 | dfs(root->right, path, ans); 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Medium Problems/Longest Palindromic Substring.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/longest-palindromic-substring/description/ 2 | 3 | class Solution { 4 | public: 5 | string longestPalindrome(string s) { 6 | 7 | string ans=""; 8 | int start=0; 9 | int end=0; 10 | int len=0; 11 | int n=s.size(); 12 | 13 | for(int i=1;i=0 && enlen) 21 | { 22 | len=en-st+1; 23 | start=st; 24 | end=en; 25 | } 26 | st--; 27 | en++; 28 | } 29 | 30 | // for even 31 | st=i-1; 32 | en=i; 33 | while(st>=0 && enlen) 36 | { 37 | len=en-st+1; 38 | start=st; 39 | end=en; 40 | } 41 | st--; 42 | en++; 43 | } 44 | } 45 | 46 | for(int i=start;i<=end;i++) 47 | { 48 | ans+=s[i]; 49 | } 50 | 51 | return ans; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /Medium Problems/Rotting Oranges.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/rotting-oranges/description/ 2 | 3 | class Solution { 4 | public: 5 | int orangesRotting(vector>& grid) 6 | { 7 | 8 | vector dir={-1,0,1,0,-1}; 9 | 10 | int m=grid.size(); 11 | int n=grid[0].size(); 12 | 13 | queue> q; 14 | int fresh=0; 15 | for(int i=0;i p=q.front(); 30 | q.pop(); 31 | for(int i=0;i<4;i++) 32 | { 33 | int r=p.first+dir[i]; 34 | int c=p.second+dir[i+1]; 35 | if(r>=0 && r=0 && c0) return -1; 47 | if(ans==-1) return 0; 48 | return ans; 49 | 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Medium Problems/Evaluate Reverse Polish Notation.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/evaluate-reverse-polish-notation/description/ 2 | 3 | class Solution { 4 | public: 5 | int evalRPN(vector& tokens) { 6 | stack st; 7 | int n = tokens.size(); 8 | int ans = 0; 9 | int temp = 0; 10 | 11 | if (n == 1) return stoi(tokens[0]); 12 | else { 13 | for (int i = 0; i < n; i++) { 14 | if (tokens[i] == "+") { 15 | temp = st.top(); 16 | st.pop(); 17 | ans = st.top() + temp; 18 | st.pop(); 19 | st.push(ans); 20 | } else if (tokens[i] == "*") { 21 | temp = st.top(); 22 | st.pop(); 23 | ans = st.top() * temp; 24 | st.pop(); 25 | st.push(ans); 26 | } else if (tokens[i] == "-") { 27 | temp = st.top(); 28 | st.pop(); 29 | ans = st.top() - temp; 30 | st.pop(); 31 | st.push(ans); 32 | } else if (tokens[i] == "/") { 33 | temp = st.top(); 34 | st.pop(); 35 | ans = st.top() / temp; 36 | st.pop(); 37 | st.push(ans); 38 | } else { 39 | st.push(stoi(tokens[i])); 40 | } 41 | } 42 | return ans; 43 | } 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /Medium Problems/Accounts Merge.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/accounts-merge/description/ 2 | 3 | 4 | class Solution { 5 | public: 6 | vector parent; 7 | int find_set(int x){ 8 | if(parent[x] == x) return x; 9 | return parent[x] = find_set(parent[x]); 10 | } 11 | 12 | void make_union(int x, int y){ 13 | int a = find_set(x); 14 | int b = find_set(y); 15 | if(a != b){ 16 | parent[a] = b; 17 | } 18 | } 19 | 20 | vector> accountsMerge(vector>& accounts) { 21 | int n = accounts.size(); 22 | parent.resize(n); 23 | unordered_map emailtoId; 24 | for(int i = 0; i> newaccounts; 36 | for(auto it : emailtoId){ 37 | newaccounts[find_set(it.second)].push_back(it.first); 38 | } 39 | vector> ans; 40 | for(auto &it : newaccounts){ 41 | auto &emails = it.second; 42 | sort(emails.begin(), emails.end()); 43 | emails.insert(emails.begin(), accounts[it.first][0]); 44 | ans.push_back(emails); 45 | } 46 | return ans; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Medium Problems/Number of Islands.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/number-of-islands/description/ 2 | 3 | class Solution { 4 | private: 5 | void bfs(int row, int col, vector>& vis, vector>& grid) { 6 | vis[row][col] = true; 7 | queue> q; 8 | q.push({row, col}); 9 | int n = grid.size(); 10 | int m = grid[0].size(); 11 | vector> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; 12 | 13 | while (!q.empty()) { 14 | int r = q.front().first; 15 | int c = q.front().second; 16 | q.pop(); 17 | 18 | for (auto dir : directions) { 19 | int nRow = dir.first + r; 20 | int nCol = dir.second + c; 21 | if (nRow >= 0 && nRow < n && nCol >= 0 && nCol < m && !vis[nRow][nCol] && grid[nRow][nCol] == '1') { 22 | vis[nRow][nCol] = true; 23 | q.push({nRow, nCol}); 24 | } 25 | } 26 | } 27 | } 28 | 29 | public: 30 | int numIslands(vector>& grid) { 31 | int n = grid.size(); 32 | if (n == 0) return 0; 33 | int m = grid[0].size(); 34 | vector> vis(n, vector(m, false)); 35 | int count = 0; 36 | 37 | for (int i = 0; i < n; i++) { 38 | for (int j = 0; j < m; j++) { 39 | if (!vis[i][j] && grid[i][j] == '1') { 40 | count++; 41 | bfs(i, j, vis, grid); 42 | } 43 | } 44 | } 45 | return count; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /Easy Problems/002 Valid Parenthesis.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/valid-parentheses/ 2 | 3 | class Solution { 4 | public: 5 | bool isValid(string s) { 6 | stackst; 7 | if (s.length() < 2) 8 | return false; 9 | for (int i = 0; i < s.length(); i++) { 10 | char c = s.at(i); 11 | if (c == '{' || c == '(' || c == '[') { 12 | st.push(c); 13 | } else { 14 | if (st.empty()) 15 | return false; 16 | if (c == '}' && st.top() == '{') 17 | st.pop(); 18 | else if (c == ')' && st.top() == '(') 19 | st.pop(); 20 | else if (c == ']' && st.top() == '[') 21 | st.pop(); 22 | else 23 | return false; 24 | } 25 | } 26 | return st.empty(); 27 | } 28 | }; 29 | 30 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- 31 | 32 | class Solution { 33 | public: 34 | bool isValid(string s) { 35 | stack st; 36 | for(auto i:s) { //iterate every element of s 37 | 38 | if(i=='(' or i=='{' or i=='[') 39 | st.push(i); 40 | 41 | else { 42 | if(st.empty() or (st.top()=='(' and i!=')') or (st.top()=='{' and i!='}') or (st.top()=='[' and i!=']')) return false; 43 | st.pop(); 44 | } 45 | } 46 | return st.empty(); 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /Medium Problems/Valid Sudoku.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/valid-sudoku/description/ 2 | 3 | class Solution { 4 | #define DPSolver ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0); 5 | public: 6 | bool checkSubThree (vector>& board, int row, int col){ 7 | vector vis(10); 8 | for(int i = row; i < row + 3; i ++){ 9 | for(int j = col; j < col + 3; j++){ 10 | if(board[i][j]!='.'){ 11 | if(!vis[board[i][j] - '1']) 12 | vis[board[i][j] - '1'] = true; 13 | else 14 | return false; 15 | } 16 | } 17 | } 18 | return true; 19 | } 20 | 21 | bool isValidSudoku(vector>& board) { 22 | DPSolver; 23 | int n = 9; 24 | for (int i = 0; i < n; i++) 25 | { 26 | vector row(9, false); 27 | vector col(9, false); 28 | 29 | for (int j = 0; j < 9; j++) 30 | { 31 | if (board[i][j] != '.') 32 | { 33 | if (row[board[i][j] - '1']) 34 | return false; 35 | 36 | else 37 | row[board[i][j] - '1'] = true; 38 | } 39 | if (board[j][i] != '.') 40 | { 41 | if (col[board[j][i] - '1']) 42 | return false; 43 | 44 | else 45 | col[board[j][i] - '1'] = true; 46 | } 47 | } 48 | } 49 | for(int i = 0 ; i < 9; i+=3) 50 | for(int j = 0; j < 9; j+=3) 51 | if(!checkSubThree(board, i,j)) 52 | return false; 53 | 54 | return true; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /Hard Problems/002 Largest Rectangle in Histogram.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/largest-rectangle-in-histogram/ 2 | 3 | class Solution { 4 | private: 5 | vector nextSmallerElement(vector arr, int n) { 6 | stack s; 7 | s.push(-1); 8 | vector ans(n); 9 | 10 | for(int i=n-1; i>=0 ; i--) { 11 | int curr = arr[i]; 12 | while(s.top() != -1 && arr[s.top()] >= curr) 13 | { 14 | s.pop(); 15 | } 16 | ans[i] = s.top(); 17 | s.push(i); 18 | } 19 | return ans; 20 | } 21 | 22 | vector prevSmallerElement(vector arr, int n) { 23 | stack s; 24 | s.push(-1); 25 | vector ans(n); 26 | 27 | for(int i=0; i= curr) 30 | { 31 | s.pop(); 32 | } 33 | 34 | ans[i] = s.top(); 35 | s.push(i); 36 | } 37 | return ans; 38 | } 39 | 40 | public: 41 | int largestRectangleArea(vector& heights) { 42 | int n= heights.size(); 43 | 44 | vector next(n); 45 | next = nextSmallerElement(heights, n); 46 | 47 | vector prev(n); 48 | prev = prevSmallerElement(heights, n); 49 | 50 | int area = INT_MIN; 51 | for(int i=0; i; 7 | vector jobs; // (startTime, endTime, profit) 8 | vector dp; 9 | int n; 10 | vector next; 11 | 12 | void binary_search() { 13 | for (int i = 0; i < n; i++) { 14 | // Be careful 15 | next[i] = upper_bound(jobs.begin()+i, jobs.end(), 16 | array{jobs[i][1], 0, 0}) - jobs.begin(); 17 | // cout << i << "->" << next[i] << endl; 18 | } 19 | } 20 | 21 | int dfs(int i) { 22 | if (i == n ) return 0; 23 | if (dp[i]!= -1) return dp[i]; 24 | 25 | // take the job i 26 | int profit_w_i = jobs[i][2] + dfs(next[i]); 27 | 28 | // Skip the job i 29 | int profit_n_i = dfs(i+1); 30 | 31 | // Choose the maximum of profit_w_i & profit_n_i 32 | return dp[i] = max(profit_w_i, profit_n_i); 33 | } 34 | 35 | int jobScheduling(vector& startTime, vector& endTime, vector& profit) 36 | { 37 | n = startTime.size(); 38 | jobs.assign(n, {-1, -1, -1}); 39 | for (int i = 0; i < n; i++) 40 | jobs[i] = {startTime[i], endTime[i], profit[i]}; 41 | 42 | sort(jobs.begin(), jobs.end()); 43 | // Initialize the 'next' vector with the correct size 44 | next.assign(n, -1); 45 | 46 | dp.assign(n+1, -1); 47 | binary_search(); 48 | return dfs(0); 49 | } 50 | }; 51 | 52 | auto init = []() 53 | { 54 | ios::sync_with_stdio(0); 55 | cin.tie(0); 56 | cout.tie(0); 57 | return 'c'; 58 | }(); 59 | -------------------------------------------------------------------------------- /Medium Problems/Spiral Matrix.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/search-in-rotated-sorted-array/description/ 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | class Solution { 7 | public: 8 | vector spiralOrder(vector >& matrix) { 9 | 10 | 11 | vector ans; 12 | int row = matrix.size(); 13 | int col = matrix[0].size(); 14 | 15 | int count = 0; 16 | int total = row*col; 17 | 18 | //index initialisation 19 | int startingRow = 0; 20 | int startingCol = 0; 21 | int endingRow = row-1; 22 | int endingCol = col-1; 23 | 24 | 25 | while(count < total) { 26 | 27 | //print starting row 28 | for(int index = startingCol; count < total && index<=endingCol; index++) { 29 | ans.push_back(matrix[startingRow][index]); 30 | count++; 31 | } 32 | startingRow++; 33 | 34 | //print ending column 35 | for(int index = startingRow; count < total && index<=endingRow; index++) { 36 | ans.push_back(matrix[index][endingCol]); 37 | count++; 38 | } 39 | endingCol--; 40 | 41 | //print ending row 42 | for(int index = endingCol; count < total && index>=startingCol; index--) { 43 | ans.push_back(matrix[endingRow][index]); 44 | count++; 45 | } 46 | endingRow--; 47 | 48 | //print starting column 49 | for(int index = endingRow; count < total && index>=startingRow; index--) { 50 | ans.push_back(matrix[index][startingCol]); 51 | count++; 52 | } 53 | startingCol++; 54 | } 55 | return ans; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /Medium Problems/Amount of Time for Binary Tree to Be Infected.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/description/ 2 | 3 | 4 | 5 | class Solution { 6 | public: 7 | int amountOfTime(TreeNode* root, int start) { 8 | unordered_map> map; 9 | convert(root, 0, map); 10 | queue q; 11 | q.push(start); 12 | int minute = 0; 13 | unordered_set visited; 14 | visited.insert(start); 15 | 16 | while (!q.empty()) { 17 | int levelSize = q.size(); 18 | while (levelSize > 0) { 19 | int current = q.front(); 20 | q.pop(); 21 | 22 | for (int num : map[current]) { 23 | if (visited.find(num) == visited.end()) { 24 | visited.insert(num); 25 | q.push(num); 26 | } 27 | } 28 | levelSize--; 29 | } 30 | minute++; 31 | } 32 | return minute - 1; 33 | } 34 | 35 | void convert(TreeNode* current, int parent, unordered_map>& map) { 36 | if (current == nullptr) { 37 | return; 38 | } 39 | if (map.find(current->val) == map.end()) { 40 | map[current->val] = unordered_set(); 41 | } 42 | unordered_set& adjacentList = map[current->val]; 43 | if (parent != 0) { 44 | adjacentList.insert(parent); 45 | } 46 | if (current->left != nullptr) { 47 | adjacentList.insert(current->left->val); 48 | } 49 | if (current->right != nullptr) { 50 | adjacentList.insert(current->right->val); 51 | } 52 | convert(current->left, current->val, map); 53 | convert(current->right, current->val, map); 54 | } 55 | }; 56 | 57 | 58 | -------------------------------------------------------------------------------- /Hard Problems/004 Count of Smaller Numbers After Self.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/count-of-smaller-numbers-after-self/description/ 2 | 3 | class Solution { 4 | public: 5 | void merge(vector &count, vector > &v, int left, int mid, int right) { 6 | vector > tmp(right-left+1); 7 | int i = left; 8 | int j = mid+1; 9 | int k = 0; 10 | 11 | while (i <= mid && j <= right) { 12 | // mind that we're sorting in descending order 13 | if (v[i].first <= v[j].first) { 14 | tmp[k++] = v[j++]; 15 | } 16 | else { 17 | // only line responsible to update count, related to problem constraint, 18 | // remaining part is just regular mergeSort 19 | count[v[i].second] += right - j + 1; 20 | tmp[k++] = v[i++]; 21 | } 22 | } 23 | while (i <= mid) { 24 | tmp[k++] = v[i++]; 25 | } 26 | while (j <= right) { 27 | tmp[k++] = v[j++]; 28 | } 29 | for (int i = left; i <= right; i++) 30 | v[i] = tmp[i-left]; 31 | } 32 | 33 | void mergeSort(vector &count, vector > &v, int left, int right) { 34 | if (left >= right) 35 | return; 36 | 37 | int mid = left + (right-left)/2; 38 | mergeSort(count, v, left, mid); 39 | mergeSort(count, v, mid+1, right); 40 | merge(count, v, left, mid, right); 41 | } 42 | 43 | vector countSmaller(vector& nums) { 44 | int N = nums.size(); 45 | 46 | vector > v(N); 47 | for (int i = 0; i < N; i++) 48 | v[i] = make_pair(nums[i], i); 49 | 50 | vector count(N, 0); 51 | // sorting in descending order 52 | mergeSort(count, v, 0, N-1); 53 | 54 | return count; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /Medium Problems/Number of Enclaves.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/number-of-enclaves/ 2 | 3 | class Solution { 4 | public: 5 | 6 | int dfs(int i,int j,vector>&grid,int n,int m,int&f){ 7 | 8 | if(i ==0 || j == 0 || i == n-1 || j== m-1){ 9 | f=1; 10 | //we can reach to the bounday so we will mark it 11 | //and will not add no of nodes to our answer 12 | } 13 | 14 | //changing current cell to 0, so that I don't visit again 15 | grid[i][j] = 0; 16 | int c = 0; 17 | //we can move in four directions 18 | //going UP 19 | if((i-1)>=0){ 20 | if(grid[i-1][j] == 1){ 21 | //go there 22 | //we make it water 23 | grid[i-1][j] = 0; 24 | c += dfs(i-1,j,grid,n,m,f); 25 | } 26 | } 27 | 28 | //going DOWN 29 | if((i+1)=0){ 40 | if(grid[i][j-1] == 1){ 41 | //go there 42 | //we make it water 43 | grid[i][j-1] = 0; 44 | c += dfs(i,j-1,grid,n,m,f); 45 | } 46 | } 47 | 48 | //going RIGHT 49 | if((j+1)>& grid) { 63 | int ans = 0; 64 | 65 | int n = grid.size(); 66 | int m = grid[0].size(); 67 | 68 | for(int i=0;i