├── 01 Matrix.cpp ├── Add Binary.cpp ├── Add Digits.cpp ├── Add One Row to Tree.cpp ├── Add Two Numbers II.cpp ├── Add to Array-Form of Integer.cpp ├── All Nodes Distance K in Binary Tree.cpp ├── All Paths From Source to Target.CPP ├── All Possible Full Binary Trees.cpp ├── Arithmetic Slices II - Subsequence.cpp ├── As Far from Land as Possible.cpp ├── Asteroid Collision.cpp ├── Average Salary Excluding the Minimum and Maximum Salary.cpp ├── Average of Levels in Binary Tree.cpp ├── Backspace String Compare.cpp ├── Bag of Tokens.cpp ├── Basic Calculator.cpp ├── Best Team With No Conflicts.cpp ├── Best Time to Buy and Sell Stock with Cooldown.cpp ├── Best Time to Buy and Sell Stock.cpp ├── Binary Search.cpp ├── Binary Tree Inorder Traversal.cpp ├── Binary Tree Maximum Path Sum.cpp ├── Binary Tree Preorder Traversal.cpp ├── Binary Tree Pruning.cpp ├── Binary Tree Zigzag Level Order Traversal.cpp ├── Binary Trees With Factors.cpp ├── Boats to Save People.cpp ├── Break a Palindrome.cpp ├── Buddy Strings.cpp ├── Bulb Switcher.cpp ├── Can Make Arithmetic Progression From Sequence.cpp ├── Can Place Flowers.cpp ├── Candy.cpp ├── Capacity To Ship Packages Within D Days.cpp ├── Champagne Tower.cpp ├── Cheapest Flights Within K Stops.cpp ├── Check Completeness of a Binary Tree.cpp ├── Check If It Is a Straight Line.cpp ├── Check if the Sentence Is Pangram.cpp ├── Checking Existence of Edge Length Limited Paths.cpp ├── Climbing Stairs.cpp ├── Clone Graph.cpp ├── Coin Change II.cpp ├── Combination Sum IV.cpp ├── Concatenated Words.cpp ├── Concatenation of Consecutive Binary Numbers.cpp ├── Construct Binary Tree from Inorder and Postorder Traversal.cpp ├── Construct Quad Tree.cpp ├── Construct String from Binary Tree.cpp ├── Convert Sorted Array to Binary Search Tree.cpp ├── Convert Sorted List to Binary Search Tree.cpp ├── Copy List with Random Pointer.cpp ├── Count Good Nodes in Binary Tree.cpp ├── Count Negative Numbers in a Sorted Matrix.cpp ├── Count Odd Numbers in an Interval Range.cpp ├── Count Subarrays With Fixed Bounds.cpp ├── Count Unreachable Pairs of Nodes in an Undirected Graph.cpp ├── Count Vowels Permutation.cpp ├── Count Ways To Build Good Strings.cpp ├── Counting Bits.cpp ├── Counting elements in two arrays.cpp ├── Course Schedule.cpp ├── Daily Temperatures.cpp ├── Data Stream as Disjoint Intervals.cpp ├── Decode Ways.cpp ├── Delete Columns to Make Sorted.cpp ├── Delete Node in a Linked List.cpp ├── Delete the Middle Node of a Linked List.cpp ├── Design Add and Search Words Data Structure.cpp ├── Design Browser History.cpp ├── Design Circular Queue.cpp ├── Design HashMap.cpp ├── Design HashSet.cpp ├── Design Parking System.cpp ├── Design Underground System.cpp ├── Detect Capital.cpp ├── Determine if Two Strings Are Close.cpp ├── Detonate the Maximum Bombs.cpp ├── Distance from the Source (Bellman-Ford Algorithm).cpp ├── Domino and Tromino Tiling.cpp ├── Dota2 Senate.cpp ├── Earliest Possible Day of Full Bloom.cpp ├── Edit Distance.cpp ├── Erect the Fence.cpp ├── Evaluate Division.cpp ├── Evaluate Reverse Polish Notation.cpp ├── Extra Characters in a String.cpp ├── Fair Distribution of Cookies.cpp ├── Find All Anagrams in a String.cpp ├── Find Closest Node to Given Two Nodes.cpp ├── Find Duplicate File in System.cpp ├── Find Duplicate Subtrees.cpp ├── Find Eventual Safe States.cpp ├── Find K Closest Elements.cpp ├── Find Largest Value in Each Tree Row.cpp ├── Find Median from Data Stream.cpp ├── Find Mode in Binary Search Tree.cpp ├── Find Original Array From Doubled Array.cpp ├── Find Players With Zero or One Losses.cpp ├── Find and Replace Pattern.cpp ├── Find if Path Exists in Graph.cpp ├── Find in Mountain Array.cpp ├── Find the Difference of Two Arrays.cpp ├── Find the Difference.cpp ├── Find the Index of the First Occurrence in a String.cpp ├── Find the Longest Valid Obstacle Course at Each Position.cpp ├── Find the Town Judge.cpp ├── First Unique Character in a String.cpp ├── Flatten Binary Tree to Linked List.cpp ├── Flatten Nested List Iterator.cpp ├── Flip String to Monotone Increasing.cpp ├── Fruit Into Baskets.cpp ├── Gas Station.cpp ├── Greatest Common Divisor of Strings.cpp ├── Group Anagrams.cpp ├── Group the People Given the Group Size They Belong To.cpp ├── House Robber.cpp ├── IPO.cpp ├── Image Overlap.cpp ├── Implement Queue using Stacks.cpp ├── Implement Trie (Prefix Tree).cpp ├── Increasing Triplet Subsequence.cpp ├── Insert Delete GetRandom O(1).cpp ├── Insert Interval.cpp ├── Invert Binary Tree.cpp ├── Is Graph Bipartite.cpp ├── Is Subsequence.cpp ├── Jump Game II.cpp ├── Jump Game IV.cpp ├── Jump Game.cpp ├── Keys and Rooms.cpp ├── Kids With the Greatest Number of Candies.cpp ├── Knight Dialer.cpp ├── Knight Probability in Chessboard.cpp ├── Koko Eating Bananas.cpp ├── Kth Largest Element in a Stream.cpp ├── Kth Largest Element in an Array.cpp ├── Kth Missing Positive Number.cpp ├── Kth Smallest Element in a Sorted Matrix.cpp ├── LFU Cache.cpp ├── LRU Cache.cpp ├── Largest Color Value in a Directed Graph.cpp ├── Largest Perimeter Triangle.cpp ├── Last Day Where You Can Still Cross.cpp ├── Last Stone Weight.cpp ├── Leaf-Similar Trees.cpp ├── Linked List Cycle II.cpp ├── Linked List Random Node.cpp ├── Longest Arithmetic Subsequence of Given Difference.cpp ├── Longest Common Subsequence.cpp ├── Longest Cycle in a Graph.cpp ├── Longest Palindrome by Concatenating Two Letter Words.cpp ├── Longest Palindromic Subsequence.cpp ├── Longest Path With Different Adjacent Characters.cpp ├── Longest Perfect Piece.cpp ├── Longest String Chain.cpp ├── Longest Subarray of 1's After Deleting One Element.cpp ├── Longest Subsequence With Limited Sum.cpp ├── Lowest Common Ancestor of a Binary Search Tree.cpp ├── Lowest Common Ancestor of a Binary Tree.cpp ├── Majority Element II.cpp ├── Make The String Great.cpp ├── Matrix Diagonal Sum.cpp ├── Max Points on a Line.cpp ├── Max Sum of Rectangle No Larger Than K.cpp ├── Maximal Network Rank.cpp ├── Maximize the Confusion of an Exam.cpp ├── Maximum 69 Number.cpp ├── Maximum Bags With Full Capacity of Rocks.cpp ├── Maximum Depth of Binary Tree.cpp ├── Maximum Difference Between Node and Ancestor.cpp ├── Maximum Ice Cream Bars.cpp ├── Maximum Number of Achievable Transfer Requests.cpp ├── Maximum Number of Coins You Can Get.cpp ├── Maximum Number of Vowels in a Substring of Given Length.cpp ├── Maximum Performance of a Team.cpp ├── Maximum Profit in Job Scheduling.cpp ├── Maximum Running Time of N Computers.cpp ├── Maximum Score from Performing Multiplication Operations.cpp ├── Maximum Score of a Good Subarray.cpp ├── Maximum Subsequence Score.cpp ├── Maximum Sum Circular Subarray.cpp ├── Maximum Twin Sum of a Linked List.cpp ├── Maximum Value of K Coins From Piles.cpp ├── Maximum Width of Binary Tree.cpp ├── Median of Two Sorted Arrays.cpp ├── Merge Strings Alternately.cpp ├── Merge k Sorted Lists.cpp ├── Min Cost to Connect All Points.cpp ├── Minimize Deviation in Array.cpp ├── Minimize Maximum of Array.cpp ├── Minimize the Maximum Difference of Pairs.cpp ├── Minimum ASCII Delete Sum for Two Strings.cpp ├── Minimum Average Difference.cpp ├── Minimum Cost For Tickets.cpp ├── Minimum Deletions to Make Character Frequencies Unique.cpp ├── Minimum Depth of Binary Tree.cpp ├── Minimum Difficulty of a Job Schedule.cpp ├── Minimum Distance Between BST Nodes.cpp ├── Minimum Falling Path Sum.cpp ├── Minimum Flips to Make a OR b Equal to c.cpp ├── Minimum Fuel Cost to Report to the Capital.cpp ├── Minimum Genetic Mutation.cpp ├── Minimum Insertion Steps to Make a String Palindrome.cpp ├── Minimum Number of Arrows to Burst Balloons.cpp ├── Minimum Number of Operations to Make Array Continuous.cpp ├── Minimum Number of Refueling Stops.cpp ├── Minimum Operations to Reduce X to Zero.cpp ├── Minimum Path Sum.cpp ├── Minimum Penalty for a Shop.cpp ├── Minimum Rounds to Complete All Tasks.cpp ├── Minimum Score of a Path Between Two Cities.cpp ├── Minimum Size Subarray Sum.cpp ├── Minimum Speed to Arrive on Time.cpp ├── Minimum Time to Collect All Apples in a Tree.cpp ├── Minimum Time to Complete Trips.cpp ├── Mirror Reflection.cpp ├── Monotonic Array.cpp ├── Most Stones Removed with Same Row or Column.cpp ├── My Calendar III.cpp ├── My Calendar.cpp ├── N-ary Tree Level Order Traversal.cpp ├── N-th Tribonacci Number.cpp ├── Naming a Company.cpp ├── Nearest Exit from Entrance in Maze.cpp ├── New 21 Game.cpp ├── Non-decreasing Subsequences.cpp ├── Non-overlapping Intervals.cpp ├── Number of 1 Bits.cpp ├── Number of Closed Islands.cpp ├── Number of Dice Rolls With Target Sum.cpp ├── Number of Enclaves.cpp ├── Number of Good Pairs.cpp ├── Number of Good Paths.cpp ├── Number of Islands.cpp ├── Number of Longest Increasing Subsequence.cpp ├── Number of Nodes in the Sub-Tree With the Same Label.cpp ├── Number of Provinces.cpp ├── Number of Subsequences That Satisfy the Given Sum Condition.cpp ├── Number of Ways of Cutting a Pizza.cpp ├── Number of Ways to Divide a Long Corridor.cpp ├── Number of Zero-Filled Subarrays.cpp ├── Numbers With Same Consecutive Differences.cpp ├── Odd Even Linked List.cpp ├── Online Stock Span.cpp ├── Optimal Partition of String.cpp ├── Orderly Queue.cpp ├── Pacific Atlantic Water Flow.cpp ├── Palindrome Linked List.cpp ├── Palindrome Pairs.cpp ├── Palindrome Partitioning.cpp ├── Partition List.cpp ├── Pascal's Triangle.cpp ├── Path Sum II.cpp ├── Path Sum.cpp ├── Path With Minimum Effort.cpp ├── Peak Index in a Mountain Array.cpp ├── Perfect Squares.cpp ├── Permutation in String.cpp ├── Poor Pigs.cpp ├── Possible Bipartition.cpp ├── Pow(x, n).cpp ├── Power of Four.cpp ├── Power of Three.cpp ├── Predict the Winner.cpp ├── Profitable Schemes.cpp ├── Pseudo-Palindromic Paths in a Binary Tree.cpp ├── Push Dominoes.cpp ├── Put Marbles in Bags.cpp ├── README.md ├── Range Sum of BST.cpp ├── Ransom Note.cpp ├── Ransom Notes.cpp ├── Rectangle Area.cpp ├── Reduce Array Size to The Half.cpp ├── Reducing Dishes.cpp ├── Remove All Adjacent Duplicates In String.cpp ├── Remove Colored Pieces if Both Neighbors are the Same Color.cpp ├── Remove Duplicate Letters.cpp ├── Remove Duplicates from Sorted Array.cpp ├── Remove Max Number of Edges to Keep Graph Fully Traversable.cpp ├── Remove Nth Node From End of List.cpp ├── Remove Stones to Minimize the Total.cpp ├── Removing Stars From a String.cpp ├── Reorder Routes to Make All Paths Lead to the City Zero.cpp ├── Reordered Power of 2.cpp ├── Repeated Substring Pattern.cpp ├── Restore IP Addresses.cpp ├── Restore The Array.cpp ├── Reverse Linked List II.cpp ├── Reverse Vowels of a String.cpp ├── Reverse Words in a String III.cpp ├── Reverse Words in a String.cpp ├── Roman to Integer.cpp ├── Rotate Image.cpp ├── Same Tree.cpp ├── Satisfiability of Equality Equations.cpp ├── Scramble String.cpp ├── Search Insert Position.cpp ├── Search a 2D Matrix.cpp ├── Search in Rotated Sorted Array II.cpp ├── Search in Rotated Sorted Array.cpp ├── Shortest Bridge.cpp ├── Shortest Path in Binary Matrix.cpp ├── Shortest Path in a Grid with Obstacles Elimination.cpp ├── Shortest Path to Get All Keys.cpp ├── Shortest Path with Alternating Colors.cpp ├── Shuffle the Array.cpp ├── Sign of the Product of an Array.cpp ├── Similar String Groups.cpp ├── Simplify Path.cpp ├── Single Element in a Sorted Array.cpp ├── Single Number II.cpp ├── Single-Threaded CPU.cpp ├── Sliding Window Maximum.cpp ├── Smallest Number in Infinite Set.cpp ├── Snakes and Ladders.cpp ├── Solving Questions With Brainpower.cpp ├── Sort Array By Parity.cpp ├── Sort Characters By Frequency.cpp ├── Sort an Array.cpp ├── Sort the Matrix Diagonally.cpp ├── Soup Servings.cpp ├── Spiral Matrix II.cpp ├── Spiral Matrix.cpp ├── Split Array into Consecutive Subsequences.cpp ├── Split Linked List in Parts.cpp ├── Stamping The Sequence.cpp ├── Stone Game II.cpp ├── Stone Game III.cpp ├── Strange Printer.cpp ├── String Compression II.cpp ├── String Compression.cpp ├── Subarray Sums Divisible by K.cpp ├── Substring with Concatenation of All Words.cpp ├── Successful Pairs of Spells and Potions.cpp ├── Sum Root to Leaf Numbers.cpp ├── Sum of Distances in Tree.cpp ├── Sum of Even Numbers After Queries.cpp ├── Sum of Subarray Minimums.cpp ├── Swap Nodes in Pairs.cpp ├── Swapping Nodes in a Linked List.cpp ├── Symmetric Tree.cpp ├── The K Weakest Rows in a Matrix.cpp ├── The Number of Weak Characters in the Game.cpp ├── The Skyline Problem.cpp ├── Time Based Key-Value Store.cpp ├── Time Needed to Inform All Employees.cpp ├── Toeplitz Matrix.cpp ├── Trapping Rain Water.cpp ├── Two Sum IV - Input is a BST.cpp ├── UTF-8 Validation.cpp ├── Ugly Number.cpp ├── Uncrossed Lines.cpp ├── Unique Morse Code Words.cpp ├── Unique Number of Occurrences.cpp ├── Unique Paths II.cpp ├── Unique Paths III.cpp ├── Unique Paths.cpp ├── Valid Anagram.cpp ├── Valid Parentheses.cpp ├── Valid Sudoku.cpp ├── Validate Binary Search Tree.cpp ├── Validate Binary Tree Nodes.cpp ├── Validate Stack Sequences.cpp ├── Verifying an Alien Dictionary.cpp ├── Vertical Order Traversal of a Binary Tree.cpp ├── Where Will the Ball Fall.cpp ├── Word Ladder.cpp ├── Word Pattern.cpp ├── Word Search II.cpp ├── Word Search.cpp ├── Word Subsets.cpp └── Zigzag Conversion.cpp /Add Binary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string addBinary(string a, string b) { 4 | string result; 5 | int carry = 0; 6 | int i = a.length() - 1; 7 | int j = b.length() - 1; 8 | while (i >= 0 || j >= 0) { 9 | int a_bit = i >= 0 ? a[i--] - '0' : 0; 10 | int b_bit = j >= 0 ? b[j--] - '0' : 0; 11 | int sum = a_bit + b_bit + carry; 12 | result.insert(result.begin(), sum % 2 + '0'); 13 | carry = sum / 2; 14 | } 15 | if (carry) { 16 | result.insert(result.begin(), '1'); 17 | } 18 | return result; 19 | } 20 | }; -------------------------------------------------------------------------------- /Add Digits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Add Digits " Problem ==>> https://leetcode.com/problems/add-digits/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/mlfJ7YpaPJM 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int addDigits(int num) { 11 | while(num>9){ 12 | int ans=0; 13 | while(num){ 14 | ans=ans+(num%10); 15 | num/=10; 16 | } 17 | num=ans; 18 | } 19 | return num; 20 | } 21 | }; -------------------------------------------------------------------------------- /Add to Array-Form of Integer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Add to Array-Form of Integer" Problem ==>> https://leetcode.com/problems/add-to-array-form-of-integer/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/KbclXMG8ka4 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector addToArrayForm(vector& nums, int k) { 11 | for(int i = nums.size() - 1; i >= 0; i--) { 12 | nums[i] += k; 13 | k = nums[i] / 10; 14 | nums[i] = nums[i] % 10; 15 | } 16 | while(k > 0) { 17 | nums.insert(nums.begin(), k % 10); 18 | k /= 10; 19 | } 20 | return nums; 21 | } 22 | }; -------------------------------------------------------------------------------- /All Paths From Source to Target.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> allPathsSourceTarget(vector>& G) { 4 | 5 | vector> ans; 6 | queue> q; 7 | q.push({0}); 8 | while(!q.empty()) { 9 | vector path =q.front(); 10 | q.pop(); 11 | if(path.back() == size(G)-1) 12 | ans.push_back(path); 13 | else 14 | for(int child : G[path.back()]){ 15 | path.push_back(child); 16 | q.push(path); 17 | path.pop_back(); 18 | } 19 | } 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /All Possible Full Binary Trees.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " All Possible Full Binary Trees " Problem ==>> https://leetcode.com/problems/all-possible-full-binary-trees/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/2OYxhqhhA2k 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector allPossibleFBT(int n) { 11 | 12 | if(n==1) 13 | return {new TreeNode(0)}; 14 | 15 | vector ans; 16 | 17 | for(int i=1;i left = allPossibleFBT(i); 20 | 21 | vector right = allPossibleFBT(n-i-1); 22 | 23 | for(auto l:left){ 24 | for(auto r:right){ 25 | TreeNode* root = new TreeNode(); 26 | root->left = l; 27 | root->right = r; 28 | ans.push_back(root); 29 | } 30 | } 31 | } 32 | return ans; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Arithmetic Slices II - Subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfArithmeticSlices(vector &nums) { 4 | int n = nums.size(); 5 | int ans = 0; 6 | vector> dp(n); 7 | for (int i = 1; i < n; i++) { 8 | for (int j = 0; j < i; j++) { 9 | long long diff = (long long) nums[i] - nums[j]; 10 | int cnt; 11 | if(dp[j].count(diff)){ 12 | cnt=dp[j][diff]; 13 | } 14 | else{ 15 | cnt=0; 16 | } 17 | dp[i][diff]+= cnt + 1; 18 | ans += cnt; 19 | } 20 | } 21 | return ans; 22 | } 23 | }; -------------------------------------------------------------------------------- /Asteroid Collision.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Asteroid Collision " Problem ==>> https://leetcode.com/problems/asteroid-collision/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/maNWFhgFuoU 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector asteroidCollision(vector& asteroids) { 11 | stack st; 12 | for(int i=0; i0 || st.empty()) 15 | st.push(asteroids[i]); 16 | else{ 17 | while(!st.empty() && st.top()>0 && st.top() ans(st.size()); 27 | for(int i=st.size()-1; i>=0; i--) 28 | { 29 | ans[i]=(st.top()); 30 | st.pop(); 31 | } 32 | return ans; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Average Salary Excluding the Minimum and Maximum Salary.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Average Salary Excluding the Minimum and Maximum Salary " Problem ==>> https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/yhfPWZLYj8w 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | double average(vector& salary) { 11 | double total = 0; 12 | int mini=INT_MAX,maxi=INT_MIN; 13 | for(int i=0;i averageOfLevels(TreeNode* root) { 4 | vector ans; 5 | queue q; 6 | q.push(root); 7 | while(!q.empty()){ 8 | long temp=0; 9 | int size= q.size(); 10 | for(int i=0;ileft!=NULL) q.push(node->left); 14 | if(node->right!=NULL) q.push(node->right); 15 | temp+=node->val; 16 | } 17 | ans.push_back((double)temp/size); 18 | } 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /Bag of Tokens.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int bagOfTokensScore(vector& tokens, int power) { 4 | sort(tokens.begin(), tokens.end()); 5 | int res = 0, points = 0, i = 0, j = tokens.size() - 1; 6 | while (i <= j) { 7 | if (power >= tokens[i]) { 8 | power -= tokens[i++]; 9 | res = max(res, ++points); 10 | } else if (points > 0) { 11 | points--; 12 | power += tokens[j--]; 13 | } else { 14 | break; 15 | } 16 | } 17 | return res; 18 | } 19 | }; -------------------------------------------------------------------------------- /Basic Calculator.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int calculate(string s) { 4 | stack nums, ops; 5 | long long int num = 0; 6 | long long int rst = 0; 7 | long long int sign = 1; 8 | for (char c : s) { 9 | if (isdigit(c)) { 10 | num = num * 10 + c - '0'; 11 | } 12 | else { 13 | rst += sign * num; 14 | num = 0; 15 | if (c == '+') 16 | sign = 1; 17 | if (c == '-') 18 | sign = -1; 19 | if (c == '(') { 20 | nums.push(rst); 21 | ops.push(sign); 22 | rst = 0; 23 | sign = 1; 24 | } 25 | if (c == ')' && ops.size()) { 26 | rst = ops.top() * rst + nums.top(); 27 | ops.pop(); nums.pop(); 28 | } 29 | } 30 | } 31 | rst += sign * num; 32 | return rst; 33 | } 34 | }; -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock with Cooldown.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int l = prices.size(); 5 | if(l < 2) return 0; 6 | 7 | int donothing1 = -prices[0]; 8 | int sell1 = 0; 9 | int donothing0 = 0; 10 | int buy0 = -prices[0]; 11 | for(int i=1; i buy0 ? donothing1 : buy0; 13 | buy0 = -prices[i] + donothing0; 14 | donothing0 = donothing0 > sell1 ? donothing0 : sell1; 15 | sell1 = prices[i] + donothing1; 16 | } 17 | return sell1 > donothing0 ? sell1 : donothing0; 18 | } 19 | 20 | }; -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Best Time to Buy and Sell Stock" Problem ==>> https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/Rp7dTS4gAJ0 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int maxProfit(vector& prices) { 11 | 12 | int buy = INT_MAX; 13 | int profit = 0; 14 | for(int i = 0; i < prices.size(); i++){ 15 | if(prices[i]> https://leetcode.com/problems/binary-search/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/8AUsxW6cu-Q 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | 11 | int func(int low,int high,vector nums,int target){ 12 | 13 | int mid=(low+high)/2; 14 | if(nums[mid]==target){ 15 | return mid; 16 | } 17 | else if(low==high){ 18 | return -1; 19 | } 20 | else if(nums[mid]>target){ 21 | return func(low,mid,nums,target); 22 | } 23 | else{ 24 | return func(mid+1,high,nums,target); 25 | } 26 | return -1; 27 | } 28 | 29 | 30 | int search(vector& nums, int target) { 31 | 32 | return func(0,nums.size()-1,nums,target); 33 | } 34 | }; -------------------------------------------------------------------------------- /Binary Tree Inorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | vector ans; 5 | vector inorderTraversal(TreeNode* root) { 6 | if(root==NULL){ 7 | return ans; 8 | } 9 | inorderTraversal(root->left); 10 | ans.push_back(root->val); 11 | inorderTraversal(root->right); 12 | return ans; 13 | } 14 | }; -------------------------------------------------------------------------------- /Binary Tree Maximum Path Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxPathSum(TreeNode* root) { 4 | int maxSum = INT_MIN; 5 | DFS(root, maxSum); 6 | return maxSum; 7 | } 8 | 9 | int DFS(TreeNode* root, int& maxSum){ 10 | if(!root) return 0; 11 | int left = max(0, DFS(root->left, maxSum)); 12 | int right = max(0, DFS(root->right, maxSum)); 13 | maxSum = max(maxSum, left + right + root->val); 14 | return max(left, right) + root->val; 15 | } 16 | }; -------------------------------------------------------------------------------- /Binary Tree Preorder Traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Binary Tree Preorder Traversal" Problem ==>> https://leetcode.com/problems/binary-tree-preorder-traversal/description/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/1XHKNPDFo7Q 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector ans; 11 | 12 | void fun(TreeNode* root){ 13 | if(root){ 14 | ans.push_back(root->val); 15 | fun(root->left); 16 | fun(root->right); 17 | } 18 | } 19 | 20 | vector preorderTraversal(TreeNode* root) { 21 | 22 | fun(root); 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Binary Tree Pruning.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* pruneTree(TreeNode* root) { 4 | 5 | if(!root) return NULL; 6 | 7 | TreeNode *left=pruneTree(root->left); 8 | TreeNode *right=pruneTree(root->right); 9 | 10 | if(root->val==0 and !left and !right) return NULL; 11 | 12 | root->left=left; 13 | root->right=right; 14 | return root; 15 | 16 | } 17 | }; -------------------------------------------------------------------------------- /Binary Trees With Factors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numFactoredBinaryTrees(vector& arr) { 4 | long long ans=0; 5 | unordered_map mp; 6 | sort(arr.begin(),arr.end()); 7 | for(int i=0;i> https://leetcode.com/problems/boats-to-save-people/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/cQHUQYE5k7E 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int numRescueBoats(vector& people, int limit) { 11 | 12 | int boatCount = 0; 13 | sort(people.begin(), people.end()); 14 | int left = 0; 15 | int right = people.size() - 1; 16 | while(left <= right){ 17 | int sum = people[left] + people[right]; 18 | if(sum <= limit){ 19 | boatCount++; 20 | left++; 21 | right--; 22 | } 23 | else{ 24 | boatCount++; 25 | right--; 26 | } 27 | } 28 | return boatCount; 29 | } 30 | }; -------------------------------------------------------------------------------- /Break a Palindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string breakPalindrome(string p) { 4 | int l = p.length(); 5 | 6 | if(l==1) 7 | return ""; 8 | 9 | int s = 0, e = l/2; 10 | 11 | bool changed = false; 12 | 13 | while(s> https://leetcode.com/problems/buddy-strings/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/v2FWcP-QGqo 5 | 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | bool buddyStrings(string s, string goal) { 12 | 13 | if(s.size()!=goal.size()){ 14 | return false; 15 | } 16 | 17 | unordered_map mp; 18 | 19 | for(int i=0;i> https://leetcode.com/problems/bulb-switcher/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/XCS71mUD85U 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int bulbSwitch(int n) { 11 | return int(sqrt(n)); 12 | } 13 | }; 14 | 15 | 16 | 17 | /* 2 approach 18 | class Solution { 19 | public: 20 | int bulbSwitch(int n) { 21 | 22 | int count = 0; 23 | for (int i = 1; i <= n; i++) { 24 | int squareRoot = sqrt(i); 25 | if (squareRoot * squareRoot == i) { 26 | count++; 27 | } 28 | } 29 | return count; 30 | 31 | } 32 | }; 33 | 34 | */ -------------------------------------------------------------------------------- /Can Make Arithmetic Progression From Sequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Can Make Arithmetic Progression From Sequence " Problem ==>> https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/QfojPZ1JDo4 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | bool canMakeArithmeticProgression(vector& arr) { 11 | sort(arr.begin(),arr.end()); 12 | for(int i = 1; i < arr.size()-1; i++){ 13 | if(2*arr[i] != arr[i-1]+arr[i+1]) 14 | return false; 15 | } 16 | return true; 17 | } 18 | };3 -------------------------------------------------------------------------------- /Can Place Flowers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Can Place Flowers " Problem ==>> https://leetcode.com/problems/can-place-flowers/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/0y480nJVzHs 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | bool canPlaceFlowers(vector& flowerbed, int n) { 11 | 12 | for (int i = 0; i < flowerbed.size(); i++) { 13 | 14 | if ((flowerbed[i] == 0) && (i == 0 || flowerbed[i-1] == 0) && 15 | (i == flowerbed.size() - 1 || flowerbed[i+1] == 0)) { 16 | flowerbed[i] = 1; 17 | n--; 18 | } 19 | } 20 | if (n > 0) 21 | return false; 22 | return true; 23 | } 24 | }; -------------------------------------------------------------------------------- /Candy.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Candy " Problem ==>> https://leetcode.com/problems/candy/description/?envType=daily-question&envId=2023-09-13 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/dmy_1QIUk4U 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int candy(vector& ratings) { 11 | int n = size(ratings); 12 | 13 | vector candies(n, 1); 14 | 15 | for (int i = 1; i < n; ++i) 16 | if (ratings[i] > ratings[i-1]) 17 | candies[i] = candies[i-1] + 1; 18 | 19 | 20 | 21 | for (int i = n-2; i >= 0; --i) 22 | if (ratings[i] > ratings[i+1]) 23 | candies[i] = max(candies[i], candies[i+1]+1); 24 | 25 | int ans = 0; 26 | for (int& c : candies) 27 | ans += c; 28 | 29 | return ans; 30 | } 31 | }; -------------------------------------------------------------------------------- /Champagne Tower.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Champagne Tower" Problem ==>> https://leetcode.com/problems/champagne-tower/description/?envType=daily-question&envId=2023-09-24 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/OT8L13mxv9E 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | double champagneTower(int poured, int query_row, int query_glass) { 11 | 12 | vector currRow(1, poured); 13 | 14 | for(int i=0; i<=query_row; i++){ 15 | 16 | vector nextRow(i+2, 0); 17 | 18 | for(int j=0; j<=i; j++){ 19 | 20 | if(currRow[j]>=1){ 21 | 22 | nextRow[j] += (currRow[j]-1)/2.0; 23 | nextRow[j+1] += (currRow[j]-1)/2.0; 24 | currRow[j] = 1; 25 | 26 | } 27 | } 28 | if(i!=query_row) 29 | currRow = nextRow; 30 | } 31 | return currRow[query_glass]; 32 | } 33 | }; -------------------------------------------------------------------------------- /Check Completeness of a Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Check Completeness of a Binary Tree " Problem ==>> https://leetcode.com/problems/check-completeness-of-a-binary-tree/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/O_EqWFtQ45g 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | bool isCompleteTree(TreeNode* root) { 11 | 12 | if(!root) 13 | return true; 14 | queue Q; 15 | Q.push(root); 16 | bool f = 0; 17 | while(!Q.empty()){ 18 | auto front = Q.front(); 19 | Q.pop(); 20 | if(front->left){ 21 | if(f) 22 | return false; 23 | Q.push(front->left); 24 | } 25 | else 26 | f=1; 27 | if(front->right){ 28 | if(f) 29 | return false; 30 | Q.push(front->right); 31 | } 32 | else 33 | f=1; 34 | } 35 | return true; 36 | } 37 | }; -------------------------------------------------------------------------------- /Check If It Is a Straight Line.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Check If It Is a Straight Line " Problem ==>> https://leetcode.com/problems/check-if-it-is-a-straight-line/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/FfWUgFmbMXo 5 | 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | bool checkStraightLine(vector>& coordinates) { 12 | 13 | int x0 = coordinates[0][0]; 14 | int y0 = coordinates[0][1]; 15 | int x1 = coordinates[1][0]; 16 | int y1 = coordinates[1][1]; 17 | for (int i = 2; i < coordinates.size(); i++) { 18 | int x = coordinates[i][0]; 19 | int y = coordinates[i][1]; 20 | if ((x - x0) * (y1 - y0) != (y - y0) * (x1 - x0)) { 21 | return false; 22 | } 23 | } 24 | return true; 25 | } 26 | }; -------------------------------------------------------------------------------- /Check if the Sentence Is Pangram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkIfPangram(string sen) { 4 | set s; 5 | for(int i=0;i> https://leetcode.com/problems/coin-change-ii/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/rjtoF2o5mt0 5 | 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int change(int amount, vector& coins) { 12 | 13 | vector dp(amount+1, 0); 14 | 15 | dp[0]=1; 16 | 17 | for(int c:coins){ 18 | 19 | for(int i=c; i<=amount; i++) 20 | 21 | dp[i]+=dp[i-c]; 22 | 23 | } 24 | return dp[amount]; 25 | } 26 | }; -------------------------------------------------------------------------------- /Combination Sum IV.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int dfs(vector& nums, int target, vector& ways) { 5 | if(target == 0) 6 | return 1; 7 | 8 | if(ways[target] != -1) 9 | return ways[target]; 10 | 11 | int totalWays = 0; 12 | for(int x : nums) { 13 | if(target >= x) { 14 | totalWays += dfs(nums, target-x, ways); 15 | } 16 | else{ 17 | break; 18 | } 19 | } 20 | return ways[target] = totalWays; 21 | } 22 | 23 | int combinationSum4(vector& nums, int target) { 24 | vector ways(target+1,); 25 | sort(nums.begin(),nums.end()); 26 | return dfs(nums,target,ways); 27 | } 28 | }; -------------------------------------------------------------------------------- /Concatenation of Consecutive Binary Numbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int concatenatedBinary(int n) { 4 | long res = 0, mod = 1e9+7, len_of_curr = 0; 5 | for (int i = 1; i <= n; i++) { 6 | if ((i & (i-1)) == 0) 7 | len_of_curr++; 8 | res = (res << len_of_curr) % mod; 9 | res += i % mod; 10 | } 11 | return res; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Construct Quad Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | Node *dfs(vector> &grid, int rows, int cols, int i, int j) { 4 | Node *node = new Node(); 5 | 6 | int isLeaf = 1; 7 | int val = grid[i][j]; 8 | 9 | for (int k = i; k < rows + i && isLeaf; ++k) { 10 | for (int l = j; l < cols + j && isLeaf; ++l) { 11 | if (grid[k][l] != val) isLeaf = 0; 12 | } 13 | } 14 | 15 | node->isLeaf = isLeaf; 16 | node->val = val; 17 | 18 | if (!isLeaf) { 19 | node->topLeft = dfs(grid, rows / 2, cols / 2, i, j); 20 | node->topRight = dfs(grid, rows / 2, cols / 2, i, j + cols / 2); 21 | node->bottomLeft = dfs(grid, rows / 2, cols / 2, i + rows / 2, j); 22 | node->bottomRight = dfs(grid, rows / 2, cols / 2, i + rows / 2, j + cols / 2); 23 | } 24 | 25 | return node; 26 | } 27 | 28 | public: 29 | Node *construct(vector> &grid) { 30 | int n = grid.size(); 31 | return dfs(grid, n, n, 0, 0); 32 | } 33 | }; -------------------------------------------------------------------------------- /Construct String from Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string tree2str(TreeNode* root) { 4 | if(!root) 5 | return ""; 6 | string s= to_string(root->val); 7 | if(root->left) s+="(" + tree2str(root->left) +")"; 8 | else if(root->right) s+="()"; 9 | if(root->right) s+="(" + tree2str(root->right) +")"; 10 | return s; 11 | } 12 | }; -------------------------------------------------------------------------------- /Convert Sorted Array to Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | TreeNode* helper(vector& nums, int left, int right){ 5 | if(left > right){ 6 | return NULL; 7 | } 8 | int mid = (left + right) / 2; 9 | TreeNode* temp = new TreeNode(nums[mid]); 10 | temp->left = helper(nums, left, mid-1); 11 | temp->right = helper(nums, mid+1 , right); 12 | return temp; 13 | } 14 | 15 | TreeNode* sortedArrayToBST(vector& nums) { 16 | return helper(nums, 0, nums.size()-1); 17 | } 18 | }; -------------------------------------------------------------------------------- /Convert Sorted List to Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Convert Sorted List to Binary Search Tree " Problem ==>> https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/mbEaJWHtTvQ 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | TreeNode* chk(int i, int j, vector& v){ 11 | 12 | if(i>j){ 13 | return NULL; 14 | } 15 | int mid=i+(j-i)/2; 16 | TreeNode* root=new TreeNode(v[mid]); 17 | root->left=chk(i, mid-1, v); 18 | root->right=chk(mid+1, j, v); 19 | return root; 20 | } 21 | TreeNode* sortedListToBST(ListNode* head) { 22 | 23 | vectorv; 24 | while(head){ 25 | v.push_back(head->val); 26 | head=head->next; 27 | } 28 | int i=0, j=v.size(); 29 | return chk(i, j-1, v); 30 | } 31 | }; -------------------------------------------------------------------------------- /Count Good Nodes in Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ans=0; 4 | void pre(TreeNode* root,int maxi){ 5 | if(!root) return; 6 | if(root->val>=maxi){ 7 | ans++; 8 | maxi = root->val; 9 | } 10 | pre(root->left,maxi); 11 | pre(root->right,maxi); 12 | } 13 | int goodNodes(TreeNode* root) { 14 | pre(root,INT_MIN); 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /Count Negative Numbers in a Sorted Matrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Count Negative Numbers in a Sorted Matrix " Problem ==>> https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/QqU24e6Es60 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int binsearch(vector>& grid,int r, int si, int ei){ 11 | if(si>ei) 12 | return 0; 13 | int mid = ei - (ei-si)/2; 14 | if(grid[r][mid]<0) 15 | return (ei-mid+1)+binsearch(grid,r,si,mid-1); 16 | return binsearch(grid,r,mid+1,ei); 17 | } 18 | 19 | int countNegatives(vector>& grid) { 20 | 21 | int count=0; 22 | for(int i=0; i> https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/vVsz2N1OlM4 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int countOdds(int low, int high) { 11 | if(low%2==0 && high%2==0){ 12 | return ((high-low)/2); 13 | } 14 | return (high-low)/2+1; 15 | } 16 | }; -------------------------------------------------------------------------------- /Count Subarrays With Fixed Bounds.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Count Subarrays With Fixed Bounds " Problem ==>> https://leetcode.com/problems/count-subarrays-with-fixed-bounds/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/zLv5H6CaTgE 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | long long countSubarrays(vector& nums, int minK, int maxK) { 11 | long res=0; 12 | int start=0,minstart=0,maxstart=0; 13 | bool minf=false,maxf=false; 14 | for(int i=0;imaxK){ 17 | minf=false; 18 | maxf=false; 19 | start=i+1; 20 | } 21 | if(num==minK){ 22 | minf=true; 23 | minstart=i; 24 | } 25 | if(num==maxK){ 26 | maxf=true; 27 | 28 | maxstart=i; 29 | } 30 | if(minf && maxf){ 31 | res+=(min(minstart,maxstart)-start+1); 32 | } 33 | } 34 | return res; 35 | } 36 | }; -------------------------------------------------------------------------------- /Count Ways To Build Good Strings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Count Ways To Build Good Strings " Problem ==>> https://leetcode.com/problems/count-ways-to-build-good-strings/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/PEJ883NDE4A 5 | 6 | */ 7 | 8 | class Solution { 9 | int mod=1e9+7; 10 | int solve(int target,int one ,int zero,vector&dp){ 11 | 12 | if(target==0) 13 | return 1; 14 | 15 | if(target<0) 16 | return 0; 17 | 18 | if(dp[target]!=-1) 19 | return dp[target]; 20 | 21 | long long sum; 22 | 23 | sum=solve(target-one,one,zero,dp)+solve(target-zero,one,zero,dp); 24 | 25 | return dp[target]=sum%mod; 26 | } 27 | public: 28 | int countGoodStrings(int low, int high, int zero, int one) { 29 | 30 | int ans=0; 31 | 32 | vectordp(high+1,-1); 33 | 34 | for(int i=low;i<=high;i++){ 35 | 36 | ans=((ans%mod)+solve(i,one,zero,dp))%mod; 37 | } 38 | return ans; 39 | } 40 | }; -------------------------------------------------------------------------------- /Counting Bits.cpp: -------------------------------------------------------------------------------- 1 | #Link to vedio Solution: https://www.youtube.com/watch?v=CHurGpL3FA4 2 | #Link to Problem: https://leetcode.com/problems/counting-bits/?envType=daily-question&envId=2023-09-01 3 | class Solution { 4 | public: 5 | vector countBits(int n) { 6 | 7 | vector ans(n+1,0); 8 | 9 | for(int i = 0; i<=n; i++){ 10 | if(i%2!=0){ 11 | ans[i]=ans[i>>1]+1; 12 | } 13 | else{ 14 | ans[i]=ans[i>>1]; 15 | } 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Counting elements in two arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | 4 | vector countEleLessThanOrEqual(int arr1[], int arr2[], 5 | int m, int n) 6 | { 7 | vector ans(m); 8 | sort(arr2, arr2+n); 9 | for(int i = 0; i < m; i++){ 10 | ans[i] = upper_bound(arr2, arr2+n, arr1[i]) - arr2; 11 | } 12 | return ans; 13 | } 14 | }; -------------------------------------------------------------------------------- /Daily Temperatures.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector dailyTemperatures(vector& temperatures) { 4 | int n = temperatures.size(); 5 | vectornge(n, 0); 6 | stackst{}; 7 | for(int i = n-1; i>=0; --i){ 8 | while(!st.empty() && temperatures[st.top()] <= temperatures[i]) 9 | st.pop(); 10 | if(!st.empty()) 11 | nge[i] = st.top()-i; 12 | st.push(i); 13 | } 14 | return nge; 15 | } 16 | }; -------------------------------------------------------------------------------- /Decode Ways.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dp[101]; 4 | 5 | int decoding(string s, int i){ 6 | 7 | if(i == s.length()) 8 | return 1; 9 | 10 | if(dp[i] != -1) 11 | return dp[i]; 12 | 13 | long long int cnt = 0; 14 | 15 | if(s[i] != '0') 16 | cnt += decoding(s, i+1); 17 | 18 | if(i& strs) { 4 | int ans=0; 5 | if (strs.empty()) return ans; 6 | for (int j = 0; j < strs[0].size(); j++) 7 | for (int i = 1; i < strs.size(); i++) { 8 | if (strs[i - 1][j] > strs[i][j]) { 9 | ans++; 10 | break; 11 | } 12 | } 13 | return ans; 14 | } 15 | }; -------------------------------------------------------------------------------- /Delete Node in a Linked List.cpp: -------------------------------------------------------------------------------- 1 | // Approach :1 2 | 3 | *node=*node->next; 4 | 5 | // Approach :2 6 | 7 | void deleteNode(ListNode* node) { 8 | ListNode* next = node->next; 9 | *node = *next; 10 | delete next; 11 | } -------------------------------------------------------------------------------- /Delete the Middle Node of a Linked List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* deleteMiddle(ListNode* head) { 4 | if(head->next==NULL)return NULL; 5 | ListNode*slow=head,*fast=head->next->next; 6 | while(fast&&fast->next){ 7 | slow=slow->next; 8 | fast=fast->next->next; 9 | } 10 | if(slow->next->next) 11 | slow->next=slow->next->next; 12 | else 13 | slow->next=NULL; 14 | return head; 15 | } 16 | }; -------------------------------------------------------------------------------- /Design Browser History.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Design Browser History " Problem ==>> https://leetcode.com/problems/design-browser-history/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/W2hhdHsGOUM 5 | 6 | */ 7 | 8 | class BrowserHistory { 9 | public: 10 | 11 | vectorhistory; 12 | int curr; 13 | 14 | BrowserHistory(string homepage) { 15 | history.push_back(homepage); 16 | curr = 0; 17 | } 18 | 19 | void visit(string url) { 20 | history.erase(history.begin()+curr+1,history.end()); 21 | history.push_back(url); 22 | curr++; 23 | } 24 | 25 | string back(int K) { 26 | curr = max(0,curr-K); 27 | return history[curr]; 28 | } 29 | 30 | string forward(int K) { 31 | curr = min((int)history.size()-1,curr+K); 32 | return history[curr]; 33 | } 34 | }; -------------------------------------------------------------------------------- /Design HashMap.cpp: -------------------------------------------------------------------------------- 1 | class MyHashMap { 2 | public: 3 | 4 | vector mp; 5 | 6 | MyHashMap() { 7 | mp.resize(1000001, -1); 8 | } 9 | 10 | void put(int key, int value) { 11 | mp[key] = value; 12 | } 13 | 14 | int get(int key) { 15 | return mp[key]; 16 | } 17 | 18 | void remove(int key) { 19 | mp[key] = -1; 20 | } 21 | }; -------------------------------------------------------------------------------- /Design HashSet.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Design HashSet " Problem ==>> https://leetcode.com/problems/design-hashset/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/5_GPb-91fIs 5 | 6 | */ 7 | 8 | 9 | class MyHashSet { 10 | public: 11 | int arr[10000001]; 12 | 13 | MyHashSet() { 14 | memset(arr,-1,sizeof(arr)); 15 | } 16 | 17 | void add(int key) { 18 | arr[key]=1; 19 | } 20 | 21 | void remove(int key) { 22 | arr[key]=-1; 23 | } 24 | 25 | bool contains(int key) { 26 | return arr[key]==1; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Design Parking System.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Design Parking System " Problem ==>> https://leetcode.com/problems/design-parking-system/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/f6AX-JRNRGE 5 | 6 | */ 7 | 8 | class ParkingSystem { 9 | public: 10 | int b; int m; int s; 11 | 12 | ParkingSystem(int big, int medium, int small) { 13 | b=big; m=medium; s=small; 14 | } 15 | 16 | bool addCar(int carType) { 17 | 18 | if(carType==1 && b>0){ 19 | b--; return true; 20 | } 21 | if(carType==2 && m>0){ 22 | m--; return true; 23 | } 24 | if(carType==3 && s>0){ 25 | s--; return true; 26 | } 27 | return false; 28 | } 29 | }; 30 | 31 | /** 32 | * Your ParkingSystem object will be instantiated and called as such: 33 | * ParkingSystem* obj = new ParkingSystem(big, medium, small); 34 | * bool param_1 = obj->addCar(carType); 35 | */ -------------------------------------------------------------------------------- /Detect Capital.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Detect Capital" Problem ==>> https://leetcode.com/problems/detect-capital/description/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/9zh4g6-CtUQ 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | bool detectCapitalUse(string word) { 11 | 12 | for(int i = 1; i < word.size(); i++){ 13 | if((isupper(word[1]) != isupper(word[i])) || (islower(word[0]) && isupper(word[i]))) 14 | return false; 15 | } 16 | return true; 17 | } 18 | }; -------------------------------------------------------------------------------- /Domino and Tromino Tiling.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numTilings(int N) { 4 | int a = 0, b = 1, c = 1, c2, mod = 1e9 + 7; 5 | while (--N) { 6 | c2 = (c * 2 % mod + a) % mod; 7 | a = b; 8 | b = c; 9 | c = c2; 10 | } 11 | return c; 12 | } 13 | }; -------------------------------------------------------------------------------- /Earliest Possible Day of Full Bloom.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int earliestFullBloom(vector& plantTime, vector& growTime) { 4 | int n = plantTime.size(); 5 | vector> times(n); 6 | for (int i = 0; i < n; i++) { 7 | times[i].first = -growTime[i]; 8 | times[i].second = plantTime[i]; 9 | } 10 | sort(times.begin(),times.end()); 11 | int total = 0; 12 | int current = 0; 13 | for (int i = 0; i < n; i++) { 14 | total = max(total,current+times[i].second-times[i].first); 15 | current += times[i].second; 16 | } 17 | return total; 18 | } 19 | }; -------------------------------------------------------------------------------- /Edit Distance.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | int minDistance(string word1, string word2) { 5 | int m=word1.length(),n=word2.length(); 6 | vector> dp(m+1,vector(n+1,-1)); 7 | for(int i=0;i<=m;i++) for(int j=0;j<=n;j++){ 8 | if(i==0) dp[i][j]=j; 9 | if(j==0) dp[i][j]=i; 10 | } 11 | 12 | for(int i=1;i<=m;i++) for(int j=1;j<=n;j++){ 13 | if(word1[i-1]==word2[j-1]) dp[i][j]=dp[i-1][j-1]; 14 | else{ 15 | dp[i][j]= 1 + min(min(dp[i-1][j],dp[i][j-1]),dp[i-1][j-1]); 16 | } 17 | } 18 | 19 | return dp[m][n]; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Evaluate Reverse Polish Notation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Evaluate Reverse Polish Notation" Problem ==>> https://leetcode.com/problems/evaluate-reverse-polish-notation/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/RNns2yxMOiA 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int evalRPN(vector& tokens) { 11 | stack st; 12 | for(string s:tokens) { 13 | if(s.size()>1 || isdigit(s[0])){ 14 | st.push(stoi(s)); 15 | } 16 | else { 17 | long long int x2=st.top(); 18 | st.pop(); 19 | long long int x1=st.top(); 20 | st.pop(); 21 | switch(s[0]) { 22 | case '+': x1+=x2; break; 23 | case '-': x1-=x2; break; 24 | case '*': x1*=x2; break; 25 | case '/': x1/=x2; break; 26 | default : break; 27 | } 28 | st.push(x1); 29 | } 30 | } 31 | return st.top(); 32 | } 33 | }; -------------------------------------------------------------------------------- /Fair Distribution of Cookies.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Fair Distribution of Cookies " Problem ==>> https://leetcode.com/problems/fair-distribution-of-cookies/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/T_2AOlGIvfg 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int solve(vector&v,int i,vector&a){ 11 | 12 | if(i==v.size()){ 13 | int ans=0; 14 | for(auto it : a) 15 | ans=max(ans,it); 16 | return ans; 17 | } 18 | 19 | int mn=INT_MAX; 20 | 21 | for(int j=0;j&v, int k) { 33 | 34 | int i,n=v.size(); 35 | vectora(k); 36 | 37 | return solve(v,0,a); 38 | } 39 | }; -------------------------------------------------------------------------------- /Find Duplicate Subtrees.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Find Duplicate Subtrees 3 | " Problem ==>> https://leetcode.com/problems/find-duplicate-subtrees/ 4 | 5 | Link to the complete Explaination Video ==>> https://youtu.be/2OBDP3Omi30 6 | 7 | */ 8 | 9 | class Solution { 10 | public: 11 | vector findDuplicateSubtrees(TreeNode* root) { 12 | 13 | unordered_mapa; 14 | vectorans; 15 | solve(root,a,ans); 16 | return ans; 17 | } 18 | string solve(TreeNode* root,unordered_map&a,vector&ans){ 19 | if(!root){ 20 | return ""; 21 | } 22 | string s=to_string(root->val)+","+solve(root->left,a,ans)+","+solve(root->right,a,ans); 23 | a[s]++; 24 | if(a[s]==2){ 25 | ans.push_back(root); 26 | } 27 | return s; 28 | } 29 | }; -------------------------------------------------------------------------------- /Find Eventual Safe States.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Find Eventual Safe States " Problem ==>> https://leetcode.com/problems/find-eventual-safe-states/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/7iRQGtz3qn8 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | map safe; 11 | vector res; 12 | 13 | bool dfs(int node, vector>& graph) { 14 | 15 | if (safe.find(node) != safe.end()) 16 | return safe[node]; 17 | 18 | safe[node] = 0; 19 | 20 | for (auto neighbor : graph[node]) { 21 | if (!dfs(neighbor, graph)) { 22 | return false; 23 | } 24 | } 25 | 26 | safe[node] = 1; 27 | return true; 28 | } 29 | 30 | vector eventualSafeNodes(vector>& graph) { 31 | 32 | for (int i = 0; i < graph.size(); i++) { 33 | 34 | if (dfs(i, graph)) { 35 | res.push_back(i); 36 | } 37 | } 38 | 39 | 40 | return res; 41 | } 42 | }; -------------------------------------------------------------------------------- /Find K Closest Elements.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | vector findClosestElements(vector& arr, int k, int x) { 4 | vectorans; 5 | int n = arr.size(); 6 | priority_queue , vector> , greater>>q; 7 | for(int i=0 ; iMaxHeap; 5 | priority_queue,greater>MinHeap; 6 | 7 | MedianFinder(){} 8 | 9 | void addNum(int num) { 10 | MaxHeap.push(num); 11 | MinHeap.push(MaxHeap.top()); 12 | MaxHeap.pop(); 13 | if(MinHeap.size() > MaxHeap.size()) 14 | { 15 | MaxHeap.push(MinHeap.top()); 16 | MinHeap.pop(); 17 | } 18 | } 19 | 20 | double findMedian() { 21 | if(MaxHeap.size() > MinHeap.size()) return MaxHeap.top(); 22 | else return (double)(MaxHeap.top()+MinHeap.top())/2.0; 23 | } 24 | }; -------------------------------------------------------------------------------- /Find Original Array From Doubled Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findOriginalArray(vector& changed) { 4 | int n = changed.size(); 5 | if (n % 2 == 1) return {}; 6 | sort(changed.begin(), changed.end()); 7 | vector ans; 8 | map mp; 9 | for (int i = 0; i < n; i++) { 10 | mp[changed[i]]++; 11 | } 12 | for (int i = 0; i < n; i++) { 13 | if (mp[changed[i]] == 0) continue; 14 | if (mp[changed[i] * 2] == 0) return {}; 15 | ans.push_back(changed[i]); 16 | mp[changed[i]]--; 17 | mp[changed[i] * 2]--; 18 | } 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /Find Players With Zero or One Losses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> findWinners(vector>& matches) { 4 | unordered_set u; 5 | map m; 6 | int n=matches.size(); 7 | for(int i=0;i> ans(2); 13 | n=u.size(); 14 | 15 | for(auto i=u.begin();i!=u.end();i++){ 16 | if(!m[*i]) ans[0].push_back(*i); 17 | else if(m[*i]==1) ans[1].push_back(*i); 18 | } 19 | 20 | sort(ans[1].begin(),ans[1].end()); 21 | sort(ans[0].begin(),ans[0].end()); 22 | 23 | return ans; 24 | } 25 | }; -------------------------------------------------------------------------------- /Find and Replace Pattern.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector find(string a){ 4 | vector f; 5 | if(a.size()==0) 6 | return f; 7 | int ind=0; 8 | unordered_map m; 9 | for(int i=0;i findAndReplacePattern(vector& words, string pattern) { 21 | vector p=find(pattern); 22 | vector ans; 23 | for(int i=0;i w=find(words[i]); 25 | if(p==w) 26 | ans.push_back(words[i]); 27 | } 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /Find the Difference.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Find the Difference" Problem ==>> https://leetcode.com/problems/find-the-difference/description/?envType=daily-question&envId=2023-09-25 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/V0_3dDXmOKw 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | char findTheDifference(string s, string t) { 11 | int n = s.length(); 12 | sort(s.begin(), s.end()); 13 | sort(t.begin(), t.end()); 14 | for(int i=0; i> https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/MIu2o3Wrlg0 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int strStr(string h, string n) { 11 | 12 | if(h.size()> https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/o84Vb1qbZms 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | 11 | int firstGreater(const vector& A, int target) { 12 | return upper_bound(begin(A), end(A), target) - begin(A); 13 | } 14 | 15 | vector longestObstacleCourseAtEachPosition(vector& obstacles) { 16 | 17 | vector ans; 18 | vector tail; 19 | for (int obstacle : obstacles){ 20 | if (tail.empty() || obstacle >= tail.back()) { 21 | tail.push_back(obstacle); 22 | ans.push_back(tail.size()); 23 | } 24 | else { 25 | int index = firstGreater(tail, obstacle); 26 | tail[index] = obstacle; 27 | ans.push_back(index + 1); 28 | } 29 | } 30 | return ans; 31 | } 32 | }; -------------------------------------------------------------------------------- /Find the Town Judge.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Find the Town Judge" Problem ==>> https://leetcode.com/problems/find-the-town-judge/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/u0HQXBc8V0E 5 | 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int findJudge(int N, vector>& trust) { 12 | 13 | vector Trusted(N + 1, 0); 14 | for(auto person : trust){ 15 | Trusted[person[0]]--; 16 | Trusted[person[1]]++; 17 | } 18 | for(int i = 1;i <= N;i++){ 19 | if(Trusted[i] == N - 1) 20 | return i; 21 | } 22 | return -1; 23 | } 24 | }; -------------------------------------------------------------------------------- /First Unique Character in a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstUniqChar(string s) { 4 | unordered_map ma; 5 | for(int i=0;i> https://leetcode.com/problems/flip-string-to-monotone-increasing/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/l1hif4AqUW8 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int minFlipsMonoIncr(string s) { 11 | 12 | int flips = 0, counter = 0; 13 | for (auto c : s) { 14 | if (c == '1') 15 | counter++; 16 | else 17 | flips++; 18 | flips = min(flips, counter); 19 | } 20 | return flips; 21 | } 22 | }; -------------------------------------------------------------------------------- /Fruit Into Baskets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int totalFruit(vector &tree) { 4 | unordered_map count; 5 | int i, j,ans=INT_MIN; 6 | for (i = 0, j = 0; j < tree.size(); ++j) { 7 | count[tree[j]]++; 8 | while(count.size() > 2) { 9 | if (--count[tree[i]] == 0)count.erase(tree[i]); 10 | i++; 11 | } 12 | ans=max(ans,(j-i+1)); 13 | } 14 | return ans; 15 | } 16 | }; -------------------------------------------------------------------------------- /Gas Station.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int canCompleteCircuit(vector& gas, vector& cost) { 4 | int n = gas.size(); 5 | int max = gas[n-1] - cost[n-1]; 6 | int total = max; 7 | int ans = n-1; 8 | 9 | for (int i = n-2; i >= 0; i--) { 10 | total += gas[i] - cost[i]; 11 | if (total > max) { 12 | ans = i; 13 | max = total; 14 | } 15 | } 16 | return total >= 0 ? ans : -1; 17 | } 18 | }; -------------------------------------------------------------------------------- /Greatest Common Divisor of Strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string gcdOfStrings(string str1, string str2) { 4 | if (str1.size() < str2.size()) return gcdOfStrings(str2, str1); 5 | if (str2.empty()) return str1; 6 | if (str1.substr(0, str2.size()) != str2) return ""; 7 | return gcdOfStrings(str1.substr(str2.size()), str2); 8 | } 9 | }; -------------------------------------------------------------------------------- /Group Anagrams.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> groupAnagrams(vector& strs) { 4 | vector> ans; 5 | unordered_map> mp; 6 | for(int i = 0 ; i < strs.size() ; i++) 7 | { 8 | string s = strs[i]; 9 | sort(strs[i].begin(),strs[i].end()); 10 | mp[strs[i]].push_back(s); 11 | } 12 | for(auto i : mp) 13 | { 14 | ans.push_back(i.second); 15 | } 16 | return ans; 17 | } 18 | }; -------------------------------------------------------------------------------- /Group the People Given the Group Size They Belong To.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Group the People Given the Group Size They Belong To " Problem ==>> https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/?envType=daily-question&envId=2023-09-11 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/6ikOxMQrb24 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector> groupThePeople(vector& groupSizes) { 11 | 12 | vector> ans; 13 | 14 | unordered_map> dict; 15 | 16 | for (int i=0; i> https://leetcode.com/problems/house-robber/description/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/78AW9ZrOXnE 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int rob(vector& nums) { 11 | int n=nums.size(); 12 | vectordp(n,0); 13 | dp[0]=nums[0]; 14 | for(int i=1;i1){ 17 | pick+=dp[i-2]; 18 | } 19 | dp[i]=max(pick,dp[i-1]); 20 | } 21 | return dp[n-1]; 22 | } 23 | }; -------------------------------------------------------------------------------- /Image Overlap.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestOverlap(vector>& img1, vector>& img2) { 4 | int n=img1.size(); 5 | vector>vec_a; 6 | vector>vec_b; 7 | for(int i=0;i,int>mp; 19 | for(auto [i1,j1]:vec_a){ 20 | for(auto [i2,j2]:vec_b){ 21 | mp[{i1-i2,j1-j2}]++; 22 | ans=max(ans,mp[{i1-i2,j1-j2}]); 23 | } 24 | } 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /Implement Queue using Stacks.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Implement Queue using Stacks" Problem ==>> https://leetcode.com/problems/implement-queue-using-stacks/description/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/5bjAbpWaip4 5 | 6 | */ 7 | 8 | class MyQueue { 9 | private: 10 | stack s1,s2; 11 | public: 12 | MyQueue() { 13 | } 14 | void push(int x) { 15 | s1.push(x); 16 | } 17 | int pop() { 18 | int res = peek(); 19 | s2.pop(); 20 | return res; 21 | } 22 | int peek() { 23 | if(s2.empty()){ 24 | while(!s1.empty()){ 25 | s2.push(s1.top()); 26 | s1.pop(); 27 | } 28 | } 29 | int res = s2.top(); 30 | return res; 31 | } 32 | bool empty() { 33 | return s1.empty()&&s2.empty(); 34 | } 35 | }; -------------------------------------------------------------------------------- /Implement Trie (Prefix Tree).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Implement Trie (Prefix Tree) " Problem ==>> https://leetcode.com/problems/implement-trie-prefix-tree/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/_5dmDxPPBU4 5 | 6 | */ 7 | 8 | class Trie { 9 | public: 10 | set st; 11 | 12 | Trie(){} 13 | 14 | void insert(string word) { 15 | st.insert(word); 16 | } 17 | 18 | bool search(string word) { 19 | return st.find(word) != st.end(); 20 | } 21 | 22 | bool startsWith(string prefix) { 23 | 24 | auto it = st.lower_bound(prefix); 25 | if(it == st.end()) 26 | return false; 27 | for(int i = 0;i& nums) { 4 | if(nums.size() < 3){ 5 | return false; 6 | } 7 | int x = INT_MAX, y = INT_MAX; 8 | for(int i : nums) { 9 | if(i <= x) 10 | x = i; 11 | else if(i <= y) 12 | y = i; 13 | else 14 | return true; 15 | } 16 | return false; 17 | } 18 | }; -------------------------------------------------------------------------------- /Insert Delete GetRandom O(1).cpp: -------------------------------------------------------------------------------- 1 | class RandomizedSet { 2 | private: 3 | vector a; 4 | unordered_map m; 5 | public: 6 | RandomizedSet() { 7 | } 8 | 9 | bool insert(int val) { 10 | 11 | if(m[val]>0) 12 | return false; 13 | else{ 14 | a.push_back(val); 15 | m[val]=a.size(); 16 | return true; 17 | } 18 | } 19 | 20 | bool remove(int val) { 21 | if(m[val]==0) 22 | return false; 23 | else{ 24 | int last=a.back(); 25 | a[m[val]-1]=a.back(); 26 | a.pop_back(); 27 | m[last]=m[val]; 28 | m.erase(val); 29 | return true; 30 | } 31 | } 32 | 33 | int getRandom() { 34 | return a[rand()%a.size()]; 35 | } 36 | }; -------------------------------------------------------------------------------- /Insert Interval.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Insert Interval" Problem ==>> https://leetcode.com/problems/insert-interval/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/VTQ0JYL8IHg 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector> insert(vector>& intervals, vector& newInterval) { 11 | int n = intervals.size(); 12 | int i = 0; 13 | vector> res; 14 | while(i < n && intervals[i][1] < newInterval[0]){ 15 | res.push_back(intervals[i]); 16 | i++; 17 | } 18 | while(i < n && newInterval[1] >= intervals[i][0]){ 19 | newInterval[0] = min(newInterval[0], intervals[i][0]); 20 | newInterval[1] = max(newInterval[1], intervals[i][1]); 21 | i++; 22 | } 23 | res.push_back(newInterval); 24 | while(i < n){ 25 | res.push_back(intervals[i]); 26 | i++; 27 | } 28 | return res; 29 | } 30 | }; -------------------------------------------------------------------------------- /Invert Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Invert Binary Tree" Problem ==>> https://leetcode.com/problems/invert-binary-tree/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/ZOj0cIdwUYI 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | TreeNode* invertTree(TreeNode* root) { 11 | 12 | if(!root) 13 | return NULL; 14 | 15 | swap(root->left, root->right); 16 | invertTree(root->left); 17 | invertTree(root->right); 18 | return root; 19 | 20 | } 21 | }; -------------------------------------------------------------------------------- /Is Subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Is Subsequence" Problem ==>> https://leetcode.com/problems/is-subsequence/description/?envType=daily-question&envId=2023-09-22 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/QrLKHEKYdiI 5 | 6 | */ 7 | 8 | class Solution { 9 | int isSubSequence(string& s1, string& s2, int i, int j) 10 | { 11 | if (i == 0 || j == 0) { 12 | return 0; 13 | } 14 | else if (s1[i - 1] == s2[j - 1]) { 15 | return 1 + isSubSequence(s1, s2, i - 1, j - 1); 16 | } 17 | return isSubSequence(s1, s2, i, j - 1); 18 | } 19 | 20 | public: 21 | bool isSubsequence(string s, string t) { 22 | int m = s.size(); 23 | int n = t.size(); 24 | if (m > n) { 25 | return false; 26 | } 27 | if (isSubSequence(s, t, m, n) == m) { 28 | return true; 29 | } 30 | return false; 31 | } 32 | }; -------------------------------------------------------------------------------- /Jump Game II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Jump Game II" Problem ==>> https://leetcode.com/problems/jump-game-ii/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/u-El7w9BnK0 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int jump(vector& nums) {. 11 | 12 | int n = nums.size(); 13 | if (n < 2) return 0; 14 | int curMax = 0, nextMax = 0, jumps = 0; 15 | for (int i = 0; i < n - 1; i++) { 16 | nextMax = max(nextMax, i + nums[i]); 17 | if (i == curMax){ 18 | jumps++; 19 | curMax = nextMax; 20 | if (curMax >= n - 1) 21 | break; 22 | } 23 | } 24 | return jumps; 25 | } 26 | }; -------------------------------------------------------------------------------- /Jump Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector &nums) { 4 | int max_distance = 0; 5 | const int target = nums.size() - 1; 6 | for (int i = 0; i < nums.size() && i <= max_distance; ++i) { 7 | max_distance = std::max(max_distance, nums[i] + i); 8 | } 9 | return target <= max_distance; 10 | } 11 | }; -------------------------------------------------------------------------------- /Keys and Rooms.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Evaluate Reverse Polish Notation" Problem ==>> https://leetcode.com/problems/keys-and-rooms/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/aH3Og3dKpCM 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | bool canVisitAllRooms(vector>& rooms){ 11 | int n=rooms.size(); 12 | vector visited(n,0); 13 | queue q; 14 | q.push(0); 15 | visited[0]=1; 16 | while(!q.empty()) { 17 | int current = q.front(); 18 | q.pop(); 19 | for (int k : rooms[current]){ 20 | if(visited[k]==0){ 21 | q.push(k); 22 | visited[k]=1; 23 | } 24 | } 25 | } 26 | 27 | for(int i=0;i> https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/_tH2KNcUb04 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector kidsWithCandies(vector& candies, int extraCandies) { 11 | 12 | int maxi=0; 13 | maxi = *max_element(candies.begin(),candies.end()); 14 | vector result; 15 | for(int i=0;i=maxi){ 18 | result.push_back(true); 19 | } 20 | else{ 21 | result.push_back(false); 22 | } 23 | } 24 | return result; 25 | } 26 | }; -------------------------------------------------------------------------------- /Koko Eating Bananas.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Koko Eating Bananas " Problem ==>> https://leetcode.com/problems/koko-eating-bananas/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/g8AS-1vRsa4 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int minEatingSpeed(vector& piles, int h) { 11 | int i=1, j=*max_element(piles.begin(), piles.end()), ans; 12 | while(i<=j){ 13 | int mid=i+(j-i)/2; 14 | long long int cnt=0; 15 | for(int i=0; ih){ 20 | i=mid+1; 21 | } 22 | else{ 23 | j=mid-1; 24 | } 25 | } 26 | return i; 27 | } 28 | }; -------------------------------------------------------------------------------- /Kth Largest Element in a Stream.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Kth Largest Element in a Stream " Problem ==>> https://leetcode.com/problems/kth-largest-element-in-a-stream/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/RcFFZFsVSEI 5 | 6 | */ 7 | 8 | class KthLargest { 9 | public: 10 | priority_queue,greater> pq; 11 | int position; 12 | 13 | KthLargest(int k, vector& nums) { 14 | position=k; 15 | for(int i=0;i> https://leetcode.com/problems/kth-largest-element-in-an-array/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/QLCGmSjD9c8 5 | 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int findKthLargest(vector& nums, int k) { 12 | 13 | int size = nums.size(); 14 | 15 | priority_queue , greater > pq ; 16 | for(int i =0 ; ik) 19 | pq.pop(); 20 | } 21 | return pq.top() ; 22 | } 23 | }; -------------------------------------------------------------------------------- /Kth Missing Positive Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Kth Missing Positive Number " Problem ==>> https://leetcode.com/problems/kth-missing-positive-number/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/DpEMbKwHJKQ 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int findKthPositive(vector& arr, int k) { 11 | int lo = 0, hi = arr.size(); 12 | while (lo < hi) { 13 | int mid = lo + (hi - lo) / 2; 14 | if (arr[mid] - mid > k) hi = mid; 15 | else lo = mid + 1; 16 | } 17 | return hi + k; 18 | } 19 | }; -------------------------------------------------------------------------------- /Kth Smallest Element in a Sorted Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int kthSmallest(vector>& m, int k) { 4 | int n=m.size(); 5 | int low=m[0][0]; 6 | int high=m[n-1][n-1]; 7 | while(low& nums) { 4 | sort(nums.begin(),nums.end()); 5 | for(int i=nums.size()-1;i>=2;i--) 6 | if(nums[i]> https://leetcode.com/problems/last-stone-weight/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/5P26CXY-Rbk 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int lastStoneWeight(vector& stones) { 11 | 12 | priority_queue p; 13 | for(int i=0;i1){ 17 | int ans=p.top(); 18 | p.pop(); 19 | ans=ans-p.top(); 20 | p.pop(); 21 | p.push(ans); 22 | } 23 | return p.top(); 24 | } 25 | }; -------------------------------------------------------------------------------- /Leaf-Similar Trees.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Link to the "Distance of nearest cell having 1" Problem ==>> https://leetcode.com/problems/leaf-similar-trees/ 4 | 5 | Link to the complete Explaination Video ==>> https://youtu.be/eoEbu0TnF7Q 6 | 7 | */ 8 | 9 | class Solution { 10 | public: 11 | void inorder(TreeNode* root,vector& x){ 12 | if(root==NULL) return; 13 | inorder(root->left,x); 14 | if(!root->left && !root->right) x.push_back(root->val); 15 | inorder(root->right,x); 16 | } 17 | bool leafSimilar(TreeNode* root1, TreeNode* root2) { 18 | vector a,b; 19 | inorder(root1,a); 20 | inorder(root2,b); 21 | return a==b; 22 | } 23 | }; -------------------------------------------------------------------------------- /Linked List Cycle II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Linked List Cycle II " Problem ==>> https://leetcode.com/problems/linked-list-cycle-ii/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/owc1yVJOklw 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | ListNode *detectCycle(ListNode *head) { 11 | ListNode *slw,*fst; 12 | slw=fst=head; 13 | while(fst && fst->next){ 14 | slw = slw->next; 15 | fst = fst->next->next; 16 | if(fst==slw)break; 17 | } 18 | if(!fst || !fst->next) 19 | return NULL; 20 | fst=head; 21 | while(fst!=slw){ 22 | fst=fst->next; 23 | slw=slw->next; 24 | } 25 | return fst; 26 | } 27 | }; -------------------------------------------------------------------------------- /Linked List Random Node.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Linked List Random Node " Problem ==>> https://leetcode.com/problems/linked-list-random-node/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/qQDM1J02Sq4 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | ListNode *head = NULL; 11 | 12 | Solution(ListNode* head) { 13 | this->head = head; 14 | } 15 | 16 | int getRandom() { 17 | int ans = 0, i = 1; 18 | ListNode *p = this->head; 19 | while (p) { 20 | if (rand() % i == 0) 21 | ans = p->val; 22 | i++; 23 | p = p->next; 24 | } 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /Longest Arithmetic Subsequence of Given Difference.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Longest Arithmetic Subsequence of Given Difference " Problem ==>> https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/9BqVjYVLSMU 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int longestSubsequence(vector& nums, int diff) { 11 | int n=nums.size(); 12 | 13 | unordered_map mp; 14 | 15 | int ans=1; 16 | 17 | for(auto x:nums){ 18 | 19 | if(mp.count(x-diff)){ 20 | mp[x]=mp[x-diff]+1; 21 | } 22 | else{ 23 | mp[x]=1; 24 | } 25 | ans=max(ans,mp[x]); 26 | } 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /Longest Common Subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Longest Common Subsequence" Problem ==>> https://leetcode.com/problems/longest-common-subsequence/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/zP9KksDZ3vI 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int longestCommonSubsequence(string text1, string text2) { 11 | int m = text1.size(), n = text2.size(); 12 | int dp[m+1][n+1]; 13 | for(int i = 0; i <= m; i++) { 14 | for(int j = 0; j <= n; j++) { 15 | if(i == 0 || j == 0) 16 | dp[i][j] = 0; 17 | else if(text1[i-1] == text2[j-1]) 18 | dp[i][j] = 1 + dp[i-1][j-1]; 19 | else 20 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]); 21 | } 22 | } 23 | return dp[m][n]; 24 | } 25 | }; -------------------------------------------------------------------------------- /Longest Palindrome by Concatenating Two Letter Words.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestPalindrome(vector& words) { 4 | int ans=0; 5 | unordered_map ma; 6 | for(int i=0;i0){ 8 | ans+=4; 9 | ma[words[i]]--; 10 | if(ma[words[i]]==0){ 11 | ma.erase(words[i]); 12 | } 13 | } 14 | else{ 15 | reverse(words[i].begin(),words[i].end()); 16 | ma[words[i]]++; 17 | } 18 | } 19 | for(auto it:ma){ 20 | string s=it.first; 21 | if(s[0]==s[1]){ 22 | ans+=2; 23 | break; 24 | } 25 | } 26 | return ans; 27 | } 28 | }; 29 | 30 | -------------------------------------------------------------------------------- /Longest Palindromic Subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Longest Palindromic Subsequence " Problem ==>> https://leetcode.com/problems/longest-palindromic-subsequence/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/71jPaTBK1dc 5 | 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int longestPalindromeSubseq(string s) { 12 | 13 | int n=s.length(); 14 | string rev=s; 15 | reverse(rev.begin(),rev.end()); 16 | int t[n+1][n+1]; 17 | for(int i=0;i mp; 6 | while(hifirst - mp.begin()->first > 1) { 9 | mp[a[lo]]--; 10 | if(mp[a[lo]]==0) mp.erase(a[lo]); 11 | lo++; 12 | } 13 | ans=max(ans, hi-lo+1); 14 | hi++; 15 | } 16 | return ans; 17 | } 18 | }; -------------------------------------------------------------------------------- /Longest String Chain.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Is Subsequence" Problem ==>> https://leetcode.com/problems/longest-string-chain/?envType=daily-question&envId=2023-09-23 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/eS3a5sOMyog 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | static bool cmp(const string &s1, const string &s2) { 11 | return s1.length() < s2.length(); 12 | } 13 | 14 | int longestStrChain(vector& words) { 15 | 16 | sort(words.begin(), words.end(), cmp); 17 | 18 | unordered_map ump; 19 | 20 | int ans = 0; 21 | 22 | for (string w : words) { 23 | int longest=0; 24 | 25 | for (int i = 0; i < w.length(); i++) { 26 | string sub = w; 27 | sub.erase(i, 1); 28 | longest = max(longest,ump[sub]+1); 29 | } 30 | 31 | ump[w] = longest; 32 | 33 | ans = max(ans,longest); 34 | } 35 | return ans; 36 | } 37 | }; -------------------------------------------------------------------------------- /Longest Subarray of 1's After Deleting One Element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Longest Subarray of 1's After Deleting One Element " Problem ==>> https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/WpqF7Mv_gnk 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int longestSubarray(vector& nums) { 11 | 12 | int start=0,end=0,n=nums.size(); 13 | 14 | int ans=0; 15 | 16 | int skip=0; 17 | 18 | while(end1){ 24 | skip-=nums[start]==0; 25 | start++; 26 | } 27 | 28 | ans=max(ans,end-start); 29 | end++; 30 | } 31 | 32 | return ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /Longest Subsequence With Limited Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector answerQueries(vector& nums, vector& queries) { 4 | sort(nums.begin(),nums.end()); 5 | for(int i=1;i ans; 7 | for(int i:queries){ 8 | int res=upper_bound(nums.begin(),nums.end(),i)-nums.begin(); 9 | ans.push_back(res); 10 | } 11 | return ans; 12 | } 13 | }; -------------------------------------------------------------------------------- /Lowest Common Ancestor of a Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 5 | if (root==NULL || root == p || root == q) 6 | return root; 7 | 8 | TreeNode* left =lowestCommonAncestor(root->left, p, q); 9 | TreeNode* right =lowestCommonAncestor(root->right, p, q); 10 | 11 | if(left && right) 12 | return root; 13 | else if(left) 14 | return left; 15 | else if(right) 16 | return right; 17 | 18 | return NULL; 19 | } 20 | }; -------------------------------------------------------------------------------- /Lowest Common Ancestor of a Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 4 | if(root==p||root==q||root==NULL) 5 | return root; 6 | TreeNode* left=lowestCommonAncestor(root->left,p,q); 7 | TreeNode* right=lowestCommonAncestor(root->right,p,q); 8 | if(!left) 9 | return right; 10 | else if(!right) 11 | return left; 12 | else return root; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Majority Element II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Majority Element II" Problem ==>> https://leetcode.com/problems/majority-element-ii/?envType=daily-question&envId=2023-10-05 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/CgoiWJU5FIw 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector majorityElement(vector& nums) { 11 | 12 | unordered_map freq; 13 | 14 | int n = nums.size(); 15 | 16 | vector ans; 17 | 18 | for(auto it : nums) { 19 | freq[it]++; 20 | } 21 | 22 | for(auto it : freq){ 23 | if(it.second > floor(n/3)) 24 | ans.push_back(it.first); 25 | } 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /Make The String Great.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string makeGood(string s) { 4 | int n=s.size(); 5 | stack st; 6 | for(int i=0;i> https://leetcode.com/problems/matrix-diagonal-sum/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/u8x28hURqts 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int diagonalSum(vector>& mat) { 11 | 12 | int s=0,i=0,j=0; 13 | while(i>& m, int k) { 4 | int res = INT_MIN, rows = m.size(), cols = m[0].size(); 5 | for (int l = 0; l < cols; ++l) { 6 | vector sums(rows); 7 | for (int r = l; r < cols; ++r) { 8 | for (int i = 0; i < rows; ++i){ 9 | sums[i] += m[i][r]; 10 | } 11 | set s = {0}; 12 | int maxisum = 0; 13 | for (int sum : sums) { 14 | maxisum += sum; 15 | auto it = s.lower_bound(maxisum - k); 16 | if (it != end(s)) 17 | res = max(res, maxisum - *it); 18 | s.insert(maxisum); 19 | } 20 | } 21 | } 22 | return res; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Maximal Network Rank.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Maximal Network Rank " Problem ==>> https://leetcode.com/problems/maximal-network-rank/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/-bauKABZQyI 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int maximalNetworkRank(int n, vector>& roads) { 11 | 12 | int ans = 0; 13 | 14 | vector> adj(n, unordered_set ()); 15 | 16 | for(auto road: roads){ 17 | adj[road[0]].insert(road[1]); 18 | adj[road[1]].insert(road[0]); 19 | } 20 | 21 | for(int i = 0; i < n; i++){ 22 | for(int j = i+1; j < n; j++){ 23 | 24 | int tmp = adj[i].size()+adj[j].size(); 25 | 26 | if(adj[i].count(j)) 27 | tmp--; 28 | 29 | ans = max(ans, tmp); 30 | } 31 | } 32 | return ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /Maximize the Confusion of an Exam.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Maximize the Confusion of an Exam " Problem ==>> https://leetcode.com/problems/maximize-the-confusion-of-an-exam/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/YQlsxIcXASk 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int maxConsecutiveAnswers(string answerKey, int k) { 11 | 12 | int ans=0,T=0,F=0,i=0; 13 | for(int j=0;jk){ 19 | if(answerKey[i]=='T') 20 | T--; 21 | else 22 | F--; 23 | i++; 24 | } 25 | ans=max(ans,T+F); 26 | } 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /Maximum 69 Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | /*int maximum69Number (int num) { 4 | string s=to_string(num); 5 | for(int i=0;i& capacity, vector& rocks, int additionalRocks) { 4 | vectorv; 5 | for(int i=0;i0 and i> https://leetcode.com/problems/maximum-depth-of-binary-tree/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/EVydX_Sn5Ow 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int maxDepth(TreeNode* root) { 11 | if(root == NULL) 12 | return 0; 13 | int left = maxDepth(root->left); 14 | int right = maxDepth(root->right); 15 | return max(left, right) + 1; 16 | } 17 | }; -------------------------------------------------------------------------------- /Maximum Difference Between Node and Ancestor.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int res=0; 4 | int maxAncestorDiff(TreeNode* root) { 5 | int mx = INT_MIN, mn = INT_MAX; 6 | helper(root, mx, mn); 7 | return res; 8 | } 9 | void helper(TreeNode* node, int mx, int mn) { 10 | if (!node) return; 11 | if (mx != INT_MIN) res = max(res, abs(mx - node->val)); 12 | if (mn != INT_MAX) res = max(res, abs(node->val - mn)); 13 | mx = max(mx, node->val); 14 | mn = min(mn, node->val); 15 | helper(node->left, mx, mn); 16 | helper(node->right, mx, mn); 17 | } 18 | }; -------------------------------------------------------------------------------- /Maximum Ice Cream Bars.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxIceCream(vector& A, int coins) { 4 | sort(A.begin(), A.end()); 5 | for (int i = 0; i < A.size(); ++i) 6 | if ((coins -= A[i]) < 0) 7 | return i; 8 | return A.size(); 9 | } 10 | }; -------------------------------------------------------------------------------- /Maximum Number of Coins You Can Get.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Maximum Number of Coins You Can Get" Problem ==>> https://leetcode.com/problems/maximum-number-of-coins-you-can-get/description/?envType=daily-question&envId=2023-11-24 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/8OoBNy6gw2U 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int maxCoins(vector& piles) { 11 | 12 | sort(piles.begin(), piles.end()); 13 | 14 | int ans = 0, n = piles.size(); 15 | for (int i = n / 3; i < n; i+=2) 16 | ans += piles[i]; 17 | 18 | return ans; 19 | } 20 | }; -------------------------------------------------------------------------------- /Maximum Number of Vowels in a Substring of Given Length.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Maximum Number of Vowels in a Substring of Given Length " Problem ==>> https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/w-wBwJSDCCY 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int maxVowels(string s, int k) { 11 | int count=0,ctemp=0; 12 | for(int i=0;i=0) 16 | if(s[i-k]=='a' || s[i-k]=='e' || s[i-k]=='i' || s[i-k]=='o' || s[i-k]=='u') 17 | ctemp--; 18 | if(ctemp>count) 19 | count=ctemp; 20 | } 21 | return count; 22 | } 23 | }; -------------------------------------------------------------------------------- /Maximum Performance of a Team.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxPerformance(int n, vector& speed, vector& efficiency, int k) { 4 | int MOD = 1e9 + 7; 5 | vector> candidates(n); 6 | for (int i = 0; i < n; i++) candidates[i] = { efficiency[i], speed[i] }; 7 | sort(candidates.rbegin(), candidates.rend()); 8 | long speedSum = 0, ans = 0; 9 | priority_queue , greater> pq; 10 | for (auto& [e, s] : candidates) { 11 | pq.push(s); 12 | speedSum += s; 13 | if (pq.size() > k) { 14 | speedSum -= pq.top(); 15 | pq.pop(); 16 | } 17 | ans = max(ans, speedSum * e); 18 | } 19 | return ans % MOD; 20 | } 21 | }; -------------------------------------------------------------------------------- /Maximum Profit in Job Scheduling.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int jobScheduling(vector& startTime, vector& endTime, vector& profit) { 4 | int n = startTime.size(); 5 | int dp[n]; 6 | vector>> y(n); 7 | for(int i = 0; i < n; i++){ 8 | y[i].first = endTime[i]; 9 | y[i].second.first = startTime[i]; 10 | y[i].second.second = profit[i]; 11 | } 12 | sort(y.begin(), y.end()); 13 | for (int i = 0; i < n; i++) { 14 | if (i==0){ 15 | dp[i] = y[i].second.second; 16 | continue; 17 | } 18 | int f = 0; 19 | for (int j = i - 1; j >= 0; j--){ 20 | if (y[j].first <= y[i].second.first){ 21 | f = dp[j]; 22 | break; 23 | } 24 | } 25 | dp[i] = max(dp[i-1],f+y[i].second.second); 26 | } 27 | return dp[n - 1]; 28 | } 29 | }; -------------------------------------------------------------------------------- /Maximum Score from Performing Multiplication Operations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rec(int idx,int st,int end,vector& nums,vector& multi,vector> &dp){ 4 | if(idx==multi.size()) return 0; 5 | if(dp[idx][st]!=INT_MIN) return dp[idx][st]; 6 | int ans=INT_MIN; 7 | ans= max(multi[idx]*nums[st] + rec(idx+1,st+1,end,nums,multi,dp), 8 | multi[idx]*nums[end] + rec(idx+1,st,end-1,nums,multi,dp)); 9 | return dp[idx][st]= ans; 10 | } 11 | int maximumScore(vector& nums, vector& multi) { 12 | vector> dp(multi.size(),vector(multi.size(),INT_MIN)); 13 | return rec(0,0,nums.size()-1,nums,multi,dp); 14 | } 15 | }; -------------------------------------------------------------------------------- /Maximum Score of a Good Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumScore(vector& nums, int k) { 4 | int mn = nums[k], i = k, j = k, res = nums[k]; 5 | do { 6 | if (i > 0 && j < nums.size() - 1) { 7 | if (nums[i - 1] >= nums[j + 1]) 8 | --i; 9 | else 10 | ++j; 11 | } 12 | else if (i == 0 && j < nums.size() - 1) 13 | ++j; 14 | else if (j == nums.size() - 1 && i > 0) 15 | --i; 16 | mn = min({mn, nums[i], nums[j]}); 17 | res = max(res, mn * (j - i + 1)); 18 | } 19 | while (i > 0 || j < nums.size() - 1); 20 | return res; 21 | } 22 | }; -------------------------------------------------------------------------------- /Maximum Subsequence Score.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Maximum Subsequence Score " Problem ==>> https://leetcode.com/problems/maximum-subsequence-score/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/wOiDbypgER8 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | long long maxScore(vector& nums1, vector& nums2, int k) { 11 | 12 | vector> vec; 13 | for(int i=0;i,greater> pq; 19 | for(int i=0;i& A) { 4 | int total_sum=0,curr_sum1=0,curr_sum2=0,mxsum_subary=INT_MIN,minsum_subary=INT_MAX; 5 | for(auto i:A) 6 | { 7 | total_sum+=i; curr_sum1+=i; curr_sum2+=i; 8 | mxsum_subary=max(mxsum_subary,curr_sum1); 9 | if(curr_sum1<0) curr_sum1=0; 10 | minsum_subary=min(curr_sum2,minsum_subary); 11 | if(curr_sum2>0) curr_sum2=0; 12 | } 13 | return (total_sum==minsum_subary)?mxsum_subary:max(mxsum_subary,total_sum-minsum_subary); 14 | } 15 | }; -------------------------------------------------------------------------------- /Maximum Twin Sum of a Linked List.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Maximum Twin Sum of a Linked List " Problem ==>> https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/3LvaB9Z7gN4 5 | 6 | */ 7 | 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | int pairSum(ListNode* head) { 21 | vectorlist; 22 | while(head!=NULL){ 23 | list.push_back(head->val); 24 | head=head->next; 25 | } 26 | int n=list.size(); 27 | int mxSum=0; 28 | for(int i=0;i> https://leetcode.com/problems/maximum-value-of-k-coins-from-piles/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/zOG-NwqPtB0 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int solve(int i,vector>&p, int k,vector> &dp){ 11 | 12 | if(i>=p.size() || k<=0) 13 | return 0; 14 | if(dp[i][k]!=-1) 15 | return dp[i][k]; 16 | int fur = solve(i+1,p,k,dp); 17 | int cur=0; 18 | for(int idx=0;idx>& p, int k) { 26 | 27 | vector> dp(p.size(), vector(k+1,-1)); 28 | return solve(0,p,k,dp); 29 | } 30 | }; -------------------------------------------------------------------------------- /Merge Strings Alternately.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Merge Strings Alternately " Problem ==>> https://leetcode.com/problems/merge-strings-alternately/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/EkJeBKfsJMo 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | string mergeAlternately(string word1, string word2) { 11 | 12 | string ans = ""; 13 | int p1 = 0, p2 = 0; 14 | int n = word1.length(), m = word2.length(); 15 | int i = 0; 16 | while(p1 != n && p2 != m) { 17 | if (i%2==1) { 18 | ans += word2[p2++]; 19 | } else { 20 | ans += word1[p1++]; 21 | } 22 | i++; 23 | } 24 | if (p1 != n) { 25 | ans += word1.substr(p1, n); 26 | } 27 | if (p2 != m) { 28 | ans += word2.substr(p2, m); 29 | } 30 | return ans; 31 | } 32 | }; -------------------------------------------------------------------------------- /Minimize Deviation in Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Minimize Deviation in Array" Problem ==>> https://leetcode.com/problems/minimize-deviation-in-array/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/CP7M1JrBoc8 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int minimumDeviation(vector& nums) { 11 | 12 | priority_queue pq; 13 | int m = INT_MAX; 14 | for(int i=0;i> https://leetcode.com/problems/minimize-maximum-of-array/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/xDN7LSSmvDU 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int minimizeArrayValue(vector& nums) { 11 | 12 | long long mini = nums[0]; 13 | long long sum = nums[0]; 14 | for (int i = 1; i mini){ 17 | int x = sum/(i+1); 18 | if (x >= mini){ 19 | if (sum%(i+1)) 20 | mini = x+1; 21 | else 22 | mini =x; 23 | } 24 | } 25 | } 26 | return mini; 27 | } 28 | }; -------------------------------------------------------------------------------- /Minimum Average Difference.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumAverageDifference(vector& nums) { 4 | long long total=0; 5 | long long sum=0; 6 | long long mini=INT_MAX; 7 | int ans=0; 8 | for(int i=0;ine){ 23 | mini=ne; 24 | ans=i; 25 | } 26 | } 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Minimum Cost For Tickets.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Minimum Cost For Tickets " Problem ==>> https://leetcode.com/problems/minimum-cost-for-tickets/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/A-N1SXEOXr4 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | 11 | int mincostTickets(vector& days, vector& costs){ 12 | 13 | int n=days.size(); 14 | vectordp(n+31,0); 15 | for(int i=n-1;i>=0;i--){ 16 | int nextDay=0; 17 | nextDay=lower_bound(days.begin(),days.end(),days[i]+1)-days.begin(); 18 | int op1= costs[0]+ dp[nextDay]; 19 | nextDay= lower_bound(days.begin() , days.end() , days[i]+7)-days.begin(); 20 | int op2= costs[1]+ dp[nextDay]; 21 | nextDay= lower_bound(days.begin() , days.end() , days[i]+30)-days.begin(); 22 | int op3= costs[2]+ dp[nextDay]; 23 | dp[i]=min(op1 , min( op2 , op3)); 24 | } 25 | return dp[0]; 26 | } 27 | }; -------------------------------------------------------------------------------- /Minimum Deletions to Make Character Frequencies Unique.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Minimum Deletions to Make Character Frequencies Unique " Problem ==>> https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/description/?envType=daily-question&envId=2023-09-12 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/L2-9goh3GwU 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int minDeletions(string s) { 11 | 12 | unordered_map count; 13 | 14 | for(char c : s) 15 | count[c]++; 16 | 17 | unordered_set freqcount; 18 | 19 | int ans = 0; 20 | 21 | for(auto& k : count) 22 | { 23 | int freq = k.second; 24 | while(freq>0 && freqcount.find(freq) != freqcount.end()) 25 | { 26 | freq--; 27 | ans++; 28 | } 29 | freqcount.insert(freq); 30 | } 31 | 32 | return ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /Minimum Depth of Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Minimum Depth of Binary Tree " Problem ==>> https://leetcode.com/problems/minimum-depth-of-binary-tree/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/BNU_3wZ29Q8 5 | 6 | */ 7 | 8 | 9 | /** 10 | * Definition for a binary tree node. 11 | * struct TreeNode { 12 | * int val; 13 | * TreeNode *left; 14 | * TreeNode *right; 15 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 17 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 18 | * }; 19 | */ 20 | class Solution { 21 | public: 22 | int minDepth(TreeNode* root) { 23 | 24 | if(root==NULL){ 25 | return 0; 26 | } 27 | 28 | int leftt=minDepth(root->left); 29 | 30 | int rightt=minDepth(root->right); 31 | 32 | if(min(leftt,rightt)!=0){ 33 | return min(leftt,rightt)+1; 34 | } 35 | else{ 36 | return max(leftt,rightt)+1; 37 | } 38 | } 39 | }; -------------------------------------------------------------------------------- /Minimum Difficulty of a Job Schedule.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int n , maxVal = 1e7; 4 | int solve(vector& jobs, int d , int index , vector> &dp){ 5 | if(n==index && d==0) 6 | return 0; 7 | if(n==index || d==0 || n-index& jobs, int d) { 20 | n = jobs.size(); 21 | if(n> dp(n,vector(d+1,-1)); 24 | return solve(jobs , d , 0 , dp); 25 | } 26 | }; -------------------------------------------------------------------------------- /Minimum Distance Between BST Nodes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Minimum Distance Between BST Nodes" Problem ==>> https://leetcode.com/problems/minimum-distance-between-bst-nodes/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/IVJorOUIJTU 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector ans; 11 | 12 | void inorder(TreeNode* root){ 13 | 14 | if(root->left!=NULL){ 15 | inorder(root->left); 16 | } 17 | ans.push_back(root->val); 18 | if(root->right!=NULL){ 19 | inorder(root->right); 20 | } 21 | return; 22 | } 23 | 24 | int minDiffInBST(TreeNode* root) { 25 | 26 | inorder(root); 27 | int k=INT_MAX; 28 | for(int i=1;i>& A) { 5 | int sum =0; 6 | for (int i = A.size()-2; i>=0; --i){ 7 | for (int j = 0; j < A[0].size(); ++j){ 8 | if (j>0 && j A[0][i]) 19 | sum = A[0][i]; 20 | return sum; 21 | } 22 | }; -------------------------------------------------------------------------------- /Minimum Flips to Make a OR b Equal to c.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Minimum Flips to Make a OR b Equal to c " Problem ==>> https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/upgnDo9eA-k 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int minFlips(int a, int b, int c) { 11 | int flips = 0; 12 | while (a > 0 || b > 0 || c > 0) { 13 | int bitA = a & 1; 14 | int bitB = b & 1; 15 | int bitC = c & 1; 16 | if ((bitA | bitB) != bitC) { 17 | if (bitC == 1) { 18 | flips++; 19 | } else { 20 | flips += (bitA + bitB); 21 | } 22 | } 23 | a >>= 1; 24 | b >>= 1; 25 | c >>= 1; 26 | } 27 | return flips; 28 | } 29 | }; -------------------------------------------------------------------------------- /Minimum Insertion Steps to Make a String Palindrome.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Minimum Insertion Steps to Make a String Palindrome " Problem ==>> https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/PF8cW7k8BT8 5 | 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int minInsertions(string s) { 12 | 13 | int n=s.length(); 14 | string rev=s; 15 | reverse(rev.begin(),rev.end()); 16 | int t[n+1][n+1]; 17 | for(int i=0;i> https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/ZuB6rZqC11M 5 | 6 | */ 7 | 8 | bool comp(vector &a, vector &b){ 9 | return a[1] < b[1]; 10 | } 11 | class Solution { 12 | public: 13 | int findMinArrowShots(vector>& points) { 14 | 15 | if(points.size() == 0) 16 | return 0; 17 | sort(points.begin(), points.end(), comp); 18 | int arrows = 1; 19 | int last = points[0][1]; 20 | for(int i = 1; i < points.size(); i++){ 21 | if(points[i][0] > last){ 22 | arrows++; 23 | last = points[i][1]; 24 | } 25 | } 26 | return arrows; 27 | } 28 | }; -------------------------------------------------------------------------------- /Minimum Number of Operations to Make Array Continuous.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector& nums) { 4 | 5 | int n=nums.size(); 6 | 7 | int ans=n-1; 8 | 9 | sort(nums.begin(), nums.end()); 10 | 11 | auto it=unique(nums.begin(), nums.end()); 12 | 13 | nums.erase(it, nums.end()); 14 | 15 | int m=nums.size(); 16 | 17 | for(int i=0; i>& stations) { 4 | int i=0, ans=0; 5 | priority_queue pq; 6 | while(startFuel < target) { 7 | while(i < stations.size() && stations[i][0] <= startFuel) { 8 | pq.push(stations[i][1]); 9 | i++; 10 | } 11 | if(pq.size()==0) return -1; 12 | startFuel += pq.top(); pq.pop(); 13 | ans++; 14 | } 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /Minimum Operations to Reduce X to Zero.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector& nums, int targetSum) { 4 | int totalSum = accumulate(nums.begin(), nums.end(), 0); 5 | int target = totalSum - targetSum; 6 | if (target < 0) 7 | return -1; 8 | if (target == 0) 9 | return nums.size(); 10 | int n = nums.size(); 11 | int minOperations = INT_MAX; 12 | int currentSum = 0; 13 | int leftIndex = 0, rightIndex = 0; 14 | while (rightIndex < n) { 15 | currentSum += nums[rightIndex]; 16 | rightIndex++; 17 | while (currentSum > target && leftIndex < n) { 18 | currentSum -= nums[leftIndex]; 19 | leftIndex++; 20 | } 21 | if (currentSum == target) 22 | minOperations = min(minOperations, n - (rightIndex - leftIndex)); 23 | } 24 | return (minOperations == INT_MAX) ? -1 : minOperations; 25 | } 26 | }; -------------------------------------------------------------------------------- /Minimum Path Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Minimum Path Sum " Problem ==>> https://leetcode.com/problems/minimum-path-sum/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/S99RAK_R9rQ 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int minPathSum(vector>& grid) { 11 | 12 | int m=grid.size(), n=grid[0].size(); 13 | vector> dp(m, vector(n, 0)); 14 | dp[0][0]=grid[0][0]; 15 | for (int i=1; i> https://leetcode.com/problems/minimum-penalty-for-a-shop/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/L8FxWqmgl64 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int bestClosingTime(string customers) { 11 | 12 | int n=customers.size(); 13 | 14 | int penalty=0; 15 | 16 | for(int i=0;i=0;i--) 25 | { 26 | if(customers[i]=='Y') 27 | penalty++; 28 | else 29 | penalty--; 30 | if(penalty<=mini){ 31 | mini=penalty; 32 | ans=i; 33 | } 34 | } 35 | return ans; 36 | } 37 | }; -------------------------------------------------------------------------------- /Minimum Rounds to Complete All Tasks.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumRounds(vector& A) { 4 | unordered_map count; 5 | int res = 0, freq1; 6 | for (int a: A) 7 | ++count[a]; 8 | for (auto& it: count) { 9 | if (it.second == 1) return -1; 10 | res += (it.second + 2) / 3; 11 | } 12 | return res; 13 | } 14 | }; -------------------------------------------------------------------------------- /Minimum Size Subarray Sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Minimum Size Subarray Sum " Problem ==>> https://leetcode.com/problems/minimum-size-subarray-sum/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/jA7IxWg8uTA 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int minSubArrayLen(int target, vector& nums) { 11 | 12 | int n=nums.size(); 13 | int wsum=0, l=0, r; 14 | int ans=INT_MAX; 15 | for(r=0; r=target){ 18 | ans=min(ans, r-l+1); 19 | wsum-=nums[l]; 20 | l++; 21 | } 22 | } 23 | return ans==INT_MAX? 0: ans; 24 | } 25 | }; -------------------------------------------------------------------------------- /Minimum Speed to Arrive on Time.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Minimum Speed to Arrive on Time " Problem ==>> https://leetcode.com/problems/minimum-speed-to-arrive-on-time/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/FvNtVJqEy50 5 | 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | bool isPossible(vector& arr, double hr, int mid){ 12 | 13 | double time=0; 14 | 15 | for(int i=0;i& dist, double hour) { 27 | 28 | int s=1; 29 | int e=1e7; 30 | int ans=-1; 31 | 32 | while(s<=e){ 33 | int mid=s+(e-s)/2; 34 | 35 | if(isPossible(dist,hour,mid)){ 36 | ans=mid; 37 | e=mid-1; 38 | } 39 | else s=mid+1; 40 | } 41 | return ans; 42 | } 43 | }; -------------------------------------------------------------------------------- /Minimum Time to Complete Trips.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Minimum Time to Complete Trips " Problem ==>> https://leetcode.com/problems/minimum-time-to-complete-trips/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/nOfq3MgbFQI 5 | 6 | */ 7 | 8 | typedef long long ll; 9 | class Solution { 10 | 11 | bool check(vector &time, ll mid, ll t){ 12 | ll trips = 0; 13 | for(auto &i:time){ 14 | trips += (mid/i); 15 | if(trips >= t) return true; 16 | } 17 | return false; 18 | } 19 | 20 | public: 21 | long long minimumTime(vector& time, int t) { 22 | 23 | int n = time.size(); 24 | sort(time.begin(), time.end()); 25 | ll l = (ll)time[0]; 26 | ll r = (ll)time[n-1]*(ll)t; 27 | while(l> https://leetcode.com/problems/monotonic-array/?envType=daily-question&envId=2023-09-29 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/w0XVOR4taLY 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector sortArrayByParity(vector& nums) { 11 | 12 | int left=0,right=nums.size()-1; 13 | 14 | while(leftleft && nums[right]%2==1) { 17 | right--; 18 | } 19 | swap(nums[left],nums[right]); 20 | } 21 | left++; 22 | } 23 | 24 | return nums; 25 | } 26 | }; -------------------------------------------------------------------------------- /Most Stones Removed with Same Row or Column.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int n; 4 | vector vis; 5 | void dfs(int idx,vector> &stones){ 6 | vis[idx] = 1; 7 | for(int i=0;i>& stones) { 16 | n = stones.size(); 17 | vis.resize(n,0); 18 | int val = 0; 19 | for(int i=0;i mp; 4 | MyCalendarThree() { 5 | 6 | } 7 | 8 | int book(int start, int end) { 9 | mp[start]++; 10 | mp[end]--; 11 | int sum=0; 12 | int curr_sum=0; 13 | for(auto it : mp){ 14 | curr_sum+= it.second; 15 | sum=max(sum,curr_sum); 16 | } 17 | return sum; 18 | } 19 | }; -------------------------------------------------------------------------------- /My Calendar.cpp: -------------------------------------------------------------------------------- 1 | class MyCalendar { 2 | public: 3 | MyCalendar() { 4 | } 5 | map m; 6 | bool book(int start, int end) { 7 | m[start]++; 8 | m[end]--; 9 | int s=0; 10 | for(auto it:m){ 11 | s+=it.second; 12 | if(s>1){ 13 | m[start]--; 14 | m[end]++; 15 | return false; 16 | } 17 | } 18 | return true; 19 | } 20 | }; -------------------------------------------------------------------------------- /N-ary Tree Level Order Traversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> levelOrder(Node* root) { 4 | if (root == NULL) 5 | return {}; // Handle Corner Case 6 | vector> res; 7 | queue q; 8 | q.push(root); 9 | while (!q.empty()) 10 | { 11 | int size = q.size(); 12 | vector currlevel; 13 | for(int i = 0 ; i < size ; i++) 14 | { 15 | Node* tmp=q.front() ; 16 | q.pop() ; 17 | currlevel.push_back(tmp->val) ; 18 | for (auto n : tmp -> children) 19 | q.push(n); 20 | } 21 | res.push_back(currlevel) ; 22 | } 23 | return res ; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /N-th Tribonacci Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "N-th Tribonacci Number" Problem ==>> https://leetcode.com/problems/n-th-tribonacci-number/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/JA9sXqmDKmw 5 | 6 | */ 7 | class Solution { 8 | public: 9 | int tribonacci(int n) { 10 | int t1=0; 11 | int t2=1; 12 | int t3=1; 13 | int ans=0; 14 | if(n==0){ 15 | return t1; 16 | } 17 | else if(n==1 || n==2){ 18 | return t2; 19 | } 20 | int i=3; 21 | while(i<=n){ 22 | ans=t1+t2+t3; 23 | t1=t2; 24 | t2=t3; 25 | t3=ans; 26 | i++; 27 | } 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /Naming a Company.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Naming a Company" Problem ==>> https://leetcode.com/problems/naming-a-company/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/WPOkNEIkVPs 5 | 6 | */ 7 | class Solution { 8 | public: 9 | long long distinctNames(vector& ideas) { 10 | unordered_set t(ideas.begin(), ideas.end()); 11 | unordered_map> m; 12 | for (auto& str : t){ 13 | string s = str; 14 | char prev = s[0]; 15 | for (char c = 'a'; c <= 'z'; ++c){ 16 | s[0] = c; 17 | if (t.find(s) == t.end()) 18 | ++m[c][prev]; 19 | } 20 | } 21 | long long ans = 0; 22 | for (auto& str : t){ 23 | string s = str; 24 | char prev = s[0]; 25 | for (char c = 'a'; c <= 'z'; ++c){ 26 | s[0] = c; 27 | if (t.find(s) == t.end()) 28 | ans += m[prev][c]; 29 | } 30 | } 31 | return ans; 32 | } 33 | }; -------------------------------------------------------------------------------- /New 21 Game.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " New 21 Game " Problem ==>> https://leetcode.com/problems/new-21-game/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/d0XRA7WXFx0 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | double new21Game(int n, int k, int maxPts) { 11 | if (k == 0 || n >= k + maxPts) { 12 | return 1.0; 13 | } 14 | vector dp(n + 1); 15 | dp[0] = 1.0; 16 | double sum = 1.0, res = 0.0; 17 | for (int i = 1; i <= n; i++) { 18 | dp[i] = sum / maxPts; 19 | if (i < k){ 20 | sum += dp[i]; 21 | } 22 | else{ 23 | res += dp[i]; 24 | } 25 | if (i >= maxPts) { 26 | sum -= dp[i - maxPts]; 27 | } 28 | } 29 | return res; 30 | } 31 | }; -------------------------------------------------------------------------------- /Non-decreasing Subsequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> findSubsequences(vector& nums) { 4 | vector> res; 5 | vector seq; 6 | dfs(res, seq, nums, 0); 7 | return res; 8 | } 9 | 10 | void dfs(vector>& res, vector& seq, vector& nums, int pos) { 11 | if(seq.size() > 1) res.push_back(seq); 12 | unordered_set hash; 13 | for(int i = pos; i < nums.size(); ++i) { 14 | if((seq.empty() || nums[i] >= seq.back()) && hash.find(nums[i]) == hash.end()) { 15 | seq.push_back(nums[i]); 16 | dfs(res, seq, nums, i + 1); 17 | seq.pop_back(); 18 | hash.insert(nums[i]); 19 | } 20 | } 21 | } 22 | }; -------------------------------------------------------------------------------- /Non-overlapping Intervals.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Non-overlapping Intervals " Problem ==>> https://leetcode.com/problems/non-overlapping-intervals/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/iE9bxP9dawg 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int eraseOverlapIntervals(vector>& intervals) { 11 | 12 | sort(intervals.begin(), intervals.end()); 13 | vector prev=intervals[0]; 14 | int num=-1; 15 | for(vector& A: intervals){ 16 | if (A[0]prev[1]) 21 | num++; 22 | else 23 | prev=A; 24 | } 25 | return num; 26 | } 27 | }; -------------------------------------------------------------------------------- /Number of 1 Bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Number of 1 Bits" Problem ==>> https://leetcode.com/problems/number-of-1-bits/description/?envType=daily-question&envId=2023-11-29 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/ZUU5EmWQVIE 5 | 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int hammingWeight(uint32_t n) { 12 | 13 | int count = 0; 14 | 15 | while (n) { 16 | 17 | count += n & 1; 18 | n >>= 1; 19 | } 20 | return count; 21 | } 22 | }; -------------------------------------------------------------------------------- /Number of Dice Rolls With Target Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int solve(int n, int k ,int t,vector>&dp){ 5 | if(n == 0 && t == 0 ) 6 | return 1; 7 | 8 | if(n == 0) 9 | return 0; 10 | 11 | int take = 0; 12 | 13 | if(dp[n][t] != -1) 14 | return dp[n][t]; 15 | 16 | for(int i = 1;i<=k;i++) { 17 | if(t >= i) { 18 | take += solve(n-1,k,t-i , dp); 19 | take %= 1000000007; 20 | } 21 | } 22 | return dp[n][t] = take; 23 | } 24 | 25 | int numRollsToTarget(int n, int k, int target) { 26 | vector> dp(n+1 , vector (target+1,-1)); 27 | return solve(n , k ,target , dp); 28 | } 29 | 30 | }; -------------------------------------------------------------------------------- /Number of Good Pairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Remove Colored Pieces if Both Neighbors are the Same Color" Problem ==>> https://leetcode.com/problems/number-of-good-pairs/?envType=daily-question&envId=2023-10-03 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/wPXUmwWKaLo 5 | 6 | */ 7 | 8 | class Solution{ 9 | public: 10 | 11 | int numIdenticalPairs(vector &nums){ 12 | 13 | int n = nums.size(), cnt = 0; 14 | 15 | unordered_map mp; 16 | 17 | for (auto & it: nums) 18 | mp[it]++; 19 | 20 | for (auto & pair: mp) { 21 | n = pair.second; 22 | cnt += ((n)*(n-1))/2; 23 | } 24 | return cnt; 25 | } 26 | }; -------------------------------------------------------------------------------- /Number of Provinces.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Number of Provinces " Problem ==>> https://leetcode.com/problems/number-of-provinces/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/xaxdyPZaQGI 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | void dfs(vector>& isConnected, int i, vector& visited,int n){ 11 | if(visited[i]==1) 12 | return; 13 | visited[i] = 1; 14 | for(int j=0;j>& isConnected) { 21 | 22 | int n = isConnected.size(); 23 | vector visited(n,0); 24 | int ans=0; 25 | for(int i=0;i> https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/sjS_TzEgxZA 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int numSubseq(vector& nums, int target) { 11 | 12 | sort(nums.begin(),nums.end()); 13 | int ans=0; 14 | int mod=1e9+7; 15 | vectorpow(nums.size(),1); 16 | int l=0,r=nums.size()-1; 17 | for(int i=1;itarget) 24 | r--; 25 | else 26 | { 27 | ans=(ans+pow[r-l])%mod; 28 | l++; 29 | 30 | } 31 | } 32 | return ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /Number of Zero-Filled Subarrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Number of Zero-Filled Subarrays " Problem ==>> https://leetcode.com/problems/number-of-zero-filled-subarrays/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/22CfEGAetpQ 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | long long zeroFilledSubarray(vector& n) { 11 | 12 | long long int ans = 0, cnt = 0; 13 | for(int x: n){ 14 | if(x) 15 | cnt=0; 16 | else 17 | cnt++; 18 | ans+=cnt; 19 | } 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /Numbers With Same Consecutive Differences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | //To find digits in the current number 4 | int counts(int x) { 5 | int len = 0; 6 | while(x) 7 | { 8 | len++; 9 | x = x/10; 10 | } 11 | return len; 12 | } 13 | void findnum(int x, int n ,int k, vector &res){ 14 | if(counts(x) == n) //Base case 15 | { 16 | res.push_back(x); 17 | return; 18 | } 19 | for(int i=0;i<10;i++) { 20 | int last_digit = x % 10; 21 | if(abs(last_digit - i) == k) 22 | { 23 | findnum((x*10 + i), n, k, res); 24 | } 25 | } 26 | } 27 | vector numsSameConsecDiff(int n, int k) { 28 | vector res; 29 | if(n == 1) //Special Case where 0 can be included if given 'N' is 1 30 | { 31 | res.push_back(0); 32 | } 33 | for(int i=1;i<10;i++) { 34 | findnum(i, n, k, res); 35 | } 36 | return res; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Odd Even Linked List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* oddEvenList(ListNode* head) { 4 | ListNode *odd = NULL, *headodd = NULL, *even = NULL, *headeven = NULL; 5 | 6 | if(!head || !head->next || !head->next->next) return head; 7 | 8 | odd = head; headodd = odd; 9 | even = head->next; headeven = even; 10 | 11 | while(even && even->next){ 12 | odd->next = odd->next->next; 13 | even->next = even->next->next; 14 | odd = odd->next; 15 | even = even->next; 16 | } 17 | 18 | odd->next = headeven; 19 | return headodd; 20 | } 21 | }; -------------------------------------------------------------------------------- /Online Stock Span.cpp: -------------------------------------------------------------------------------- 1 | class StockSpanner { 2 | public: 3 | stack> s; 4 | StockSpanner() {} 5 | 6 | int next(int price) { 7 | int span = 1; 8 | while(s.size() && s.top().first <= price) 9 | span += s.top().second, s.pop(); 10 | s.push({price, span}); 11 | return span; 12 | } 13 | }; -------------------------------------------------------------------------------- /Optimal Partition of String.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Optimal Partition of String " Problem ==>> https://leetcode.com/problems/optimal-partition-of-string/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/K9p6PJeT_DE 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int partitionString(string s) { 11 | 12 | int count = 0, right = 0; 13 | int n = s.size(); 14 | int mask = 0; 15 | while(right < n){ 16 | int pos = (s[right] - 'a'); 17 | if(mask & (1 << pos)){ 18 | mask = 0; 19 | count++; 20 | } 21 | mask |= (1 << pos); 22 | right++; 23 | } 24 | if(mask) 25 | count++; 26 | 27 | return count; 28 | } 29 | }; -------------------------------------------------------------------------------- /Orderly Queue.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static string orderlyQueue(string s, int k) { 4 | if (k == 1) { 5 | string ans = s; 6 | s += s; 7 | for (int i = 1; i > generate(int numRows) { 8 | vector> v; 9 | 10 | v.push_back({1}); 11 | 12 | if(numRows == 1) { 13 | return v; 14 | } 15 | 16 | for (int i = 2; i <= numRows; i++) { 17 | 18 | vector curr(i); 19 | 20 | curr[0] = 1; 21 | 22 | curr[i-1] = 1; 23 | 24 | for(int j = 1;j < v.back().size(); j++) { 25 | curr[j] = v.back()[j-1] + v.back()[j]; 26 | } 27 | 28 | v.push_back(curr); 29 | } 30 | return v; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Path Sum II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> res; 4 | vector curr; 5 | void dfs(TreeNode* root, int curr_sum, int target_sum){ 6 | if(root == NULL) 7 | return; 8 | curr.push_back(root -> val); 9 | curr_sum += root -> val; 10 | if(root -> left == NULL && root -> right == NULL){ 11 | if(curr_sum == target_sum){ 12 | res.push_back(curr); 13 | } 14 | } 15 | dfs(root -> left, curr_sum, target_sum); 16 | dfs(root -> right, curr_sum, target_sum); 17 | curr.pop_back(); 18 | } 19 | vector> pathSum(TreeNode* root, int targetSum) { 20 | dfs(root, 0, targetSum); 21 | return res; 22 | } 23 | }; -------------------------------------------------------------------------------- /Path Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasPathSum(TreeNode* root, int targetSum) { 4 | int sum = 0; 5 | return pathSum(root, sum, targetSum); 6 | } 7 | bool pathSum(TreeNode* node, int sum, int targetSum){ 8 | if(node == NULL) return false; 9 | sum += node->val; 10 | if(node->left == NULL && node->right ==NULL && sum == targetSum) 11 | return true; 12 | if(pathSum(node->left, sum, targetSum) || pathSum(node->right, sum, targetSum)) 13 | return true; 14 | return false; 15 | 16 | } 17 | }; -------------------------------------------------------------------------------- /Peak Index in a Mountain Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Peak Index in a Mountain Array " Problem ==>> https://leetcode.com/problems/peak-index-in-a-mountain-array/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/544u8B_PA34 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int peakIndexInMountainArray(vector& arr) { 11 | 12 | int lo=1,hi=arr.size()-2; 13 | if(arr.size()>=3) 14 | { 15 | while(loarr[mid+1]) 19 | return mid; 20 | else if(arr[mid-1] dp(n+1,INT_MAX); 5 | dp[0]=0; 6 | int count = 1; 7 | while(count*count <= n) { 8 | int sq = count*count; 9 | for(int i = sq; i < n+1; i++) { 10 | dp[i] = min(dp[i-sq] + 1,dp[i]); 11 | } 12 | count++; 13 | } 14 | return dp[n]; 15 | } 16 | }; -------------------------------------------------------------------------------- /Poor Pigs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 4 | return ceil(log(buckets) / log(minutesToTest / minutesToDie + 1)); 5 | } 6 | }; -------------------------------------------------------------------------------- /Pow(x, n).cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Pow(x, n) " Problem ==>> https://leetcode.com/problems/powx-n/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/lPQGK2IvNuI 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | double myPow(double x, long long int n) { 11 | 12 | double ans=1; 13 | 14 | if(n==0 || x==1){ 15 | return 1; 16 | } 17 | else if(n<0){ 18 | x=1/x; 19 | n=-n; 20 | } 21 | ans*=x; 22 | n--; 23 | int t=0; 24 | while(n){ 25 | t++; 26 | if(t0){ 32 | ans=ans*x; 33 | n--; 34 | } 35 | } 36 | return ans; 37 | } 38 | }; -------------------------------------------------------------------------------- /Power of Four.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfFour(int n) { 4 | int bits = 0; 5 | int idx = -1; 6 | int i = 0; 7 | while(n) { 8 | if((n & 1) == 1) { 9 | if(bits == 1) return false; 10 | bits++; 11 | idx = i; 12 | } 13 | i++; 14 | n >>= 1; 15 | } 16 | if(idx == -1) return false; 17 | 18 | return (idx % 2) == 0; 19 | } 20 | }; -------------------------------------------------------------------------------- /Power of Three.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfThree(int n) { 4 | if(n<=0){ 5 | return false; 6 | } 7 | double f=(double)log10(n)/log10(3); 8 | return ceil(f)==floor(f); 9 | } 10 | }; -------------------------------------------------------------------------------- /Predict the Winner.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Predict the Winner " Problem ==>> https://leetcode.com/problems/predict-the-winner/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/_qMuhtc5WLs 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int solve(vector& nums,int i,int j, bool choose){ 11 | 12 | if(i>j) 13 | return 0; 14 | 15 | int ans=0; 16 | 17 | if(choose){ 18 | ans=max(nums[i]+solve(nums,i+1,j,false),nums[j]+solve(nums,i,j-1,false)); 19 | } 20 | else{ 21 | ans=min(-nums[i]+solve(nums,i+1,j,true),-nums[j]+solve(nums,i,j-1,true)); 22 | } 23 | return ans; 24 | } 25 | 26 | bool PredictTheWinner(vector& nums) { 27 | 28 | bool choose=true; 29 | 30 | int n=nums.size(); 31 | 32 | int score=solve(nums,0,n-1,choose); 33 | 34 | if(score>=0) 35 | return true; 36 | return false; 37 | } 38 | }; -------------------------------------------------------------------------------- /Pseudo-Palindromic Paths in a Binary Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ans = 0; 4 | void trav(TreeNode* root, vector& cur){ 5 | if(!root) return; 6 | cur[root->val]++; 7 | trav(root->left, cur); 8 | trav(root->right, cur); 9 | if(root->left == nullptr && root->right == nullptr){ 10 | int odd=0; 11 | for(int i=1;i<=9;i++){ 12 | if(cur[i]%2!=0) 13 | odd++; 14 | } 15 | if(odd<=1) ans++; 16 | } 17 | cur[root->val]--; 18 | } 19 | int pseudoPalindromicPaths (TreeNode* root) { 20 | vector cur(10, 0); 21 | trav(root, cur); 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /Put Marbles in Bags.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Put Marbles in Bags " Problem ==>> https://leetcode.com/problems/put-marbles-in-bags/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/czT67Xo_Sis 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | long long putMarbles(vector& weights, int k) { 11 | 12 | priority_queue pq; 13 | priority_queue , greater > pq2; 14 | 15 | int n = weights.size(); 16 | 17 | long long ans = 0; 18 | 19 | for(int i=0;i> https://leetcode.com/problems/range-sum-of-bst/ 4 | 5 | Link to the complete Explaination Video ==>> https://youtu.be/rQuiUXvR7e0 6 | 7 | */ 8 | 9 | class Solution { 10 | public: 11 | int rangeSumBST(TreeNode* root, int L, int R) { 12 | if (root == nullptr) 13 | return 0; 14 | return (root->val >= L && root->val <= R ? root->val : 0) + 15 | rangeSumBST(root->left, L, R) + rangeSumBST(root->right, L, R); 16 | } 17 | }; -------------------------------------------------------------------------------- /Ransom Note.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canConstruct(string ransomNote, string magazine) { 4 | unordered_map m; 5 | for(auto it: magazine){ 6 | m[it]++; 7 | } 8 | for(auto it: ransomNote){ 9 | if(!m[it]--){ 10 | return false; 11 | } 12 | } 13 | return true; 14 | } 15 | }; -------------------------------------------------------------------------------- /Ransom Notes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canConstruct(string ransomNote, string magazine) { 4 | unordered_map m; 5 | for(auto it: magazine){ 6 | m[it]++; 7 | } 8 | for(auto it: ransomNote){ 9 | if(!m[it]--){ 10 | return false; 11 | } 12 | } 13 | return true; 14 | } 15 | }; -------------------------------------------------------------------------------- /Rectangle Area.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) 5 | { 6 | // sum of areas of two rectangles minus the area of their intersection 7 | return (ax2 - ax1) * (ay2 - ay1) + 8 | (bx2 - bx1) * (by2 - by1) - 9 | max(min(ax2,bx2) - max(ax1,bx1),0) * max(min(ay2,by2) - max(ay1,by1),0); 10 | } 11 | }; -------------------------------------------------------------------------------- /Reduce Array Size to The Half.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSetSize(vector& arr) { 4 | int ans=0; 5 | int n1=0; 6 | vector v; 7 | int n= arr.size(); 8 | unordered_map um; 9 | for(int i=0; i< n; i++) 10 | { 11 | um[arr[i]]++; 12 | } 13 | 14 | for (auto x : um) 15 | { 16 | v.push_back(x.second); 17 | 18 | } 19 | if(v.size()==1)return 1; 20 | sort(v.begin(), v.end()); 21 | for(int i=v.size()-1; i>=0; i--) 22 | { 23 | if(ans>=n/2){ 24 | return n1; 25 | } 26 | n1++; 27 | ans= ans+ v[i]; 28 | 29 | } 30 | return 0; 31 | } 32 | }; -------------------------------------------------------------------------------- /Reducing Dishes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Reducing Dishes " Problem ==>> https://leetcode.com/problems/reducing-dishes/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/A-N1SXEOXr4 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int helper(vector< int> &nums, int i, int j, vector> &dp){ 11 | 12 | if(i==nums.size()){ 13 | return 0; 14 | } 15 | if(dp[i][j]!=-1) 16 | return dp[i][j]; 17 | int pick = j*nums[i] + helper(nums, i+1, j+1, dp); 18 | int notpick = helper(nums,i+1,j,dp); 19 | return dp[i][j] = max(pick,notpick); 20 | } 21 | 22 | int maxSatisfaction(vector& sat) { 23 | 24 | int n = sat.size(); 25 | sort(sat.begin(),sat.end()); 26 | vector>dp(n+1, vector(n+1, -1)); 27 | return helper(sat,0,1,dp); 28 | } 29 | }; -------------------------------------------------------------------------------- /Remove All Adjacent Duplicates In String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeDuplicates(string s) { 4 | 5 | string ans; 6 | 7 | for(int i = 0 ; i < s.size() ; i++) 8 | { 9 | if(ans.size() && ans.back() == s[i]) 10 | ans.pop_back(); 11 | else 12 | ans.push_back(s[i]); 13 | } 14 | 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /Remove Colored Pieces if Both Neighbors are the Same Color.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Remove Colored Pieces if Both Neighbors are the Same Color" Problem ==>> https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/jaCf5jv_Z4I 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | bool winnerOfGame(string colors) { 11 | int as = 0, bs = 0; 12 | for(int i = 1; i< colors.size()-1; i++){ 13 | 14 | if(colors[i-1]== 'A' && colors[i] =='A' && colors[i+1] =='A'){ 15 | as++; 16 | } 17 | if(colors[i-1] == 'B' && colors[i] =='B' && colors[i+1]== 'B'){ 18 | bs++; 19 | } 20 | } 21 | return as > bs; 22 | } 23 | }; -------------------------------------------------------------------------------- /Remove Duplicates from Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int index = 1; 5 | int n=nums.size(); 6 | for(int i = 1; i < n; i++) 7 | if(nums[i] != nums[i - 1]) 8 | nums[index++] = nums[i]; 9 | 10 | return index; 11 | } 12 | }; -------------------------------------------------------------------------------- /Remove Nth Node From End of List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* removeNthFromEnd(ListNode* head, int n) { 4 | if(head==NULL) return NULL; 5 | else if(head->next==NULL) return NULL; 6 | ListNode* temp = head; 7 | int size=0; 8 | while(temp!=NULL){ 9 | temp=temp->next; 10 | size++; 11 | } 12 | temp=head; 13 | if(size==n){ 14 | head=head->next; 15 | return head; 16 | } 17 | for(int i=0;inext; 19 | } 20 | if(temp->next->next) 21 | temp->next = temp->next->next; 22 | else if(temp->next) 23 | temp->next=NULL; 24 | 25 | return head; 26 | } 27 | }; -------------------------------------------------------------------------------- /Remove Stones to Minimize the Total.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Remove Stones to Minimize the Total" Problem ==>> https://leetcode.com/problems/remove-stones-to-minimize-the-total/description/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/ysvYRJP0E6o 5 | 6 | */ 7 | class Solution { 8 | public: 9 | int minStoneSum(vector& A, int k) { 10 | 11 | priority_queue pq(A.begin(), A.end()); 12 | int res = accumulate(A.begin(), A.end(), 0); 13 | while (k--) { 14 | int a = pq.top(); 15 | pq.pop(); 16 | pq.push(a - a / 2); 17 | res -= a / 2; 18 | } 19 | return res; 20 | } 21 | }; -------------------------------------------------------------------------------- /Removing Stars From a String.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Removing Stars From a String " Problem ==>> https://leetcode.com/problems/removing-stars-from-a-string/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/JGHBSaGx-Oo 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | string removeStars(string s) { 11 | 12 | int i=0,j=0,n=s.length(); 13 | while(j!=n){ 14 | 15 | if(s[j]=='*') i--; 16 | else s[i++]=s[j]; 17 | j++; 18 | } 19 | return s.substr(0,i); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Reordered Power of 2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool reorderedPowerOf2(int n) { 4 | if(n == 1) return true; 5 | unordered_map map; 6 | string temp = to_string(n); 7 | for(int i = 0; i < temp.size(); i++){ 8 | map[int(temp[i])-48]++; 9 | } 10 | 11 | int digits = temp.size(); 12 | return helper(map, 2, n, digits); 13 | } 14 | 15 | bool helper(unordered_map map, long k, int s, int digits){ 16 | if(k > pow(10, digits) - 1) return false; 17 | if(k == s) return true; 18 | 19 | unordered_map copy = map; 20 | 21 | string temp = to_string(k); 22 | for(int i = 0; i < temp.size(); i++){ 23 | copy[int(temp[i])-48]--; 24 | } 25 | 26 | for(auto &it: copy){ 27 | if(it.second != 0) return helper(map, k*2, s, digits); 28 | } 29 | 30 | return true; 31 | } 32 | }; -------------------------------------------------------------------------------- /Repeated Substring Pattern.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Repeated Substring Pattern " Problem ==>> https://leetcode.com/problems/repeated-substring-pattern/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/zmxw7jW7tQg 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | bool repeatedSubstringPattern(string s) { 11 | 12 | string t = s; 13 | 14 | for(int i=0; i> https://leetcode.com/problems/restore-the-array/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/yUaouOG2K_4 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int numberOfArrays(string s, int k) { 11 | 12 | vector dp(s.size(), -1); 13 | return dfs(s, k, 0, dp); 14 | } 15 | int dfs(const string& s, long k, int i, vector& dp) { 16 | 17 | if (i == s.size()) 18 | return 1; 19 | if (s[i] == '0') 20 | return 0; 21 | if (dp[i] != -1) 22 | return dp[i]; 23 | int ans = 0; 24 | long num = 0; 25 | for (int j = i; j < s.size(); j++) { 26 | num = num * 10 + s[j]-'0'; 27 | if (num > k) 28 | break; 29 | ans += dfs(s, k, j + 1, dp); 30 | ans %= 1000000007; 31 | } 32 | return dp[i] = ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /Reverse Linked List II.cpp: -------------------------------------------------------------------------------- 1 | link to the problem: https://leetcode.com/problems/reverse-linked-list-ii/?envType=daily-question&envId=2023-09-07 2 | 3 | link to the solution: https://www.youtube.com/watch?v=71eUmoZtcHo 4 | 5 | class Solution { 6 | public: 7 | ListNode* reverseBetween(ListNode* head, int left, int right) { 8 | if(!head) 9 | return nullptr; 10 | 11 | ListNode* dummy = new ListNode(0,head); 12 | head = dummy; 13 | ListNode* curr = head->next; 14 | ListNode* prev = dummy; 15 | 16 | for(int i = 1; i < left; i++) { 17 | prev = prev->next; 18 | } 19 | 20 | ListNode* left_prev = prev->next; 21 | 22 | for(int i=0; i< right - left;i++){ 23 | 24 | ListNode* temp = prev->next; 25 | prev->next = left_prev->next; 26 | 27 | left_prev->next = left_prev->next->next; 28 | 29 | prev->next->next = temp; 30 | } 31 | return dummy->next; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Reverse Vowels of a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseVowels(string s) { 4 | queue q; 5 | stack st; 6 | for(int i=0;i0 && i==q.front()){ 19 | s[i]=st.top(); 20 | st.pop(); 21 | q.pop(); 22 | } 23 | if((s[i]=='A' || s[i]=='E' || s[i]=='I' || s[i]=='O' || s[i]=='U') && q.size()>0 && i==q.front()){ 24 | s[i]=st.top(); 25 | st.pop(); 26 | q.pop(); 27 | } 28 | } 29 | return s; 30 | } 31 | }; -------------------------------------------------------------------------------- /Reverse Words in a String III.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseWords(string s) { 4 | for(int end = 0, start = 0; end <= s.size(); end++){ 5 | if(s[end] == ' ' or s[end] == '\0'){ 6 | reverse(s.begin()+start, s.begin()+end); 7 | start = end+1; 8 | } 9 | } 10 | return s; 11 | } 12 | }; -------------------------------------------------------------------------------- /Reverse Words in a String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseWords(string s) { 4 | string ans; 5 | string temp=""; 6 | for(int i=s.size()-1;i>=0;i--){ 7 | if(s[i]==' '){ 8 | reverse(temp.begin(),temp.end()); 9 | if(temp.size()>0 && ans.size()>0){ 10 | ans+=' '; 11 | ans+=temp; 12 | } 13 | if(ans.size()==0 && temp.size()>0){ 14 | ans+=temp; 15 | } 16 | temp=""; 17 | } 18 | else{ 19 | temp+=s[i]; 20 | } 21 | } 22 | reverse(temp.begin(),temp.end()); 23 | if(temp.size()>0 && ans.size()>0){ 24 | ans+=' '; 25 | ans+=temp; 26 | } 27 | if(ans.size()==0 && temp.size()>0){ 28 | ans+=temp; 29 | } 30 | return ans; 31 | } 32 | }; -------------------------------------------------------------------------------- /Roman to Integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int romanToInt(string s) { 4 | int ans = 0; 5 | unordered_map um; 6 | um['I'] = 1; 7 | um['V'] = 5; 8 | um['X'] = 10; 9 | um['L'] = 50; 10 | um['C'] = 100; 11 | um['D'] = 500; 12 | um['M'] = 1000; 13 | 14 | int n = s.length(); 15 | 16 | for(int i = 0; i < n; i++) { 17 | if(i + 1 < n && um[s[i]] < um[s[i+1]]) { 18 | ans += um[s[i+1]] - um[s[i]]; 19 | i++; 20 | } else { 21 | ans += um[s[i]]; 22 | } 23 | } 24 | 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /Rotate Image.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void rotate(vector> &matrix) 5 | { 6 | for (int i = 0; i < matrix.size(); i++) 7 | { 8 | for (int j = 0; j < i; j++) 9 | { 10 | swap(matrix[i][j], matrix[j][i]); 11 | } 12 | } 13 | 14 | for (int i = 0; i < matrix.size(); i++) 15 | { 16 | reverse(matrix[i].begin(), matrix[i].end()); 17 | } 18 | } 19 | }; -------------------------------------------------------------------------------- /Same Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Same Tree" Problem ==>> https://leetcode.com/problems/same-tree 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/D7ceKn0Oo8E 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | 11 | bool ans=true; 12 | 13 | void func(TreeNode* p,TreeNode* q){ 14 | if(p && q){ 15 | if(p->val!=q->val){ 16 | ans=false; 17 | } 18 | func(p->left,q->left); 19 | func(p->right,q->right); 20 | } 21 | if(p!=NULL && q==NULL){ 22 | ans=false; 23 | } 24 | if(p==NULL && q!=NULL){ 25 | ans=false; 26 | } 27 | } 28 | bool isSameTree(TreeNode* p, TreeNode* q) { 29 | func(p,q); 30 | return ans; 31 | } 32 | }; -------------------------------------------------------------------------------- /Satisfiability of Equality Equations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector parent; 4 | int find(int node){ 5 | return parent[node] == -1?node:parent[node] = find(parent[node]); 6 | } 7 | void takeUnion(int a,int b){ 8 | int x = find(a),y = find(b); 9 | if(x!=y) parent[x] = y; 10 | } 11 | bool equationsPossible(vector& equations) { 12 | parent = vector(26,-1); 13 | for(auto eq:equations) 14 | if(eq[1] == '=')takeUnion(eq[0]-'a',eq[3]-'a'); 15 | for(auto eq:equations) 16 | if(eq[1] == '!' and find(eq[0]-'a') == find(eq[3]-'a'))return false; 17 | return true; 18 | } 19 | }; -------------------------------------------------------------------------------- /Search Insert Position.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Search Insert Position" Problem ==>> https://leetcode.com/problems/search-insert-position/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/uOuMI58qlag 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | 11 | int func(vector nums, int low,int high, int target){ 12 | 13 | int mid=(low+high)/2; 14 | if(nums[mid]==target){ 15 | return mid; 16 | } 17 | else if(low==high){ 18 | return mid; 19 | } 20 | else if(nums[mid]>target){ 21 | return func(nums,low,mid,target); 22 | } 23 | else{ 24 | return func(nums,mid+1,high,target); 25 | } 26 | return -1; 27 | } 28 | 29 | int searchInsert(vector& nums, int target) { 30 | 31 | if(target>nums[nums.size()-1]){ 32 | return nums.size(); 33 | } 34 | return func(nums,0,nums.size(),target); 35 | } 36 | }; -------------------------------------------------------------------------------- /Search in Rotated Sorted Array II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool search(vector& nums, int target){ 4 | 5 | int l = 0; 6 | 7 | int r = nums.size() - 1; 8 | 9 | while(l <= r){ 10 | int mid = l + (r-l) / 2; 11 | 12 | if (nums[mid] == target) 13 | return true; 14 | 15 | if((nums[l]==nums[mid]) && (nums[r]==nums[mid])){ 16 | l++; 17 | r--; 18 | } 19 | else if(nums[l] <= nums[mid]){ 20 | if((nums[l] <= target) && (nums[mid] > target)) 21 | r = mid - 1; 22 | else 23 | l = mid + 1; 24 | } 25 | else{ 26 | if((nums[mid] < target) && (nums[r]>= target)) 27 | l = mid + 1; 28 | else 29 | r = mid - 1; 30 | } 31 | } 32 | return false; 33 | } 34 | }; -------------------------------------------------------------------------------- /Shuffle the Array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Shuffle the Array" Problem ==>> https://leetcode.com/problems/shuffle-the-array/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/3kpxsfuQwJo 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector shuffle(vector& nums, int n) { 11 | vector ans; 12 | for(int i=0;i> https://leetcode.com/problems/sign-of-the-product-of-an-array/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/J3ZL9s2jpz8 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int arraySign(vector& nums) { 11 | int count=0; 12 | for(int i=0;i> https://leetcode.com/problems/single-element-in-a-sorted-array/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/ANyr7n8uHrM 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | 11 | int func(vector nums, int low,int high){ 12 | 13 | int mid=(low+high)/2; 14 | if(low==high){ 15 | return low; 16 | } 17 | if(mid%2==0 && nums[mid]==nums[mid+1]){ 18 | return func(nums,mid+1,high); 19 | } 20 | else if(mid%2==0 && nums[mid]!=nums[mid+1]){ 21 | return func(nums,low,mid); 22 | } 23 | else if(mid%2!=0 && nums[mid]==nums[mid-1]){ 24 | return func(nums,mid+1,high); 25 | } 26 | return func(nums,low,mid); 27 | } 28 | 29 | int singleNonDuplicate(vector& nums) { 30 | 31 | if(nums.size()==1){ 32 | return nums[0]; 33 | } 34 | int index= func(nums,0,nums.size()-1); 35 | return nums[index]; 36 | } 37 | }; -------------------------------------------------------------------------------- /Single Number II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Single Number II " Problem ==>> https://leetcode.com/problems/single-number-ii/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/YEOQYx7qVW0 5 | 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | int singleNumber(vector& nums) { 12 | 13 | if(nums.size()<3) 14 | return nums[0]; 15 | 16 | sort(nums.begin(), nums.end()); 17 | 18 | if(nums[0] != nums[1]) 19 | return nums[0]; 20 | 21 | for(int i=1; i getOrder(vector>& A) { 4 | priority_queue, vector>, greater<>> pq; 5 | int N = A.size(); 6 | long time = 0; 7 | int i = 0; 8 | for (int i = 0; i < N; ++i){ 9 | A[i].push_back(i); 10 | } 11 | sort(begin(A), end(A)); 12 | vector ans; 13 | while (i < N || pq.size()){ 14 | if (pq.empty()) { 15 | time = max(time, (long)A[i][0]); 16 | } 17 | while (i < N && time >= A[i][0]){ 18 | pq.push({A[i][1],A[i][2]}); 19 | ++i; 20 | } 21 | pair s= pq.top(); 22 | pq.pop(); 23 | time += s.first; 24 | ans.push_back(s.second); 25 | } 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /Sliding Window Maximum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Sliding Window Maximum " Problem ==>> https://leetcode.com/problems/sliding-window-maximum/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/xnuZPbCoNSo 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector maxSlidingWindow(vector& nums, int k) { 11 | 12 | mapmp; 13 | 14 | priority_queuepq; 15 | 16 | for(int i=0;ians; 22 | 23 | for(int i=0,j=k-1;j> https://leetcode.com/problems/smallest-number-in-infinite-set/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/K9c1QOYzrt0 5 | 6 | */ 7 | 8 | class SmallestInfiniteSet { 9 | set S; 10 | public: 11 | 12 | SmallestInfiniteSet() { 13 | for (int i=1; i<=1000; i++) 14 | S.insert(i); 15 | } 16 | 17 | int popSmallest() { 18 | int x = *S.begin(); 19 | S.erase(S.begin()); 20 | return x; 21 | } 22 | 23 | void addBack(int num) { 24 | S.insert(num); 25 | } 26 | }; 27 | 28 | /** 29 | * Your SmallestInfiniteSet object will be instantiated and called as such: 30 | * SmallestInfiniteSet* obj = new SmallestInfiniteSet(); 31 | * int param_1 = obj->popSmallest(); 32 | * obj->addBack(num); 33 | */ -------------------------------------------------------------------------------- /Solving Questions With Brainpower.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Solving Questions With Brainpower " Problem ==>> https://leetcode.com/problems/solving-questions-with-brainpower/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/F5xxOU2pySg 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | long long find(vector>&ques,int n,int ind,vector&dp){ 11 | if(ind>=n) 12 | return 0; 13 | if(dp[ind]!=-1) 14 | return dp[ind]; 15 | long long choose=0; 16 | choose=max(ques[ind][0]+find(ques,n,ind+ques[ind][1]+1,dp),find(ques,n,ind+1,dp)); 17 | return dp[ind] = choose; 18 | } 19 | long long mostPoints(vector>& questions) { 20 | 21 | int n=questions.size(); 22 | vectordp(n,-1); 23 | return find(questions,n,0,dp); 24 | 25 | } 26 | }; -------------------------------------------------------------------------------- /Sort Array By Parity.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Sort Array By Parity" Problem ==>> https://leetcode.com/problems/sort-array-by-parity/description/?envType=daily-question&envId=2023-09-28 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/-ycfGA_m3Fo 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector sortArrayByParity(vector& nums) { 11 | 12 | int left=0,right=nums.size()-1; 13 | 14 | while(leftleft && nums[right]%2==1) { 17 | right--; 18 | } 19 | swap(nums[left],nums[right]); 20 | } 21 | left++; 22 | } 23 | 24 | return nums; 25 | } 26 | }; -------------------------------------------------------------------------------- /Sort Characters By Frequency.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string frequencySort(string s) { 4 | unordered_map freq; 5 | vector bucket(s.size()+1, ""); 6 | string res; 7 | for(char c:s) freq[c]++; 8 | for(auto& it:freq) { 9 | int n = it.second; 10 | char c = it.first; 11 | bucket[n].append(n, c); 12 | } 13 | for(int i=s.size(); i>0; i--) { 14 | if(!bucket[i].empty()) 15 | res.append(bucket[i]); 16 | } 17 | return res; 18 | } 19 | }; -------------------------------------------------------------------------------- /Sort the Matrix Diagonally.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> diagonalSort(vector>& mat) { 4 | unordered_map,greater>> m; 5 | int row = mat.size(); 6 | if(row == 0) return mat; 7 | int col = mat[0].size(); 8 | 9 | for(int i=0;i> https://leetcode.com/problems/soup-servings/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/lxTblMLfbMk 5 | 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | double help(int a, int b, map< pair, double>& mp) 12 | { 13 | 14 | if (a<=0 && b<=0) 15 | return 0.5; 16 | if (a<=0) 17 | return 1; 18 | if (b<=0) 19 | return 0; 20 | if (mp.count({a,b})) 21 | return mp[{a,b}]; 22 | 23 | double ans = 0; 24 | 25 | ans += help(a-100, b, mp); 26 | ans += help(a-75, b-25, mp); 27 | ans += help(a-50, b-50, mp); 28 | ans += help(a-25, b-75, mp); 29 | 30 | return mp[{a,b}] = (double)ans / (double)4; 31 | } 32 | 33 | double soupServings(int n) { 34 | 35 | if (n>=5000) 36 | return 1.0; 37 | 38 | map< pair, double> mp; 39 | 40 | return help(n, n, mp); 41 | } 42 | 43 | }; -------------------------------------------------------------------------------- /Split Array into Consecutive Subsequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPossible(vector& nums) { 4 | map m,m1; 5 | for(int i=0;i0){ 13 | m1[i-1]--; 14 | m1[i]++; 15 | } 16 | else if(m[i+1]!=0 && m[i+2]!=0){ 17 | m[i+1]--; 18 | m[i+2]--; 19 | m1[i+2]++; 20 | } 21 | else 22 | return false; 23 | } 24 | return true; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Stone Game III.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Stone Game III " Problem ==>> https://leetcode.com/problems/stone-game-iii/ 3 | 4 | Link to the complete Explaination Video ==>>https://youtu.be/5zfsDxERaik 5 | 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | string stoneGameIII(vector& stoneValue) { 12 | 13 | vector bestScore(stoneValue.size(), 0); 14 | 15 | for(int i = bestScore.size() - 1; i >= 0; i--){ 16 | 17 | int take = 0; 18 | 19 | int best = INT_MIN; 20 | 21 | for(int j = 0; j < 3 && i + j < stoneValue.size(); j++){ 22 | 23 | take += stoneValue[i + j]; 24 | int oppo = (i + j + 1 < stoneValue.size()) ? bestScore[i + j + 1] : 0; 25 | best = max(best, take - oppo); 26 | } 27 | 28 | bestScore[i] = best; 29 | 30 | } 31 | 32 | return (bestScore[0] > 0) ? "Alice" : (bestScore[0] == 0) ? "Tie" : "Bob"; 33 | } 34 | }; -------------------------------------------------------------------------------- /String Compression.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " String Compression " Problem ==>> https://leetcode.com/problems/string-compression/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/-1jhUCSVvbY 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int compress(vector& chars) { 11 | 12 | int count = 1; 13 | string ans; 14 | ans.push_back(chars[0]); 15 | for(int i=1; i 1) 20 | ans = ans + to_string(count); 21 | count = 1; 22 | ans.push_back(chars[i]); 23 | } 24 | } 25 | if(count > 1) 26 | ans = ans + to_string(count); 27 | for(int i=0; i& A, int K) { 4 | unordered_map mp; 5 | int sum = 0, ans = 0; 6 | mp[0] = 1; 7 | for(int n: A){ 8 | sum = ((sum + n) % K + K) % K; 9 | mp[sum] ++; 10 | if(mp[sum] > 1){ 11 | ans += mp[sum] - 1; 12 | } 13 | } 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Successful Pairs of Spells and Potions.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Successful Pairs of Spells and Potions " Problem ==>> https://leetcode.com/problems/successful-pairs-of-spells-and-potions/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/L6qK49vm7o8 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector successfulPairs(vector& spells, vector& potions, long long success) { 11 | 12 | int p =potions.size(); 13 | sort(potions.begin(),potions.end()); 14 | vector ans; 15 | for(long long i : spells){ 16 | 17 | int s=0; 18 | int e=p-1; 19 | int count=0; 20 | while(s<=e){ 21 | int mid=s+(e-s)/2; 22 | if(i*potions[mid]>=success){ 23 | count+=e-mid+1; 24 | e=mid-1; 25 | } 26 | else if(i*potions[mid]> https://leetcode.com/problems/sum-root-to-leaf-numbers/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/J0k0xLA8k8c 5 | 6 | */ 7 | 8 | 9 | class Solution { 10 | public: 11 | 12 | int sumNumbers(TreeNode* root,int sum=0) { 13 | 14 | if(!root){ 15 | return 0; 16 | } 17 | sum = sum*10+root->val; 18 | 19 | if(!root->left && !root->right){ 20 | return sum; 21 | } 22 | return sumNumbers(root->left,sum)+sumNumbers(root->right,sum); 23 | } 24 | }; -------------------------------------------------------------------------------- /Sum of Even Numbers After Queries.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sumEvenAfterQueries(vector& nums, vector>& queries) { 4 | int sum=0; 5 | for(int i=0;ians; 11 | for(int i=0;i it=queries[i]; 14 | int x=nums[it[1]]; 15 | if(x%2==0) 16 | { 17 | sum-=x; 18 | } 19 | nums[it[1]]+=it[0]; 20 | if(nums[it[1]]%2==0) 21 | sum+=nums[it[1]]; 22 | ans.push_back(sum); 23 | } 24 | return ans; 25 | } 26 | }; -------------------------------------------------------------------------------- /Swapping Nodes in a Linked List.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Swapping Nodes in a Linked List " Problem ==>> https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/PzACfONxUco 5 | 6 | */ 7 | 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* swapNodes(ListNode* head, int k) { 21 | 22 | ListNode* front = head; 23 | 24 | while(--k){ 25 | front = front->next; 26 | } 27 | 28 | ListNode* ahead = front; 29 | ListNode* back = head; 30 | 31 | while(ahead->next){ 32 | 33 | ahead = ahead->next; 34 | 35 | back = back->next; 36 | } 37 | swap(front->val,back->val); 38 | return head; 39 | } 40 | }; -------------------------------------------------------------------------------- /Symmetric Tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Symmetric Tree " Problem ==>> https://leetcode.com/problems/symmetric-tree/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/lGxQfZ1mujc 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | bool helper(TreeNode* left,TreeNode* right){ 11 | 12 | if(!left and !right) 13 | return true; 14 | if((left != NULL and right == NULL) || (left == NULL and right != NULL) || (left->val!=right->val)) 15 | return false; 16 | if(left->val==right->val) 17 | return helper(left->right,right->left) && helper(left->left,right->right); 18 | return true; 19 | } 20 | 21 | bool isSymmetric(TreeNode* root) { 22 | 23 | if(!root) 24 | return true; 25 | return helper(root->left,root->right); 26 | } 27 | }; -------------------------------------------------------------------------------- /The Number of Weak Characters in the Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static bool comp(vector& a,vector& b){ 4 | if(a[0]==b[0])return a[1]>b[1]; 5 | return a[0]>& properties) { 8 | int n=properties.size(); 9 | sort(properties.begin(),properties.end(),comp); 10 | int maxdef=INT_MIN; 11 | int count=0; 12 | for(int i=n-1;i>=0;i--){ 13 | if(properties[i][1]> getSkyline(vector>& buildings) { 4 | vector> ans; 5 | vector> temp; 6 | for(auto x:buildings){ 7 | temp.push_back({x[0], -x[2]}); 8 | temp.push_back({x[1], x[2]}); 9 | } 10 | sort(temp.begin(), temp.end()); 11 | multiset> set; 12 | set.insert(0); 13 | int height=0; 14 | for(auto x: temp){ 15 | int currX=x.first, currH=x.second; 16 | if(currH<0) 17 | set.insert(-currH); 18 | else 19 | set.erase(set.find(currH)); 20 | int top=*set.begin(); 21 | if(height!=top){ 22 | height=top; 23 | ans.push_back({currX, top}); 24 | } 25 | 26 | } 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /Time Based Key-Value Store.cpp: -------------------------------------------------------------------------------- 1 | class TimeMap { 2 | public: 3 | unordered_map>> mp; 4 | TimeMap() { 5 | mp.clear(); 6 | } 7 | 8 | void set(string key, string value, int timestamp) { 9 | mp[key].insert({timestamp, value}); 10 | } 11 | 12 | string get(string key, int timestamp) { 13 | if(mp[key].size() != 0){ 14 | auto it = mp[key].upper_bound({timestamp, "~"}); 15 | if(it == mp[key].begin()) return ""; 16 | --it; 17 | return it->second; 18 | } 19 | return ""; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Toeplitz Matrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isToeplitzMatrix(vector>& matrix) { 4 | int n=matrix.size(); 5 | int m=matrix[0].size(); 6 | for(int i=1;i& A) { 4 | int N = A.size(), ans = 0; 5 | 6 | vector left(N, 0), right(N, 0); 7 | 8 | for(int i = 1; i < N; i++) { 9 | left[i] = max(left[i - 1], A[i - 1]); 10 | } 11 | 12 | for(int i = N - 2; i >= 0; i--) { 13 | right[i] = max(right[i + 1], A[i + 1]); 14 | } 15 | 16 | for(int i = 1; i < N - 1; i++) { 17 | ans += max(0, min(left[i], right[i]) - A[i]); 18 | } 19 | 20 | return ans; 21 | 22 | } 23 | }; -------------------------------------------------------------------------------- /Two Sum IV - Input is a BST.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | vector vec; 4 | void inorder(TreeNode* node){ 5 | if(!node) 6 | return; 7 | inorder(node -> left); 8 | vec.push_back(node -> val); 9 | inorder(node -> right); 10 | } 11 | bool findTarget(TreeNode* root, int k) { 12 | if(!root) 13 | return false; 14 | inorder(root); 15 | int i = 0, j = vec.size()-1; 16 | while(i < j) 17 | { 18 | int sum = vec[i]+vec[j]; 19 | if(sum == k) 20 | return true; 21 | else if(sum < k) 22 | i++; 23 | else 24 | j--; 25 | } 26 | return false; 27 | } 28 | }; -------------------------------------------------------------------------------- /Ugly Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isUgly(int n) { 4 | 5 | if( n==0) return false; 6 | 7 | while( n%2==0){ 8 | n=n/2; 9 | } 10 | while( n%3==0){ 11 | n=n/3; 12 | } 13 | while( n%5==0){ 14 | n=n/5; 15 | } 16 | return (n==1); 17 | } 18 | }; -------------------------------------------------------------------------------- /Uncrossed Lines.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Uncrossed Lines " Problem ==>> https://leetcode.com/problems/uncrossed-lines/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/m052wX6wl54 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int maxUncrossedLines(vector& nums1, vector& nums2) { 11 | 12 | int n=nums1.size(),m=nums2.size(); 13 | int dp[max(n+1,m+1)][max(n+1,m+1)]; 14 | memset(dp,-1,sizeof(dp)); 15 | for(int i=0;i<=max(n,m);i++){ 16 | dp[0][i]=0; 17 | dp[i][0]=0; 18 | } 19 | for(int i=1;i<=nums1.size();i++){ 20 | for(int j=1;j<=nums2.size();j++){ 21 | if(nums1[i-1]==nums2[j-1]){ 22 | dp[i][j]=1+dp[i-1][j-1]; 23 | } 24 | else 25 | dp[i][j]=max(dp[i-1][j],dp[i][j-1]); 26 | } 27 | } 28 | return dp[n][m]; 29 | } 30 | }; -------------------------------------------------------------------------------- /Unique Morse Code Words.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniqueMorseRepresentations(vector& words) { 4 | vector t = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; 5 | 6 | // insert to set so that we can find unique solutions 7 | set s; 8 | 9 | for(int i = 0; i < words.size();i++){ 10 | string tt = words[i]; // Present word 11 | string temp = ""; // to store coded word from tt 12 | 13 | for(int j= 0 ;j < tt.length(); j++){ 14 | int e = tt[j] - 'a'; // we get the particular index 15 | temp += t[e]; 16 | } 17 | s.insert(temp); // insert all codes 18 | } 19 | return s.size(); // we get unquie number 20 | } 21 | }; -------------------------------------------------------------------------------- /Unique Number of Occurrences.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool uniqueOccurrences(vector& arr) 5 | { 6 | unordered_map cnt; 7 | unordered_set unq; 8 | for (int n : arr) cnt[n]++; // [1] count frequencies 9 | for (auto& c : cnt) unq.insert(c.second); // [2] collect unique frequencies 10 | return cnt.size() == unq.size(); 11 | } 12 | }; -------------------------------------------------------------------------------- /Unique Paths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | vector> paths(m,vector(n,1)); 5 | for(int i=1;i> https://leetcode.com/problems/valid-parentheses/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/vSx5gDa2yHk 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | bool isValid(string s) { 11 | 12 | stack st; 13 | for(int i=0;i0 && s[i]==st.top()){ 24 | st.pop(); 25 | } 26 | else{ 27 | return false; 28 | } 29 | } 30 | if(st.size()==0){ 31 | return true; 32 | } 33 | return false; 34 | } 35 | }; -------------------------------------------------------------------------------- /Valid Sudoku.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isValidSudoku(vector > &board) 5 | { 6 | int used1[9][9] = {0}, used2[9][9] = {0}, used3[9][9] = {0}; 7 | for(int i = 0; i < board.size(); ++ i) 8 | for(int j = 0; j < board[i].size(); ++ j) 9 | if(board[i][j] != '.'){ 10 | int num = board[i][j] - '0' - 1, k = (i/3)*3+ j / 3; 11 | if(used1[i][num] || used2[j][num] || used3[k][num]) 12 | return false; 13 | used1[i][num] = used2[j][num] = used3[k][num] = 1; 14 | } 15 | return true; 16 | } 17 | }; -------------------------------------------------------------------------------- /Validate Binary Search Tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool helper(TreeNode* root,long low ,long high){ 4 | if(root == NULL){ 5 | return true; 6 | } 7 | if((root->val < high) && (root->val > low)){ 8 | return (helper(root->left, low, root->val) && helper(root->right, root->val, high)); 9 | 10 | } 11 | else{ 12 | return false; 13 | } 14 | } 15 | 16 | bool isValidBST(TreeNode* root) { 17 | bool ans = helper(root, LONG_MIN, LONG_MAX); 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Validate Stack Sequences.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the " Validate Stack Sequences " Problem ==>> https://leetcode.com/problems/validate-stack-sequences/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/69LWjDSLLt8 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | bool validateStackSequences(vector& pushed, vector& popped) { 11 | 12 | stack st; 13 | int j = 0; 14 | for(auto val : pushed){ 15 | st.push(val); 16 | while(st.size() > 0 && st.top() == popped[j]){ 17 | st.pop(); 18 | j++; 19 | } 20 | } 21 | return st.size() == 0; 22 | } 23 | }; -------------------------------------------------------------------------------- /Verifying an Alien Dictionary.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Link to the "Verifying an Alien Dictionary" Problem ==>> https://leetcode.com/problems/verifying-an-alien-dictionary/ 3 | 4 | Link to the complete Explaination Video ==>> https://youtu.be/61BxjyZddVg 5 | 6 | */ 7 | 8 | class Solution { 9 | public: 10 | unordered_map mp; 11 | bool compare(string& first,string& second){ 12 | int m=first.length(),n=second.length(); 13 | for(int i=0;imp[second[i]]) 18 | return false; 19 | } 20 | if(n>=m) return true; 21 | return false; 22 | } 23 | 24 | bool isAlienSorted(vector& words, string order) { 25 | 26 | for(int i=0;i> verticalTraversal(TreeNode* root) { 4 | queue>> q; 5 | map>> m; 6 | q.push({root,{0,0}}); 7 | while(!q.empty()){ 8 | auto p=q.front(); 9 | q.pop(); 10 | TreeNode* value=p.first; 11 | int x=p.second.first,y=p.second.second; 12 | m[x][y].insert(value->val); 13 | if(value->left){ 14 | q.push({value->left,{x-1,y+1}}); 15 | } 16 | if(value->right){ 17 | q.push({value->right,{x+1,y+1}}); 18 | } 19 | } 20 | vector> ans; 21 | for(auto q: m){ 22 | vector col; 23 | for(auto z: q.second){ 24 | col.insert(col.end(),z.second.begin(),z.second.end()); 25 | } 26 | ans.push_back(col); 27 | } 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /Where Will the Ball Fall.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findBall(vector>& grid) { 4 | 5 | int m = grid.size(), n = grid[0].size(); 6 | 7 | vector res; 8 | 9 | for (int i = 0; i < n; ++i) { 10 | 11 | int i1 = i, i2; 12 | 13 | for (int j = 0; j < m; ++j) { 14 | 15 | i2 = i1 + grid[j][i1]; 16 | 17 | if (i2 < 0 || i2 >= n || grid[j][i2] != grid[j][i1]) { 18 | i1 = -1; 19 | break; 20 | } 21 | 22 | i1 = i2; 23 | } 24 | res.push_back(i1); 25 | } 26 | return res; 27 | } 28 | }; -------------------------------------------------------------------------------- /Word Search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool exist(vector>& board, string word) { 4 | for (int i = 0; i < board.size(); i++) 5 | for (int j = 0; j < board[0].size(); j++) 6 | if (dfs(board, i, j, word)) 7 | return true; 8 | return false; 9 | } 10 | 11 | bool dfs(vector>& board, int i, int j, string& word) { 12 | if (!word.size()) 13 | return true; 14 | if (i<0 || i>=board.size() || j<0 || j>=board[0].size() || board[i][j] != word[0]) 15 | return false; 16 | char c = board[i][j]; 17 | board[i][j] = '*'; 18 | string s = word.substr(1); 19 | bool ret = dfs(board, i-1, j, s) || dfs(board, i+1, j, s) || dfs(board, i, j-1, s) || dfs(board, i, j+1, s); 20 | board[i][j] = c; 21 | return ret; 22 | } 23 | }; -------------------------------------------------------------------------------- /Word Subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector wordSubsets(vector& words1, vector& words2) { 4 | vector result; 5 | int a[26]={0}; 6 | for(int i=0;i> a(numRows, vector(s.size())); 6 | int row = 0, dir = true; 7 | for(int i = 0; i < s.size(); i++){ 8 | a[row%numRows][i] = s[i]; 9 | if(dir) 10 | ++row; 11 | else 12 | --row; 13 | 14 | if(row == numRows-1) 15 | dir = false; 16 | else if(row == 0) 17 | dir = true; 18 | 19 | } 20 | 21 | string r; 22 | for(auto x : a) 23 | for(auto y : x) 24 | if(isalpha(y) || y == '.' || y == ',') 25 | r+=y; 26 | return r; 27 | } 28 | }; 29 | --------------------------------------------------------------------------------