├── .gitignore ├── Medium ├── 134. Gas Station │ ├── Readme.md │ ├── Solution.cpp │ └── Solution.java ├── 151. Reverse Words in a String │ ├── Approach 1 │ │ ├── Solution.py │ │ └── sol.md │ ├── Solution.java │ └── sol.md ├── 274. H-Index │ ├── Readme.md │ ├── Solution.java │ └── Solution.cpp ├── 172. Factorial Trailing Zeroes │ ├── Solution.java │ └── sol.md ├── 343. Integer Break │ ├── solution.py │ ├── solution.cpp │ └── solution.java ├── 8. String to Integer (atoi) │ └── Solution.js ├── 287. Find Duplicate Number │ ├── New Approach │ │ ├── Solution.java │ │ └── sol.md │ ├── sol.cpp │ └── sol.java ├── 779. K-th Symbol in Grammar │ ├── Kth_Symbol.cpp │ └── Kth_Symbol.java ├── 80. Remove-duplicates-from-sorted-array │ └── remove-duplicates.py ├── 55. Jump Game │ ├── Solution.cpp │ └── Solution.java ├── 122. Best Time to Buy and Sell Stock II │ └── solution.cpp ├── 7. Reverse Integer │ ├── Constant space approach │ │ └── Solution.java │ ├── sol.cpp │ └── sol.java ├── 1996. The Number of Weak Characters in the Game │ ├── Solution.py │ ├── Solution.java │ └── Solution.cpp ├── 1503. Last Moment Before All Ants Fall Out of a Plank │ └── Solution.java ├── 560. Subarray Sum Equals K │ ├── solution.js │ └── readme.md ├── 134.Gas Station │ ├── solution.py │ ├── solution.java │ └── solution.cpp ├── 2433. Find The Original Array of Prefix Xor │ └── Solution.cpp ├── 215. Kth Largest Element in an Array │ └── Solution.java ├── 2186. Minimum Number of Steps to Make Two Strings Anagram II │ ├── sol.md │ └── Solution.java ├── 1448. Count Good Nodes in Binary Tree │ └── Solution.java ├── 11. Container With Most Water │ ├── Solution.java │ └── Solution.cpp ├── 189. Rotate Array │ └── Solution.java ├── 974. Subarray Sums Divisible by K │ ├── Solution.cpp │ ├── Solution.py │ └── Solution.java ├── 12. Integer To Roman │ └── Solution.js ├── 2038. Remove Colored Pieces if Both Neighbors are the Same Color │ ├── Solution.cpp │ ├── Solution.java │ └── Readme.md ├── 2038. Remove Colored Pieces if │ ├── sol.cpp │ ├── sol.java │ └── sol.md ├── 98. Valid BST │ ├── solution.cpp │ ├── README.md │ └── solution.java ├── 967. Numbers With Same Consecutive Differences │ ├── Solution.py │ ├── Solution.cpp │ └── Solution.java ├── 341. Flatten Nested List Iterator │ ├── soln.py │ ├── soln.cpp │ └── soln.java ├── 34. First and Last Position of Element in an Array │ └── New Approach │ │ ├── Solution.java │ │ └── sol.md ├── 48. Rotate Image │ ├── Solution.java │ └── Solution.cpp ├── 179. Largest Number │ ├── sol.java │ └── sol.cpp ├── 62. Unique Paths │ ├── sol.java │ └── sol.md ├── 1647. Min Deletions to Make Char Frequencies Unique │ └── sol.md ├── 19. Remove nth Node From the End │ ├── sol.md │ ├── sol.java │ └── sol.cpp ├── 2. Add Two Numbers │ └── Approach 1 │ │ ├── Readme.md │ │ └── Solution..cpp ├── 853. Car Fleet │ └── Solution.js ├── 22. Generate Parentheses │ └── README.md ├── 36. Valid Sudoku │ └── Solution.java ├── 15. 3sum │ └── solution.java ├── 153. Find Minimum in Rotated Sorted Array │ ├── sol.java │ └── sol.cpp ├── 1695. Maximum Erasure Value │ └── README.md ├── 200. Number of Islands │ ├── Solution.cpp │ └── Solution.java ├── 229. MajorityElement-ll │ ├── Solution.cpp │ └── Solution.java ├── 1361. Validate Binary Tree Nodes │ └── Readme.md ├── 43. Multiply Strings │ ├── README.md │ └── Solution.java ├── 47. Permutations II │ ├── README.md │ └── Solution.java ├── 5. Longest Palindromic Substring │ ├── chiku011solution.cpp │ ├── Solution2.java │ └── Solution.java ├── 515. Find Largest Value in Each Tree Row │ └── sol.cpp ├── 823. Binary Trees With Factors │ └── README.md ├── 29. Divide Two Integers │ └── solution.cpp ├── 204.CountPrimes │ ├── Count-Primes.java │ └── README.md ├── 5. Longest Palindromic String │ └── longestPalindromic.cpp ├── 61. Rotate List │ └── sol.cpp ├── 1631. Path With Minimum Effort │ └── sol.md ├── 6. Zigzag Conversion │ └── solution.java ├── 40. Combination Sum II │ └── README.md ├── 15.3Sum │ └── solution.cpp └── 142. LinkedList Cycle II │ └── sol.cpp ├── Easy ├── 344. Reverse String │ ├── Solution.js │ ├── Solution.cpp │ └── Solution.java ├── 342. Power of Four │ ├── Solution.java │ ├── Solution.cpp │ └── Approach 1 │ │ ├── Solution.cpp │ │ ├── Solution.java │ │ └── Readme.md ├── 169. Majority Element │ ├── solution.py │ ├── solution.java │ ├── solution.cpp │ └── solution.md ├── 9. Palindrome Number │ ├── Solution.js │ ├── Solution.rb │ ├── Solution.py │ ├── Solution.cpp │ └── Solution.java ├── 1523. Count Odd Numbers in an Interval Range │ └── Simple Math │ │ ├── SimpleMath.py │ │ ├── SimpleMath.java │ │ └── SimpleMath.cpp ├── 1. Two Sum │ ├── Solution.rb │ ├── Solution.py │ ├── Solution.ts │ ├── Solution.cpp │ ├── Solution.cs │ ├── Solution.java │ └── Solution.php ├── 1486. XOR Operation in an Array │ └── Solution.java ├── 58. Length of Last Word │ ├── Length_of_last_word.js │ ├── sol.java │ └── sol.cpp ├── 557. Reverse Words in a String III │ ├── solution.py │ ├── solution.dart │ ├── solution.js │ ├── solution.java │ └── README.md ├── 1470. Shuffle the Array │ ├── README.md │ └── Solution.java ├── 1480. Running Sum of 1d Array │ └── Solution.java ├── 2703. Return Length of Arguments Passed │ ├── solution.js │ └── README.md ├── 217. Contains Duplicate │ ├── Solution.kt │ ├── Solution.js │ └── Solution.java ├── 746.Min Cost Climbing Stairs │ ├── solution.py │ ├── solution.java │ ├── Min Cost Climbing Stairs.cpp │ └── READme.md ├── 104. Maximum Depth of Binary Tree │ └── Recursion - 1 │ │ ├── Solution.ex │ │ ├── Solution.py │ │ ├── Solution.cpp │ │ └── Solution.java ├── 326. Power of Three │ ├── Solution.java │ └── README.md ├── 1356. Sort Integers by The Number of 1 Bits │ └── solution.py ├── 1920. Build Array from Permutation │ └── Solution.java ├── 2011. Final Value of Variable After Performing Operations │ └── Solution.java ├── 1342. Number of Steps to Reduce a Number to Zero │ └── Solution.java ├── 1929. Concatenation of Array │ ├── Solution.java │ └── Solution.cpp ├── 1720. Decode XORed Array │ └── Solution.java ├── 206. Reverse Linked List │ ├── Solution.java │ └── Solution.kt ├── 242. Valid Anagram │ └── Solution.js ├── 13. Roman to Integer │ ├── Solution.py │ └── Solution.java ├── 1512. Number of Good Pairs │ ├── sol.cpp │ ├── NoOfGP.java │ └── explanation.md.txt ├── 222. Count complete Tree Node │ └── Solution.java ├── 94. Binary Tree Inorder Traversal │ ├── Solution.java │ └── Solution.rb ├── 144. Binary Tree Preorder Traversal │ ├── Solution.java │ └── Solution.kt ├── 145. Binary Tree Postorder Traversal │ ├── Solution.java │ └── Solution.kt ├── 1672. Richest Customer Wealth │ ├── Solution.cpp │ └── Solution.java ├── 700. Search in a Binary Search Tree │ └── Solution.java ├── 101. Symmetric Tree │ ├── Solution.java │ ├── Solution.rb │ └── Solution.py ├── 121. Best Time to buy and sell stock │ ├── Solutioin.js │ └── Solution.java ├── 226. Invert Binary Tree │ ├── Solution.java │ └── Solution.kt ├── 119. Pascal's Triangle II │ ├── READme.md │ └── solution.py ├── 389. Find the Difference │ ├── sol.java │ ├── sol.cpp │ └── sol.md ├── 637. Average of Levels in Binary Tree │ ├── Solution.py │ ├── Solution.cpp │ └── Solution.java ├── 235. Lowest Common Ancestor of a Binary Search Tree │ └── Solution.java ├── 108. Convert Sorted Array to Binary Search Tree │ ├── Solution.cpp │ ├── Solution.py │ └── Solution.java ├── 653. Two Sum IV - Input is a BST │ └── Solution.java ├── 392. Is Subsequence │ ├── sol.cpp │ └── sol.java ├── 905. Sort Array by Parity │ ├── sol.java │ └── sol.cpp ├── 141. Linked List Cycle │ ├── sol.cpp │ └── sol.java ├── 896. Monotonic Array │ ├── sol.cpp │ └── sol.java ├── 14. Longest Common Prefix │ └── solution.java ├── 141.Linked List Cycle │ ├── solution.cpp │ └── solution.java ├── 2373. Largest Local Values in a Matrix │ └── Solution.java ├── 88. Merge Sorted Array │ └── Solution.cpp ├── 706. Design HashMap │ └── solution.js ├── 73. Set Matrix Zeroes │ └── Solution.java ├── 2591. Distribute Money to Maximum Children │ └── Solution.cpp ├── 111. Minimum Depth of Binary Tree │ └── README.md ├── 844. Backspace String Compare │ └── Solution.js ├── 26. Remove Duplicates from Sorted Array │ ├── Solution.js │ └── Solution.cpp ├── 2423. Remove Letter To Equalize Frequency │ └── Solution.py └── 122. Best Time to Buy and Sell Stock II │ └── 122. Best Time to Buy and Sell Stock II.cpp ├── Hard ├── 72. Edit Distance │ └── Levenshtein │ │ ├── images │ │ ├── intialization.png │ │ ├── finding-distance.png │ │ ├── intialization-table.png │ │ ├── levenshtein-distance.png │ │ └── finding-distance-table.png │ │ └── Solution.java ├── 2742. Painting the Walls │ └── solution.py ├── 233. Number of Digit One │ ├── Sol.java │ └── README.md ├── 2009. Minimum Number of Operations to Make Array Continuous │ └── solution.py ├── 135. Candy │ ├── Approach 1 │ │ ├── Readme.md │ │ ├── solution.cpp │ │ └── sloution.java │ ├── sol.java │ └── sol.cpp ├── 115. Distinct Subsequences │ ├── solution.java │ └── Approach 1 │ │ ├── solution.py │ │ ├── solution.go │ │ ├── solution.scala │ │ └── solution.rust ├── 1359. Count All Valid Pickup and Delivery Options │ ├── sol.java │ └── sol.cpp ├── 34. Find First and Last Position of Element in Sorted Array │ ├── sol.py │ ├── sol.cpp │ └── sol.java ├── 1269. Number of Ways to Stay in the Same Place After Some Steps │ ├── solution.py │ └── Readme.md ├── 42. Trapping Rain Water │ ├── Approach 1 │ │ └── solution.py │ └── sol.js ├── 2366. Min Replacements to Sort an Array │ ├── sol.cpp │ └── sol.java ├── 273. Integer to English Words │ └── README.md ├── 2227. Encrypt and Decrypt String │ └── solution.py ├── 1458. Max Dot Product of Two Subsequences │ ├── solution.py │ └── solution.cpp ├── 2251. Number Of Flowers In Full Bloom │ └── Solution.cpp ├── 920. Number of Music Playlists │ ├── sol.cpp │ └── sol.java ├── 1425. Constrained Subsequence Sum │ ├── sol.cpp │ └── sol.java ├── 4. Median of Two Sorted Arrays │ ├── New approach[Arraylist] │ │ └── sol.md │ └── sol.java ├── 1420. build array where you can find maximum exactly k comparison │ ├── Solution.cpp │ └── Solution.java ├── 41. First Missing Positive │ ├── sol.cpp │ └── sol.java ├── 664. Strange Printer │ ├── sol.cpp │ └── sol.java ├── 2050. Parallel Courses III │ └── solution.py ├── 239. Sliding Window Max │ ├── sol.cpp │ └── sol.java └── 1326. Min no of Taps to Open to Water a Garden │ ├── sol.cpp │ └── sol.java ├── _config.yml ├── .github └── ISSUE_TEMPLATE │ └── add-a-problem.yml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | directories.ipynb 2 | .vscode/ 3 | lib/ -------------------------------------------------------------------------------- /Medium/134. Gas Station/Readme.md: -------------------------------------------------------------------------------- 1 | Time Complexity 2 | O(n) 3 | 4 | Space Complexity 5 | O(1) -------------------------------------------------------------------------------- /Easy/344. Reverse String/Solution.js: -------------------------------------------------------------------------------- 1 | var reverseString = function (s) { 2 | s.reverse(); 3 | return s; 4 | }; 5 | -------------------------------------------------------------------------------- /Hard/72. Edit Distance/Levenshtein/images/intialization.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/godkingjay/LeetCode/HEAD/Hard/72. Edit Distance/Levenshtein/images/intialization.png -------------------------------------------------------------------------------- /Easy/342. Power of Four/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPowerOfFour(int n) { 3 | return (Math.log(n)/Math.log(4)) % 1 == 0; 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Hard/72. Edit Distance/Levenshtein/images/finding-distance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/godkingjay/LeetCode/HEAD/Hard/72. Edit Distance/Levenshtein/images/finding-distance.png -------------------------------------------------------------------------------- /Hard/72. Edit Distance/Levenshtein/images/intialization-table.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/godkingjay/LeetCode/HEAD/Hard/72. Edit Distance/Levenshtein/images/intialization-table.png -------------------------------------------------------------------------------- /Hard/72. Edit Distance/Levenshtein/images/levenshtein-distance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/godkingjay/LeetCode/HEAD/Hard/72. Edit Distance/Levenshtein/images/levenshtein-distance.png -------------------------------------------------------------------------------- /Easy/169. Majority Element/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def majorityElement(self, nums: List[int]) -> int: 3 | nums.sort() 4 | n = len(nums) 5 | return nums[n//2] -------------------------------------------------------------------------------- /Easy/9. Palindrome Number/Solution.js: -------------------------------------------------------------------------------- 1 | var isPalindrome = function(x) { 2 | x = x.toString(); // Convert the input to a string 3 | return x === x.split('').reverse().join(''); 4 | }; 5 | -------------------------------------------------------------------------------- /Hard/72. Edit Distance/Levenshtein/images/finding-distance-table.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/godkingjay/LeetCode/HEAD/Hard/72. Edit Distance/Levenshtein/images/finding-distance-table.png -------------------------------------------------------------------------------- /Easy/342. Power of Four/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfFour(int n) { 4 | return n > 0 && (n & (n - 1)) == 0 && (n & 0x55555555) != 0; 5 | } 6 | }; -------------------------------------------------------------------------------- /Easy/169. Majority Element/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int majorityElement(int[] nums) { 3 | Arrays.sort(nums); 4 | int n = nums.length; 5 | return nums[n/2]; 6 | } 7 | } -------------------------------------------------------------------------------- /Medium/151. Reverse Words in a String/Approach 1/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | lists = s.split() 4 | answer = ' '.join(lists[::-1]) 5 | return answer -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | title: LeetCode Solutions 2 | description: Solutions to LeetCode problems, categorized by difficulty level (Easy, Medium, Hard) 3 | remote_theme: pages-themes/cayman@v0.2.0 4 | plugins: 5 | - jekyll-remote-theme 6 | -------------------------------------------------------------------------------- /Easy/1523. Count Odd Numbers in an Interval Range/Simple Math/SimpleMath.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countOdds(self, low: int, high: int) -> int: 3 | return (high - low)//2 + 1 if low % 2 == 1 or high % 2 == 1 else (high - low)//2 -------------------------------------------------------------------------------- /Easy/169. Majority Element/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | sort(nums.begin(), nums.end()); 5 | int n = nums.size(); 6 | return nums[n/2]; 7 | } 8 | }; -------------------------------------------------------------------------------- /Medium/274. H-Index/Readme.md: -------------------------------------------------------------------------------- 1 | Approach 2 | -->Calculate the count of paper greater than mid. 3 | -->Now if count is greater than we increase h-index =>i=mid 4 | 5 | Complexity 6 | 1.Time complexity:O(NlogN) 7 | 2.Space complexity:O(1) 8 | -------------------------------------------------------------------------------- /Easy/9. Palindrome Number/Solution.rb: -------------------------------------------------------------------------------- 1 | def is_palindrome(x) 2 | return false if x < 0 3 | reverse = 0 4 | original = x 5 | while x > 0 6 | reverse = reverse * 10 + x % 10 7 | x /= 10 8 | end 9 | reverse == original 10 | end 11 | -------------------------------------------------------------------------------- /Easy/1. Two Sum/Solution.rb: -------------------------------------------------------------------------------- 1 | def two_sum(nums, target) 2 | hash = {} 3 | nums.each_with_index do |num, idx| 4 | complement = target - num 5 | return [hash[complement], idx] if hash.key?(complement) 6 | hash[num] = idx 7 | end 8 | end -------------------------------------------------------------------------------- /Easy/1486. XOR Operation in an Array/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int xorOperation(int n, int start) { 3 | int res = start; 4 | for(int i = 1; i < n; i++) 5 | res ^= (start + 2 * i); 6 | return res; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Easy/58. Length of Last Word/Length_of_last_word.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var lengthOfLastWord = function(s) { 6 | s = s.trim(); 7 | 8 | const words = s.split(" "); 9 | return words[words.length - 1].length; 10 | }; 11 | -------------------------------------------------------------------------------- /Easy/1523. Count Odd Numbers in an Interval Range/Simple Math/SimpleMath.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countOdds(int low, int high) { 3 | return low % 2 == 1 || high % 2 == 1 4 | ? (high - low)/2 + 1 5 | : (high - low)/2; 6 | } 7 | } -------------------------------------------------------------------------------- /Easy/1523. Count Odd Numbers in an Interval Range/Simple Math/SimpleMath.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countOdds(int low, int high) { 4 | return low % 2 == 1 || high % 2 == 1 5 | ? (high - low)/2 + 1 6 | : (high - low)/2; 7 | } 8 | }; -------------------------------------------------------------------------------- /Easy/557. Reverse Words in a String III/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | words = s.split(" ") 4 | rev= "" 5 | for word in words : 6 | rev = rev + word[::-1] + " " 7 | 8 | return rev.rstrip() 9 | -------------------------------------------------------------------------------- /Easy/1470. Shuffle the Array/README.md: -------------------------------------------------------------------------------- 1 | # Problem #1470 ([Shuffle the Array](https://leetcode.com/problems/shuffle-the-array/)) 2 | 3 | Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. 4 | 5 | Return the array in the form `[x1,y1,x2,y2,...,xn,yn]`. 6 | -------------------------------------------------------------------------------- /Easy/1480. Running Sum of 1d Array/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] runningSum(int[] nums) { 3 | int i = 1; 4 | while(i < nums.length){ 5 | nums[i] += nums[i - 1]; 6 | i++; 7 | } 8 | return nums; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Easy/2703. Return Length of Arguments Passed/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @return {number} 3 | */ 4 | var argumentsLength = function (...args) { 5 | return args.length 6 | }; 7 | 8 | // Time Complexity: O(1) 9 | // Space Complexity: O(1) 10 | 11 | /** 12 | * argumentsLength(1, 2, 3); // 3 13 | */ -------------------------------------------------------------------------------- /Easy/1. Two Sum/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | d = {} 4 | for i, num in enumerate(nums): 5 | if target - num in d: 6 | return [d[target - num], i] 7 | d[num] = i 8 | return [] 9 | -------------------------------------------------------------------------------- /Easy/217. Contains Duplicate/Solution.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun containsDuplicate(nums: IntArray): Boolean { 3 | val set = HashSet() 4 | for (num in nums) { 5 | if (!set.add(num)) { 6 | return true 7 | } 8 | } 9 | return false 10 | } 11 | 12 | } -------------------------------------------------------------------------------- /Easy/344. Reverse String/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reverseString(vector& s) { 4 | int n = s.size(); 5 | int x = 0; 6 | int y = n - 1; 7 | while(x < y){ 8 | std::swap(s[x], s[y]); 9 | x++; 10 | y--; 11 | } 12 | } 13 | }; -------------------------------------------------------------------------------- /Easy/746.Min Cost Climbing Stairs/solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minCostClimbingStairs(self, cost): 3 | n = len(cost) 4 | dp = [0] * (n + 1) 5 | 6 | for i in range(2, n + 1): 7 | dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]) 8 | 9 | return dp[n] -------------------------------------------------------------------------------- /Easy/217. Contains Duplicate/Solution.js: -------------------------------------------------------------------------------- 1 | var containsDuplicate = function (nums) { 2 | for (let i = nums.length - 1; i >= 0; i--) { 3 | for (let j = 0; j < i; j++) { 4 | if (nums[i] === nums[j]) { 5 | return true; 6 | } 7 | } 8 | } 9 | return false; 10 | } 11 | -------------------------------------------------------------------------------- /Easy/344. Reverse String/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void reverseString(char[] s) { 3 | char t; 4 | int n = s.length; 5 | for(int i = 0; i < n/2; i++) { 6 | t = s[i]; 7 | s[i] = s[n - i - 1]; 8 | s[n - i - 1] = t; 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Easy/104. Maximum Depth of Binary Tree/Recursion - 1/Solution.ex: -------------------------------------------------------------------------------- 1 | defmodule TreeNode do 2 | defstruct val: 0, left: nil, right: nil 3 | end 4 | 5 | defmodule Solution do 6 | def max_depth(nil), do: 0 7 | def max_depth(%TreeNode{left: left, right: right}) do 8 | 1 + max(max_depth(left), max_depth(right)) 9 | end 10 | end -------------------------------------------------------------------------------- /Easy/217. Contains Duplicate/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean containsDuplicate(int[] nums) { 3 | Set set = new HashSet(); 4 | for(int n: nums){ 5 | if(set.contains(n)) return true; 6 | set.add(n); 7 | } 8 | return false; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Medium/172. Factorial Trailing Zeroes/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int trailingZeroes(int n) { 3 | 4 | int zero=0; 5 | 6 | for(int i=5 ; i<=n ; i=i*5){ 7 | zero = zero + n/i; 8 | } 9 | 10 | return zero; 11 | 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Easy/326. Power of Three/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPowerOfThree(int n) { 3 | 4 | if (n <= 0) { 5 | return false; 6 | } 7 | 8 | double logResult = Math.log10(n) / Math.log10(3); 9 | 10 | return Math.floor(logResult) == logResult; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Easy/9. Palindrome Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, x: int) -> bool: 3 | if x < 0 or (x != 0 and x % 10 == 0): 4 | return False 5 | rev = 0 6 | while x > rev: 7 | rev = rev * 10 + x % 10 8 | x //= 10 9 | return x == rev or x == rev//10 10 | -------------------------------------------------------------------------------- /Medium/343. Integer Break/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def integerBreak(self, n: int) -> int: 3 | dp = [0] * (n + 1) 4 | dp[1] = 1 5 | for i in range(2, n + 1): 6 | dp[i] = -float('inf') 7 | for j in range(1, i): 8 | dp[i] = max(dp[i], j * (i - j), j * dp[i - j]) 9 | return dp[n] -------------------------------------------------------------------------------- /Easy/1356. Sort Integers by The Number of 1 Bits/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def solve1(x: int) -> int: 3 | count = 0 4 | while x: 5 | x &= (x - 1) 6 | count += 1 7 | return count 8 | 9 | def sortByBits(self,arr: list) -> list: 10 | return sorted(arr, key=lambda x: (Solution.solve1(x), x)) -------------------------------------------------------------------------------- /Easy/104. Maximum Depth of Binary Tree/Recursion - 1/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxDepth(self, root: Optional[TreeNode]) -> int: 3 | return self.traverse(root, 0) 4 | 5 | def traverse(self, node: Optional[TreeNode], depth) -> int: 6 | return depth if not node else max(self.traverse(node.left, depth), self.traverse(node.right, depth)) + 1 -------------------------------------------------------------------------------- /Easy/1920. Build Array from Permutation/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] buildArray(int[] nums) { 3 | int len = nums.length, i = 0; 4 | int[] newNums = new int[len]; 5 | 6 | for(int num: nums){ 7 | newNums[i++] = nums[num]; 8 | } 9 | 10 | return newNums; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Easy/557. Reverse Words in a String III/solution.dart: -------------------------------------------------------------------------------- 1 | class Solution { 2 | String reverseWords(String s) { 3 | String rev = ""; 4 | List words = s.split(" "); 5 | for (int i = 0 ; i< words.length; i++){ 6 | rev = rev + words[i].split("").reversed.join() + " "; 7 | } 8 | 9 | return rev.trim(); 10 | } 11 | } -------------------------------------------------------------------------------- /Easy/9. Palindrome Number/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) { 4 | if (x < 0 || (x != 0 && x % 10 == 0)) return false; 5 | int rev = 0; 6 | while(x > rev) { 7 | rev = rev * 10 + x%10; 8 | x /= 10; 9 | } 10 | return (x == rev || x == rev/10); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Easy/9. Palindrome Number/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPalindrome(int x) { 3 | if(x<0 || (x != 0 && x % 10 == 0)) return false; 4 | int rev = 0; 5 | while(x > rev){ 6 | rev = rev * 10 + x % 10; 7 | x = x/10; 8 | } 9 | return (x == rev || x == rev/10); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Easy/2011. Final Value of Variable After Performing Operations/Solution.java: -------------------------------------------------------------------------------- 1 | // Using for loop 2 | 3 | class Solution { 4 | public int finalValueAfterOperations(String[] operations) { 5 | int n = 0; 6 | for(String op: operations){ 7 | if (op.charAt(1) == '+') n++; 8 | else n--; 9 | } 10 | return n; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Hard/2742. Painting the Walls/solution.py: -------------------------------------------------------------------------------- 1 | from numpy import inf 2 | 3 | class Solution(object): 4 | def paintWalls(self, cost, time): 5 | 6 | n = len(cost) 7 | dp = [0] + [inf] * n 8 | for c, t in zip(cost, time): 9 | for j in range(n, 0, -1): 10 | dp[j] = min(dp[j], dp[max(j - t - 1, 0)] + c) 11 | return dp[n] -------------------------------------------------------------------------------- /Medium/8. String to Integer (atoi)/Solution.js: -------------------------------------------------------------------------------- 1 | const myAtoi = function(str) { 2 | if(str.length===0||!(parseInt(str)*parseInt(str)>=0)){ 3 | return 0; 4 | } 5 | if(parseInt(str)>2147483647){ 6 | return 2147483647; 7 | } 8 | if(parseInt(str)<-2147483648){ 9 | return -2147483648; 10 | } 11 | return parseInt(str); 12 | }; -------------------------------------------------------------------------------- /Easy/1. Two Sum/Solution.ts: -------------------------------------------------------------------------------- 1 | function twoSum(nums: number[], target: number): number[] | void { 2 | const numToIndex = new Map(); 3 | for (let i = 0; i < nums.length; i++) { 4 | const complement = target - nums[i]; 5 | if (numToIndex.has(complement)) return [numToIndex.get(complement)!, i]; 6 | numToIndex.set(nums[i], i); 7 | } 8 | return; 9 | } 10 | -------------------------------------------------------------------------------- /Easy/1342. Number of Steps to Reduce a Number to Zero/Solution.java: -------------------------------------------------------------------------------- 1 | // Using Bit Manipulation 2 | class Solution { 3 | public int numberOfSteps(int num) { 4 | if(num == 0) return 0; 5 | int res = 0; 6 | while(num != 0){ 7 | res += (num & 1) == 1 ? 2 : 1; 8 | num >>= 1; 9 | } 10 | return res - 1; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Easy/1929. Concatenation of Array/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] getConcatenation(int[] nums) { 3 | int len = nums.length; 4 | int[] newNums = new int[2 * len]; 5 | 6 | System.arraycopy(nums, 0, newNums, 0, len); 7 | System.arraycopy(nums, 0, newNums, len, len); 8 | 9 | return newNums; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Easy/1720. Decode XORed Array/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] decode(int[] encoded, int first) { 3 | int n = encoded.length; 4 | int[] decoded = new int[n + 1]; 5 | decoded[0] = first; 6 | for(int i = 0; i < n; i++){ 7 | decoded[i + 1] = decoded[i] ^ encoded[i]; 8 | } 9 | return decoded; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Hard/233. Number of Digit One/Sol.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countDigitOne(int n) { 3 | int count = 0; 4 | 5 | for (long i = 1; i <= n; i *= 10) { 6 | long divider = i * 10; 7 | count += (n / divider) * i + Math.min(Math.max(n % divider - i + 1, 0), i); 8 | } 9 | 10 | return count; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Medium/287. Find Duplicate Number/New Approach/Solution.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | public class Solution { 3 | public int findDuplicate(int[] nums) { 4 | Arrays.sort(nums); 5 | 6 | for(int i=1;i dp(n + 1, 0); 5 | dp[1] = 1; 6 | for (int i = 2; i <= n; ++i) { 7 | for (int j = 1; j < i; ++j) { 8 | dp[i] = max(dp[i], max(j * (i - j), j * dp[i - j])); 9 | } 10 | } 11 | return dp[n]; 12 | } 13 | }; -------------------------------------------------------------------------------- /Easy/206. Reverse Linked List/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode reverseList(ListNode head) { 3 | return reverse(head, null); 4 | } 5 | 6 | public ListNode reverse(ListNode head, ListNode prev){ 7 | if(head == null) return prev; 8 | ListNode next = head.next; 9 | head.next = prev; 10 | return reverse(next, head); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Easy/242. Valid Anagram/Solution.js: -------------------------------------------------------------------------------- 1 | var isAnagram = function (s, t) { 2 | let ss = Array.from(s); 3 | let tt = Array.from(t); 4 | ss.sort(); 5 | tt.sort(); 6 | if (ss.length !== tt.length) { 7 | return false; 8 | } 9 | for (let i = 0; i < s.length; i++) { 10 | if (ss[i] !== tt[i]) { 11 | return false; 12 | } 13 | } 14 | return true 15 | }; -------------------------------------------------------------------------------- /Medium/779. K-th Symbol in Grammar/Kth_Symbol.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | // 779. K-th Symbol in Grammar 4 | // explanation in readme file 5 | 6 | class Solution { 7 | public int kthGrammar(int n, int k) { 8 | if (n == 1) return 0; 9 | int length = 1 << (n - 2); 10 | if (k <= length) return kthGrammar(n - 1, k); 11 | else return 1 - kthGrammar(n - 1, k - length); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Easy/13. Roman to Integer/Solution.py: -------------------------------------------------------------------------------- 1 | roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000} 2 | class Solution: 3 | def romanToInt(self, S: str) -> int: 4 | summ= 0 5 | for i in range(len(S)-1,-1,-1): 6 | num = roman[S[i]] 7 | if 3*num < summ: 8 | summ = summ-num 9 | else: 10 | summ = summ+num 11 | return summ -------------------------------------------------------------------------------- /Medium/55. Jump Game/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | //checking right to left if the current position can reach the last index 4 | bool canJump(vector& nums) { 5 | int minjump=0; 6 | for(int i=nums.size()-2; i>=0; i--) { 7 | minjump++; 8 | if(nums[i]>=minjump) 9 | minjump=0; 10 | } 11 | return !minjump; 12 | } 13 | }; -------------------------------------------------------------------------------- /Easy/1512. Number of Good Pairs/sol.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numIdenticalPairs(std::vector& nums) { 4 | int ans = 0; 5 | std::vector count(101, 0); 6 | 7 | for (int n : nums) { 8 | count[n]++; 9 | } 10 | 11 | for (int n : count) { 12 | ans += (n * (n - 1)) / 2; 13 | } 14 | 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Easy/746.Min Cost Climbing Stairs/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minCostClimbingStairs(int[] cost) { 3 | int n = cost.length; 4 | int[] dp = new int[n]; 5 | dp[0] = cost[0]; 6 | dp[1] = cost[1]; 7 | for (int i = 2; i < n; i++) { 8 | dp[i] = cost[i] + Math.min(dp[i-1], dp[i-2]); 9 | } 10 | return Math.min(dp[n-1], dp[n-2]); 11 | } 12 | } -------------------------------------------------------------------------------- /Medium/122. Best Time to Buy and Sell Stock II/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int maxProfit = 0; 5 | 6 | for (int i = 1; i < prices.size(); i++) { 7 | if (prices[i] > prices[i - 1]) { 8 | maxProfit += prices[i] - prices[i - 1]; 9 | } 10 | } 11 | 12 | return maxProfit; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Easy/1. Two Sum/Solution.cpp: -------------------------------------------------------------------------------- 1 | // Using HashMap 2 | class Solution { 3 | public: 4 | vector twoSum(vector& nums, int target) { 5 | unordered_map map; 6 | for(int i = 0; i < nums.size(); i++){ 7 | int pair = target - nums[i]; 8 | if(map.count(pair)) return {map[pair], i}; 9 | map[nums[i]] = i; 10 | } 11 | return {}; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Medium/274. H-Index/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int hIndex(int[] c) { 3 | int low=0 , high = c.length; 4 | while(low < high){ 5 | int mid = (low+high+1)/2; 6 | int cnt=0; 7 | for(int i=0 ; i= mid) cnt++; 8 | if(cnt >= mid) low = mid; 9 | else high = high=mid-1; 10 | } 11 | return low; 12 | } 13 | } -------------------------------------------------------------------------------- /Easy/222. Count complete Tree Node/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int countNodes(TreeNode root) { 3 | int count = 1; //Root itself should be counted 4 | if (root ==null) { 5 | return 0; 6 | } 7 | else { 8 | count += countNodes(root.left); 9 | count += countNodes(root.right); 10 | return count; 11 | } 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Hard/2009. Minimum Number of Operations to Make Array Continuous/solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minOperations(self, nums): 3 | n = len(nums) 4 | nums = sorted(set(nums)) 5 | ans = sys.maxsize 6 | 7 | for i, s in enumerate(nums): 8 | e = s + n - 1 9 | idx = bisect_right(nums, e) 10 | 11 | ans = min(ans, n - (idx - i)) 12 | return ans 13 | -------------------------------------------------------------------------------- /Medium/7. Reverse Integer/Constant space approach/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int reverse(int num) { 3 | int x = Math.abs(num); //This ensures x%10 doesn't return -ve values 4 | int n = 0; 5 | while(x>0) { 6 | if(n > (Integer.MAX_VALUE - x%10)/10) return 0; 7 | n = n*10 + x%10; 8 | x = x/10; 9 | } 10 | return num < 0 ? -n : n; 11 | } 12 | } -------------------------------------------------------------------------------- /Medium/274. H-Index/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hIndex(vector& c) { 4 | int low=0 , high = c.size(); 5 | while(low < high){ 6 | int mid = (low+high+1)/2; 7 | int cnt=0; 8 | for(int i=0 ; i= mid) cnt++; 9 | if(cnt >= mid) low = mid; 10 | else high = mid-1; 11 | } 12 | return low; 13 | } 14 | }; -------------------------------------------------------------------------------- /Easy/1929. Concatenation of Array/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getConcatenation(vector& nums) { 4 | int n = nums.size(); 5 | int m = 2 * n; 6 | vector ans(m); 7 | for(int i = 0; i < n; i++){ 8 | ans[i] = nums[i]; 9 | } 10 | for(int i = 0; i < n; i++){ 11 | ans[n + i] = nums[i]; 12 | } 13 | return ans; 14 | } 15 | }; -------------------------------------------------------------------------------- /Medium/151. Reverse Words in a String/Approach 1/sol.md: -------------------------------------------------------------------------------- 1 | 1. Split the input string **'s'** into an array of words using the split() function with space as the delimiter, and store them in the 'lists' array. 2 | 2. Reverse the order of the words in the **'lists'** array using Python slicing. 3 | 3. Join the reversed words into a single string using the **join()** function with a space character as the separator. 4 | 4. Return the reversed sentence as the result. -------------------------------------------------------------------------------- /Easy/104. Maximum Depth of Binary Tree/Recursion - 1/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDepth(TreeNode* root) { 4 | return traverse(root, 0); 5 | } 6 | 7 | int traverse(TreeNode* node, int depth) { 8 | if(!node) { 9 | return depth; 10 | } 11 | return max( 12 | traverse(node->left,depth), 13 | traverse(node->right,depth) 14 | ) + 1; 15 | } 16 | }; -------------------------------------------------------------------------------- /Medium/1996. The Number of Weak Characters in the Game/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numberOfWeakCharacters(self, properties): 3 | count = 0 4 | maxN = ~sys.maxint 5 | properties.sort(key=lambda x: (-x[0], x[1])) 6 | for i in range(len(properties)): 7 | if(properties[i][1] < maxN): 8 | count+=1 9 | maxN = max(maxN, properties[i][1]) 10 | return count 11 | -------------------------------------------------------------------------------- /Easy/104. Maximum Depth of Binary Tree/Recursion - 1/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxDepth(TreeNode root) { 3 | return traverse(root, 0); 4 | } 5 | 6 | public int traverse(TreeNode node, int depth) { 7 | if(node == null) { 8 | return depth; 9 | } 10 | return Math.max( 11 | traverse(node.left, depth), 12 | traverse(node.right, depth) 13 | ) + 1; 14 | } 15 | } -------------------------------------------------------------------------------- /Easy/557. Reverse Words in a String III/solution.js: -------------------------------------------------------------------------------- 1 | const reverseWords = function(s) { 2 | //convert string to array 3 | let arrayOfs = s.split(" ") 4 | 5 | //loop over the hole array 6 | let finalstr = arrayOfs.map((item) => { 7 | //every element of array convert to a nasted array and reverser it then make it string again 8 | return item.split("").reverse().join("") 9 | }) 10 | return finalstr.join(" ") 11 | }; -------------------------------------------------------------------------------- /Easy/94. Binary Tree Inorder Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | List order = new ArrayList(); 3 | public List inorderTraversal(TreeNode root) { 4 | traverse(root); 5 | return order; 6 | } 7 | 8 | public void traverse(TreeNode root){ 9 | if(root == null) return; 10 | traverse(root.left); 11 | order.add(root.val); 12 | traverse(root.right); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Hard/135. Candy/Approach 1/Readme.md: -------------------------------------------------------------------------------- 1 | Strategies to Tackle the Problem 2 | 3 | Greedy Algorithm: Two-Pass Method 4 | This method takes two passes through the ratings array to ensure that each child gets the appropriate amount of candy. 5 | 6 | One-Pass Greedy Algorithm: Up-Down-Peak Method 7 | This more advanced method uses a single pass and employs three key variables—Up, Down, and Peak—to efficiently determine the minimum number of candies needed. 8 | -------------------------------------------------------------------------------- /Easy/144. Binary Tree Preorder Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | List order = new ArrayList(); 3 | public List preorderTraversal(TreeNode root) { 4 | traverse(root); 5 | return order; 6 | } 7 | 8 | public void traverse(TreeNode root){ 9 | if (root == null) return; 10 | order.add(root.val); 11 | traverse(root.left); 12 | traverse(root.right); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Easy/145. Binary Tree Postorder Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | List order = new ArrayList(); 3 | public List postorderTraversal(TreeNode root) { 4 | traverse(root); 5 | return order; 6 | } 7 | 8 | public void traverse(TreeNode root){ 9 | if(root == null) return; 10 | traverse(root.left); 11 | traverse(root.right); 12 | order.add(root.val); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Easy/1672. Richest Customer Wealth/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumWealth(vector>& accounts) { 4 | int max = 0; 5 | for(int i = 0; i < accounts.size(); i++){ 6 | int sum = 0; 7 | for(int j = 0; j < accounts[i].size(); j++){ 8 | sum += accounts[i][j]; 9 | max = max > sum ? max : sum; 10 | } 11 | } 12 | return max; 13 | } 14 | }; -------------------------------------------------------------------------------- /Medium/1503. Last Moment Before All Ants Fall Out of a Plank/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int getLastMoment(int n, int[] left, int[] right) { 3 | Arrays.sort(left); 4 | Arrays.sort(right); 5 | int t1 = 0; 6 | int t2 = 0; 7 | if (left.length > 0) 8 | t1 = left[left.length - 1]; 9 | if (right.length > 0) 10 | t2 = n - right[0]; 11 | return Math.max(t1, t2); 12 | } 13 | } -------------------------------------------------------------------------------- /Easy/700. Search in a Binary Search Tree/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | TreeNode node = null; 3 | public TreeNode searchBST(TreeNode root, int val) { 4 | traverse(root, val); 5 | return node; 6 | } 7 | 8 | public void traverse(TreeNode root, int val){ 9 | if(root == null) return; 10 | if(root.val == val) node = root; 11 | traverse(root.left, val); 12 | traverse(root.right, val); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Medium/560. Subarray Sum Equals K/solution.js: -------------------------------------------------------------------------------- 1 | const subarraySum = function(nums, k) { 2 | const hashTable = { 3 | 0:1, 4 | } 5 | let sum = 0 6 | let count =0 7 | for(let i=0; i < nums.length; i++){ 8 | sum += nums[i] 9 | 10 | if([sum - k] in hashTable){ 11 | count += hashTable[sum - k] 12 | 13 | } 14 | hashTable[sum] = (hashTable[sum] || 0 ) + 1 15 | } 16 | return count 17 | }; -------------------------------------------------------------------------------- /Easy/101. Symmetric Tree/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isSymmetric(TreeNode root) { 3 | if(root==null) return true; 4 | return isMirror(root.left,root.right); 5 | } 6 | 7 | public boolean isMirror(TreeNode p, TreeNode q) { 8 | if(p==null && q==null) return true; 9 | if(p==null || q==null) return false; 10 | return (p.val==q.val) && isMirror(p.left,q.right) && isMirror(p.right,q.left); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Easy/1. Two Sum/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] TwoSum(int[] nums, int target) { 3 | Dictionary map = new Dictionary(); 4 | for (int i = 0; i < nums.Length; i++) { 5 | int complement = target - nums[i]; 6 | if (map.ContainsKey(complement)) { 7 | return new int[] { map[complement], i }; 8 | } 9 | map[nums[i]] = i; 10 | } 11 | throw new Exception("No two sum solution"); 12 | } 13 | 14 | } -------------------------------------------------------------------------------- /Easy/121. Best Time to buy and sell stock/Solutioin.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} prices 3 | * @return {number} 4 | */ 5 | var maxProfit = function (prices) { 6 | let l = 0; 7 | let r = 1; 8 | let max = 0; 9 | let profit = 0; 10 | 11 | while (r < prices.length) { 12 | profit = prices[r] - prices[l]; 13 | if (profit > 0) { 14 | max = profit > max ? profit : max; 15 | } else { 16 | l = r; 17 | } 18 | r++; 19 | } 20 | return max; 21 | }; 22 | -------------------------------------------------------------------------------- /Medium/134.Gas Station/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 3 | n, total_surplus, surplus, start = len(gas), 0, 0, 0 4 | 5 | for i in range(n): 6 | total_surplus += gas[i] - cost[i] 7 | surplus += gas[i] - cost[i] 8 | if surplus < 0: 9 | surplus = 0 10 | start = i + 1 11 | return -1 if (total_surplus < 0) else start 12 | -------------------------------------------------------------------------------- /Easy/1. Two Sum/Solution.java: -------------------------------------------------------------------------------- 1 | // Using HashMap 2 | class Solution { 3 | public int[] twoSum(int[] nums, int target) { 4 | Map map = new HashMap(); 5 | for(int i = 0; i < nums.length; i++){ 6 | int pair = target - nums[i]; 7 | if(map.containsKey(pair)) 8 | return new int[]{map.get(pair), i}; 9 | map.put(nums[i], i); 10 | } 11 | return new int[]{}; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Easy/226. Invert Binary Tree/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public TreeNode invertTree(TreeNode root) { 3 | if (root == null) return root; 4 | invert(root); 5 | return root; 6 | } 7 | 8 | public void invert(TreeNode root){ 9 | if(root == null) return; 10 | TreeNode temp = root.left; 11 | root.left = root.right; 12 | root.right = temp; 13 | invert(root.left); 14 | invert(root.right); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Easy/557. Reverse Words in a String III/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reverseWords(String s) { 3 | StringBuilder res = new StringBuilder(); 4 | String[] arr = s.split(" "); 5 | for (String str : arr){ 6 | res.append(new StringBuffer(str).reverse().append(" ")); 7 | } 8 | 9 | // res.deleteCharAt(res.length() - 1); If you don't want to use trim() 10 | return res.toString().trim(); 11 | } 12 | } -------------------------------------------------------------------------------- /Easy/119. Pascal's Triangle II/READme.md: -------------------------------------------------------------------------------- 1 | Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. 2 | 3 | In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: 4 | 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: rowIndex = 3 11 | Output: [1,3,3,1] 12 | Example 2: 13 | 14 | Input: rowIndex = 0 15 | Output: [1] 16 | Example 3: 17 | 18 | Input: rowIndex = 1 19 | Output: [1,1] 20 | 21 | 22 | Constraints: 23 | 24 | 0 <= rowIndex <= 33 -------------------------------------------------------------------------------- /Easy/1. Two Sum/Solution.php: -------------------------------------------------------------------------------- 1 | maxReach) { 7 | return false; 8 | } 9 | 10 | maxReach = Math.max(maxReach, i + nums[i]); 11 | 12 | if (maxReach >= nums.length - 1) { 13 | return true; 14 | } 15 | } 16 | 17 | return false; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Easy/389. Find the Difference/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call your fn here 4 | } 5 | 6 | class Solution { 7 | public char findTheDifference(String s, String t) { 8 | int sum1 = helper(s); 9 | int sum2 = helper(t); 10 | int diff = sum2 - sum1; 11 | return (char) diff; 12 | } 13 | 14 | int helper(String s) { 15 | return s.chars().sum(); 16 | } 17 | 18 | } 19 | } -------------------------------------------------------------------------------- /Hard/233. Number of Digit One/README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 233.Number of Digit One 2 | 3 | 4 | ## Problem Description 5 | 6 | Given an integer `n`, count the total number of digit `1` appearing in all non-negative integers less than or equal to `n`. 7 | 8 | **Example 1:** 9 | 10 | Input: n = 13 11 | Output: 6 12 | 13 | **Example 2:** 14 | 15 | Input: n = 0 16 | Output: 0 17 | 18 | **Constraints:** 19 | 20 | `0 <= n <= 109` 21 | 22 | ### Link 23 | 24 | https://leetcode.com/problems/number-of-digit-one/ 25 | -------------------------------------------------------------------------------- /Easy/226. Invert Binary Tree/Solution.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * class TreeNode(var `val`: Int = 0) { 4 | * var left: TreeNode? = null 5 | * var right: TreeNode? = null 6 | * } 7 | */ 8 | class Solution { 9 | fun invertTree(root: TreeNode?): TreeNode? { 10 | if (root == null) return null 11 | val left = invertTree(root.left) 12 | val right = invertTree(root.right) 13 | root.left = right 14 | root.right = left 15 | return root 16 | } 17 | } -------------------------------------------------------------------------------- /Hard/115. Distinct Subsequences/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numDistinct(String s, String t) { 3 | 4 | int[] prev = new int[t.length()+1]; 5 | prev[0]=1; 6 | 7 | for(int i =1; i<=s.length(); i++){ 8 | for(int j =t.length(); j>=1; j--){ 9 | if(s.charAt(i-1)==t.charAt(j-1)){ 10 | prev[j] = prev[j-1] + prev[j]; 11 | } 12 | } 13 | } 14 | return prev[t.length()]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Hard/1359. Count All Valid Pickup and Delivery Options/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | public class Solution { 7 | private static final int MOD = 1000000007; 8 | 9 | public int countOrders(int n) { 10 | long count = 1; 11 | for (int i = 2; i <= n; i++) { 12 | count = (count * (2 * i - 1) * i) % MOD; 13 | } 14 | return (int) count; 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Easy/637. Average of Levels in Binary Tree/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: 3 | list = [] 4 | q = [root] 5 | while len(q): 6 | n = len(q) 7 | sum = 0 8 | for i in range(n): 9 | node = q.pop(0) 10 | sum += node.val 11 | if node.left: q.append(node.left) 12 | if node.right: q.append(node.right) 13 | list.append(sum/n) 14 | return list 15 | -------------------------------------------------------------------------------- /Medium/2433. Find The Original Array of Prefix Xor/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findArray(vector& pref) { 4 | int n = pref.size(); 5 | vector arr(n); 6 | 7 | arr[0] = pref[0]; // The first element of arr is equal to the first element of pref 8 | 9 | // Iterate through the pref array to find the elements of arr 10 | for (int i = 1; i < n; i++) { 11 | arr[i] = pref[i] ^ pref[i - 1]; 12 | } 13 | 14 | return arr; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Medium/215. Kth Largest Element in an Array/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findKthLargest(int[] nums, int k) { 3 | PriorityQueuepq= new PriorityQueue<>((a,b)->b-a); 4 | 5 | int n = nums.length ; 6 | 7 | for (int i = 0; i < nums.length; i++) { 8 | pq.add(nums[i]) ; 9 | } 10 | 11 | int f = k - 1 ; 12 | 13 | while (f > 0) { 14 | pq.remove() ; 15 | f-- ; 16 | } 17 | 18 | return pq.peek(); 19 | } 20 | } -------------------------------------------------------------------------------- /Medium/2186. Minimum Number of Steps to Make Two Strings Anagram II/sol.md: -------------------------------------------------------------------------------- 1 | ### Easiest solution to understand the solution 2 | 3 | 1. Create two arrays of 26 Characters 4 | 2. Count the frequency of characters in the first string 5 | 3. Count the frequency of characters in the second string 6 | 4. Calculate the difference in character frequencies 7 | 5. Return the difference Value 8 | 9 | Example 1: 10 | 11 | Input: s = "leetcode", t = "coats" 12 | 13 | Output: 7 14 | 15 | Example 2: 16 | 17 | Input: s = "night", t = "thing" 18 | 19 | Output: 0 -------------------------------------------------------------------------------- /Medium/1448. Count Good Nodes in Binary Tree/Solution.java: -------------------------------------------------------------------------------- 1 | // Using recursion 2 | class Solution { 3 | int n = 0; 4 | public int goodNodes(TreeNode root) { 5 | goodNode(root, root.val); 6 | return n; 7 | } 8 | 9 | public void goodNode(TreeNode root, int lastMax){ 10 | if(root == null) return; 11 | if(root.val >= lastMax){ 12 | n++; 13 | lastMax = root.val; 14 | } 15 | goodNode(root.left, lastMax); 16 | goodNode(root.right, lastMax); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Easy/206. Reverse Linked List/Solution.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode(var `val`: Int) { 4 | * var next: ListNode? = null 5 | * } 6 | */ 7 | class Solution { 8 | fun reverseList(head: ListNode?): ListNode? { 9 | var prev: ListNode? = null 10 | var current = head 11 | while (current != null) { 12 | val next = current.next 13 | current.next = prev 14 | prev = current 15 | current = next 16 | } 17 | return prev 18 | } 19 | } -------------------------------------------------------------------------------- /Hard/1359. Count All Valid Pickup and Delivery Options/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int MOD = 1000000007; 6 | 7 | class Solution 8 | { 9 | public: 10 | int countOrders(int n) 11 | { 12 | 13 | long long count = 1; 14 | 15 | for (int i = 2; i <= n; i++) 16 | { 17 | count = (count * (2 * i - 1) % MOD * i % MOD) % MOD; 18 | } 19 | 20 | return (int)count; 21 | } 22 | }; 23 | 24 | int main() 25 | { 26 | // call the fn here 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /Easy/1512. Number of Good Pairs/NoOfGP.java: -------------------------------------------------------------------------------- 1 | public class NoOfGP{ 2 | public static void main(String[] args) { 3 | 4 | } 5 | 6 | class Solution { 7 | public int numIdenticalPairs(int[] nums) { 8 | int ans = 0; 9 | int count[] = new int[101]; 10 | 11 | for(int n:nums) 12 | { 13 | count[n]++; 14 | } 15 | for(int n:count) 16 | { 17 | ans+=(n*(n-1))/2; 18 | } 19 | return ans; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /Medium/11. Container With Most Water/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxArea(int[] height) { 3 | int maxArea = 0; 4 | int leftIdx = 0, rightIdx = height.length-1; 5 | 6 | while(leftIdx < rightIdx){ 7 | maxArea = Math.max(maxArea, Math.min(height[leftIdx], height[rightIdx]) * (rightIdx - leftIdx)); 8 | if(height[leftIdx] < height[rightIdx]) 9 | leftIdx++; 10 | else 11 | rightIdx--; 12 | } 13 | 14 | return maxArea; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Medium/1996. The Number of Weak Characters in the Game/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfWeakCharacters(int[][] properties) { 3 | int n = properties.length; 4 | int count = 0; 5 | int maxN = Integer.MIN_VALUE; 6 | Arrays.sort(properties, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]); 7 | for(int i = 0; i < n; i++){ 8 | if(properties[i][1] < maxN) 9 | count++; 10 | maxN = Math.max(maxN, properties[i][1]); 11 | } 12 | return count; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Medium/11. Container With Most Water/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxArea(vector& height) { 4 | int maxArea = 0; 5 | int leftIdx = 0, rightIdx = height.size() - 1; 6 | 7 | while(leftIdx < rightIdx){ 8 | maxArea = max(maxArea, min(height[leftIdx], height[rightIdx]) * (rightIdx - leftIdx)); 9 | if(height[leftIdx] < height[rightIdx]) 10 | leftIdx++; 11 | else 12 | rightIdx--; 13 | } 14 | 15 | return maxArea; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Easy/235. Lowest Common Ancestor of a Binary Search Tree/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 3 | int min = Math.min(p.val, q.val); 4 | int max = Math.max(p.val, q.val); 5 | while(root != null){ 6 | if(root.val > max){ 7 | root = root.left; 8 | } else if (root.val < min) { 9 | root = root.right; 10 | } else { 11 | return root; 12 | } 13 | } 14 | return root; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Medium/287. Find Duplicate Number/New Approach/sol.md: -------------------------------------------------------------------------------- 1 | ### Simplest and Easiest approach to solve 2 | 3 | 1. Sort the input array `nums` in ascending order. 4 | 5 | 2. Initialize a loop from `i` = 1 to `n` (inclusive), where `n` is the length of the sorted `nums` array. 6 | 7 | 3. Within the loop: 8 | 9 | a. Check if `nums[i]` is equal to `nums[i-1]`. 10 | 11 | b. If the condition is true, return `nums[i]` as it is the duplicate element. 12 | 13 | 4. If no duplicate is found after the loop completes, return -1 to indicate that there are no duplicates in the array. 14 | -------------------------------------------------------------------------------- /Medium/134.Gas Station/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int canCompleteCircuit(int[] gas, int[] cost) { 3 | int n = gas.length; 4 | int total_surplus = 0; 5 | int surplus = 0; 6 | int start = 0; 7 | 8 | for(int i = 0; i < n; i++){ 9 | total_surplus += gas[i] - cost[i]; 10 | surplus += gas[i] - cost[i]; 11 | if(surplus < 0){ 12 | surplus = 0; 13 | start = i + 1; 14 | } 15 | } 16 | return (total_surplus < 0) ? -1 : start; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Hard/115. Distinct Subsequences/Approach 1/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numDistinct(self, s: str, t: str) -> int: 3 | m, n = len(s), len(t) 4 | dp = [[0] * (n + 1) for _ in range(m + 1)] 5 | 6 | for i in range(m + 1): 7 | dp[i][0] = 1 8 | 9 | for i in range(1, m + 1): 10 | for j in range(1, n + 1): 11 | if s[i - 1] == t[j - 1]: 12 | dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] 13 | else: 14 | dp[i][j] = dp[i - 1][j] 15 | 16 | return dp[m][n] -------------------------------------------------------------------------------- /Medium/134. Gas Station/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int canCompleteCircuit(vector& gas, vector& cost) { 4 | ios_base::sync_with_stdio(false); 5 | cin.tie(NULL); 6 | int n = cost.size(), bal = 0, start = 0, deficit = 0; 7 | 8 | for(int i = 0; i< n; i++){ 9 | bal += gas[i] - cost[i]; 10 | 11 | if(bal < 0){ 12 | 13 | deficit += bal; 14 | start = i+1; 15 | bal = 0; 16 | } 17 | } 18 | return bal + deficit >= 0 ? start : -1; 19 | } 20 | }; -------------------------------------------------------------------------------- /Easy/389. Find the Difference/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | char findTheDifference(string s, string t) { 9 | int sum1 = helper(s); 10 | int sum2 = helper(t); 11 | int diff = sum2 - sum1; 12 | return (char) diff; 13 | } 14 | 15 | private: 16 | int helper(string s) { 17 | int sum = 0; 18 | for(char c : s) { 19 | sum += c; 20 | } 21 | return sum; 22 | } 23 | }; 24 | 25 | int main() { 26 | // call the fn here 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /Medium/189. Rotate Array/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[] nums, int k) { 3 | int n=nums.length; 4 | k=k%nums.length; 5 | if(k<0){ 6 | k=k+nums.length; 7 | } 8 | int[] temp = new int[n]; 9 | // Copy elements to the temp array with the right shift 10 | for (int i = 0; i < n; i++) { 11 | temp[(i + k) % n] = nums[i]; 12 | } 13 | // Copy elements back to the original array 14 | for (int i = 0; i < n; i++) { 15 | nums[i] = temp[i]; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Medium/974. Subarray Sums Divisible by K/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subarraysDivByK(vector& nums, int k) { 4 | int n = nums.size(); 5 | unordered_map map; 6 | int sum = 0; 7 | int count = 0; 8 | for(int i = 0; i < n; i++) { 9 | sum += nums[i]; 10 | if(sum % k == 0) count++; 11 | int rem = sum % k; 12 | if(rem < 0) rem += k; 13 | if(map[rem]) count += map[rem]; 14 | map[rem] = map[rem] + 1; 15 | } 16 | return count; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Medium/134. Gas Station/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int canCompleteCircuit(int[] gas, int[] cost) { 3 | int sGas = 0, sCost = 0, res = 0, total = 0; 4 | for (int i = 0; i < gas.length; i++) { 5 | sGas += gas[i]; 6 | sCost += cost[i]; 7 | } 8 | if (sGas < sCost) return -1; 9 | for (int i = 0; i < gas.length; i++) { 10 | total += gas[i] - cost[i]; 11 | if (total < 0) { 12 | total = 0; 13 | res = i + 1; 14 | } 15 | } 16 | return res; 17 | } 18 | } -------------------------------------------------------------------------------- /Easy/145. Binary Tree Postorder Traversal/Solution.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * class TreeNode(var `val`: Int = 0) { 4 | * var left: TreeNode? = null 5 | * var right: TreeNode? = null 6 | * } 7 | */ 8 | class Solution { 9 | fun postorderTraversal(root: TreeNode?): List { 10 | val result = mutableListOf() 11 | if (root == null) return result 12 | 13 | result.addAll(postorderTraversal(root.left)) 14 | result.addAll(postorderTraversal(root.right)) 15 | result.add(root.`val`) 16 | 17 | return result 18 | } 19 | } -------------------------------------------------------------------------------- /Easy/101. Symmetric Tree/Solution.rb: -------------------------------------------------------------------------------- 1 | def is_symmetric(root) 2 | return true if root.nil? 3 | queue = [root.left, root.right] 4 | while !queue.empty? 5 | left = queue.shift 6 | right = queue.shift 7 | return false if left.nil? && !right.nil? || !left.nil? && right.nil? 8 | return false if !left.nil? && !right.nil? && left.val != right.val 9 | queue.push(left.left) if !left.nil? 10 | queue.push(right.right) if !right.nil? 11 | queue.push(left.right) if !left.nil? 12 | queue.push(right.left) if !right.nil? 13 | end 14 | true 15 | end 16 | -------------------------------------------------------------------------------- /Easy/108. Convert Sorted Array to Binary Search Tree/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* createBST(vector nums, int s, int e) { 4 | if (s > e) return NULL; 5 | 6 | int mid = s + (e - s) / 2; 7 | 8 | TreeNode* root = new TreeNode(nums[mid]); 9 | root->left = createBST(nums, s, mid - 1); 10 | root->right = createBST(nums, mid + 1, e); 11 | return root; 12 | } 13 | 14 | TreeNode* sortedArrayToBST(vector& nums) { 15 | int s = 0; 16 | int e = nums.size() - 1; 17 | return createBST(nums, s, e); 18 | } 19 | }; -------------------------------------------------------------------------------- /Easy/653. Two Sum IV - Input is a BST/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | Set set = new HashSet(); 3 | boolean exists = false; 4 | public boolean findTarget(TreeNode root, int k) { 5 | search(root, k); 6 | return exists; 7 | } 8 | 9 | public void search(TreeNode root, int k){ 10 | if(root == null || exists) return; 11 | if(set.contains(k - root.val)){ 12 | exists = true; 13 | return; 14 | } 15 | set.add(root.val); 16 | search(root.left, k); 17 | search(root.right, k); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Hard/34. Find First and Last Position of Element in Sorted Array/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchRange(self, N, T): 3 | Tleft = self.find(T, N, 0) 4 | if Tleft == len(N) or N[Tleft] != T: 5 | return [-1, -1] 6 | return [Tleft, self.find(T + 1, N, Tleft) - 1] 7 | 8 | def find(self, target, arr, left): 9 | right = len(arr) - 1 10 | while left <= right: 11 | mid = (left + right) // 2 12 | if arr[mid] < target: 13 | left = mid + 1 14 | else: 15 | right = mid - 1 16 | return left 17 | -------------------------------------------------------------------------------- /Medium/974. Subarray Sums Divisible by K/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subarraysDivByK(self, nums: List[int], k: int) -> int: 3 | n = len(nums) 4 | map = {} 5 | sum = 0 6 | count = 0 7 | for i in range(n): 8 | sum = sum + nums[i] 9 | if sum % k == 0: count = count + 1 10 | rem = sum % k 11 | if rem < 0: rem = rem + k 12 | if map.get(rem): 13 | count = count + map[rem] 14 | map[rem] = map[rem] + 1 15 | else: 16 | map[rem] = 1 17 | return count 18 | -------------------------------------------------------------------------------- /Easy/392. Is Subsequence/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | bool isSubsequence(string s, string t) { 9 | 10 | int n1 = s.length(); 11 | int n2 = t.length(); 12 | 13 | if(n1 < 1) return true; 14 | 15 | int i = 0; 16 | int j = 0; 17 | 18 | while(i < n2){ 19 | if(t[i] == s[j]){ 20 | j++; 21 | } 22 | i++; 23 | if(j == n1) return true; 24 | } 25 | 26 | return false; 27 | } 28 | }; 29 | 30 | int main() { 31 | 32 | // call the fn here 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /Medium/134.Gas Station/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int canCompleteCircuit(vector& gas, vector& cost) { 4 | int n = gas.size(); 5 | int total_surplus = 0; 6 | int surplus = 0; 7 | int start = 0; 8 | 9 | for(int i = 0; i < n; i++){ 10 | total_surplus += gas[i] - cost[i]; 11 | surplus += gas[i] - cost[i]; 12 | if(surplus < 0){ 13 | surplus = 0; 14 | start = i + 1; 15 | } 16 | } 17 | return (total_surplus < 0) ? -1 : start; 18 | } 19 | }; 20 | 21 | 22 | -------------------------------------------------------------------------------- /Easy/557. Reverse Words in a String III/README.md: -------------------------------------------------------------------------------- 1 | Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. 2 | 3 | 4 | 5 | Example 1: 6 | 7 | Input: s = "Let's take LeetCode contest" 8 | Output: "s'teL ekat edoCteeL tsetnoc" 9 | Example 2: 10 | 11 | Input: s = "God Ding" 12 | Output: "doG gniD" 13 | 14 | 15 | Constraints: 16 | 17 | 1 <= s.length <= 5 * 104 18 | s contains printable ASCII characters. 19 | s does not contain any leading or trailing spaces. 20 | There is at least one word in s. 21 | All the words in s are separated by a single space. -------------------------------------------------------------------------------- /Medium/12. Integer To Roman/Solution.js: -------------------------------------------------------------------------------- 1 | const intToRoman = (num) => { 2 | const numerals = { 3 | 1: 'I', 4 | 4: 'IV', 5 | 5: 'V', 6 | 9: 'IX', 7 | 10: 'X', 8 | 40: 'XL', 9 | 50: 'L', 10 | 90: 'XC', 11 | 100: 'C', 12 | 400: 'CD', 13 | 500: 'D', 14 | 900: 'CM', 15 | 1000: 'M', 16 | }; 17 | 18 | let romanized = ''; 19 | const decimalKeys = Object.keys(numerals).reverse(); 20 | 21 | decimalKeys.forEach((key) => { 22 | while (key <= num) { 23 | romanized = romanized + numerals[key]; 24 | num = num - key; 25 | } 26 | }); 27 | return romanized; 28 | }; 29 | 30 | console.log(intToRoman(112)); 31 | -------------------------------------------------------------------------------- /Medium/2038. Remove Colored Pieces if Both Neighbors are the Same Color/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool winnerOfGame(string colors) { 4 | map c; 5 | for (auto it = colors.begin(); it != colors.end(); ) { 6 | char x = *it; 7 | auto t = it; 8 | while (t != colors.end() && *t == x) { 9 | t++; 10 | } 11 | c[x] += max(int(distance(it, t) - 2), 0); 12 | it = t; 13 | } 14 | 15 | if (c['A'] > c['B']) { 16 | return true; 17 | } 18 | return false; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Easy/342. Power of Four/Approach 1/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfFour(int n) { 4 | // If 'n' is 1, it is a power of four 5 | if (n == 1) 6 | return true; 7 | 8 | // If 'n' is non-positive, it cannot be a power of four 9 | if (n <= 0) 10 | return false; 11 | 12 | // Calculate the logarithm of 'n' with base 4 13 | double logarithmBase4 = log(n) / log(4); 14 | 15 | // Check if the result of the logarithmic operation is an integer 16 | return (logarithmBase4 == (int)logarithmBase4); 17 | } 18 | }; -------------------------------------------------------------------------------- /Easy/905. Sort Array by Parity/sol.java: -------------------------------------------------------------------------------- 1 | public class sol{ 2 | public static void main(String[] args) { 3 | // call your fn here 4 | } 5 | } 6 | class Solution { 7 | public int[] sortArrayByParity(int[] nums) { 8 | int left = 0, right = 0; 9 | int n = nums.length; 10 | 11 | while (right < n) { 12 | if (nums[right] % 2 == 0) { 13 | int temp = nums[left]; 14 | nums[left] = nums[right]; 15 | nums[right] = temp; 16 | left++; 17 | } 18 | right++; 19 | } 20 | return nums; 21 | } 22 | } -------------------------------------------------------------------------------- /Hard/1269. Number of Ways to Stay in the Same Place After Some Steps/solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numWays(self, steps, arrLen): 3 | m = steps 4 | n = min(steps // 2 + 1, arrLen) 5 | 6 | dp = [[0] * n for _ in range(m + 1)] 7 | 8 | dp[0][0] = 1 9 | mod = 10 ** 9 + 7 10 | 11 | for i in range(1, m + 1): 12 | for j in range(n): 13 | dp[i][j] = dp[i-1][j] 14 | if j > 0: 15 | dp[i][j] += dp[i-1][j-1] 16 | if j < n - 1: 17 | dp[i][j] += dp[i-1][j+1] 18 | 19 | return dp[m][0] % mod -------------------------------------------------------------------------------- /Hard/42. Trapping Rain Water/Approach 1/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trap(self, height: List[int]) -> int: 3 | if not height: 4 | return 0 5 | n = len(height) 6 | lm = [0] * n 7 | rm = [0] * n 8 | 9 | lm[0] = height[0] 10 | for i in range(1, n): 11 | lm[i] = max(lm[i - 1], height[i]) 12 | 13 | rm[n - 1] = height[n - 1] 14 | for i in range(n - 2, -1, -1): 15 | rm[i] = max(rm[i + 1], height[i]) 16 | 17 | water = 0 18 | for i in range(n): 19 | water += min(lm[i], rm[i]) - height[i] 20 | 21 | return water -------------------------------------------------------------------------------- /Medium/2038. Remove Colored Pieces if/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool winnerOfGame(string colors) { 8 | int countA = 0; 9 | int countB = 0; 10 | 11 | for (int i = 1; i < colors.length() - 1; i++) { 12 | if (colors[i - 1] == colors[i] && colors[i] == colors[i + 1]) { 13 | if (colors[i] == 'A') { 14 | countA++; 15 | } else { 16 | countB++; 17 | } 18 | } 19 | } 20 | 21 | return countA > countB; 22 | } 23 | }; -------------------------------------------------------------------------------- /Easy/101. Symmetric Tree/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | 8 | class Solution: 9 | def isSymmetric(self, root: TreeNode) -> bool: 10 | def isMirror(p, q): 11 | if not p and not q: 12 | return True 13 | if not p or not q: 14 | return False 15 | return (p.val == q.val) and isMirror(p.left, q.right) and isMirror(p.right, q.left) 16 | 17 | return isMirror(root, root) 18 | -------------------------------------------------------------------------------- /Easy/342. Power of Four/Approach 1/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPowerOfFour(int n) { 3 | // If 'n' is 1, it is a power of four 4 | if (n == 1) 5 | return true; 6 | 7 | // If 'n' is non-positive, it cannot be a power of four 8 | if (n <= 0) 9 | return false; 10 | 11 | // Calculate the logarithm of 'n' with base 4 12 | double logarithmBase4 = Math.log(n) / Math.log(4); 13 | 14 | // Check if the result of the logarithmic operation is an integer 15 | return (logarithmBase4 == (int)logarithmBase4); 16 | } 17 | } -------------------------------------------------------------------------------- /Medium/343. Integer Break/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int integerBreak(int n) { 3 | if (n <= 1) { 4 | return 0; // We can't break integers less than or equal to 1. 5 | } 6 | 7 | if (n == 2) { 8 | return 1; // Special case: 1 * 1 is the only way to break 2. 9 | } 10 | 11 | if (n == 3) { 12 | return 2; // Special case: 1 * 2 is the only way to break 3. 13 | } 14 | 15 | int product = 1; 16 | 17 | while (n > 4) { 18 | product *= 3; 19 | n -= 3; 20 | } 21 | 22 | return product * n; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Easy/905. Sort Array by Parity/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector sortArrayByParity(vector& nums) { 9 | 10 | int left = 0, right = 0; 11 | int n = nums.size(); 12 | 13 | while (right < n) { 14 | if (nums[right] % 2 == 0) { 15 | int temp = nums[left]; 16 | nums[left] = nums[right]; 17 | nums[right] = temp; 18 | left++; 19 | } 20 | right++; 21 | } 22 | 23 | return nums; 24 | } 25 | }; 26 | 27 | int main() { 28 | 29 | // call the fn here 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /Easy/94. Binary Tree Inorder Traversal/Solution.rb: -------------------------------------------------------------------------------- 1 | class TreeNode 2 | attr_accessor :val, :left, :right 3 | def initialize(val = 0, left = nil, right = nil) 4 | @val = val 5 | @left = left 6 | @right = right 7 | end 8 | end 9 | 10 | def inorder_traversal(root) 11 | result = [] 12 | stack = [] 13 | current = root 14 | while current || stack.length > 0 15 | while current 16 | stack.push(current) 17 | current = current.left 18 | end 19 | current = stack.pop() 20 | result << current.val 21 | current = current.right 22 | end 23 | result 24 | end -------------------------------------------------------------------------------- /Easy/144. Binary Tree Preorder Traversal/Solution.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * class TreeNode(var `val`: Int) { 4 | * var left: TreeNode? = null 5 | * var right: TreeNode? = null 6 | * } 7 | */ 8 | class Solution { 9 | fun preorderTraversal(root: TreeNode?): List { 10 | val result = mutableListOf() 11 | helper(root, result) 12 | return result 13 | } 14 | 15 | fun helper(node: TreeNode?, result: MutableList) { 16 | if (node == null) return 17 | result.add(node.`val`) 18 | helper(node.left, result) 19 | helper(node.right, result) 20 | } 21 | } -------------------------------------------------------------------------------- /Medium/98. Valid BST/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void check(bool &firsttime, TreeNode* root, int &prev, bool &ans) { 4 | if (!ans) return; 5 | if (!root) return; 6 | check(firsttime, root->left, prev, ans); 7 | if (root->val <= prev && !firsttime) {ans = false; return;} 8 | else {prev = root->val; firsttime = false;} 9 | check(firsttime, root->right, prev, ans); 10 | } 11 | bool isValidBST(TreeNode* root) { 12 | int prev = INT_MIN; 13 | bool firsttime = true; 14 | bool ans = true; 15 | check(firsttime, root, prev, ans); 16 | return ans; 17 | } 18 | }; -------------------------------------------------------------------------------- /Easy/392. Is Subsequence/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | } 6 | 7 | class Solution { 8 | public boolean isSubsequence(String s, String t) { 9 | int n1 = s.length(); 10 | int n2 = t.length(); 11 | 12 | if (n1 < 1) 13 | return true; 14 | int i = 0; 15 | int j = 0; 16 | 17 | while (i < n2) { 18 | if (t.charAt(i) == s.charAt(j)) { 19 | j++; 20 | } 21 | i++; 22 | if (j == n1) 23 | return true; 24 | } 25 | return false; 26 | } 27 | } -------------------------------------------------------------------------------- /Medium/967. Numbers With Same Consecutive Differences/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numsSameConsecDiff(self, n: int, k: int) -> List[int]: 3 | list = [] 4 | min = pow(10, n - 1) 5 | for i in range (1, 10): 6 | q = [i] 7 | while len(q): 8 | num = q.pop(0) 9 | if num >= min: 10 | list.append(num) 11 | continue 12 | x = num % 10 13 | if k > 0 and x - k >= 0: 14 | q.append(num * 10 + x - k) 15 | if x + k < 10: 16 | q.append(num * 10 + x + k) 17 | return list 18 | -------------------------------------------------------------------------------- /Hard/115. Distinct Subsequences/Approach 1/solution.go: -------------------------------------------------------------------------------- 1 | func numDistinct(s string, t string) int { 2 | m := len(s) 3 | n := len(t) 4 | 5 | if m < n { 6 | return 0 7 | } 8 | 9 | dp := make([][]int, m+1) 10 | for i := range dp { 11 | dp[i] = make([]int, n+1) 12 | dp[i][0] = 1 13 | } 14 | 15 | for i := 1; i <= m; i++ { 16 | for j := 1; j <= n; j++ { 17 | if s[i-1] == t[j-1] { 18 | dp[i][j] = dp[i-1][j-1] + dp[i-1][j] 19 | } else { 20 | dp[i][j] = dp[i-1][j] 21 | } 22 | } 23 | } 24 | 25 | return dp[m][n] 26 | } 27 | -------------------------------------------------------------------------------- /Medium/341. Flatten Nested List Iterator/soln.py: -------------------------------------------------------------------------------- 1 | class NestedIterator: 2 | def __init__(self, nestedList): 3 | self.flatList = [] 4 | self.current = 0 5 | self.flatten(nestedList) 6 | 7 | def next(self): 8 | result = self.flatList[self.current] 9 | self.current += 1 10 | return result 11 | 12 | def hasNext(self): 13 | return self.current < len(self.flatList) 14 | 15 | def flatten(self, nestedList): 16 | for item in nestedList: 17 | if item.isInteger(): 18 | self.flatList.append(item.getInteger()) 19 | else: 20 | self.flatten(item.getList()) 21 | -------------------------------------------------------------------------------- /Easy/141. Linked List Cycle/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct ListNode { 5 | int val; 6 | ListNode *next; 7 | ListNode(int x) : val(x), next(NULL) {} 8 | }; 9 | 10 | class Solution { 11 | public: 12 | bool hasCycle(ListNode *head) { 13 | 14 | ListNode *slow = head; 15 | ListNode *fast = head; 16 | 17 | while (fast != NULL && fast->next != NULL) { 18 | slow = slow->next; 19 | fast = fast->next->next; 20 | 21 | if (fast == slow) { 22 | return true; 23 | } 24 | } 25 | 26 | return false; 27 | } 28 | }; 29 | 30 | int main() { 31 | // test Solution::hasCycle 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Medium/974. Subarray Sums Divisible by K/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subarraysDivByK(int[] arr, int k) { 3 | int n = arr.length; 4 | HashMap map = new HashMap<>(); 5 | int sum = 0; 6 | int count = 0; 7 | for(int i = 0; i= 0){ 11 | char ch = s.charAt(i); 12 | if(ch == ' ' && count == 0){ 13 | i--; 14 | continue; 15 | } 16 | if(ch != ' '){ 17 | count++; 18 | i--; 19 | } else{ 20 | return count; 21 | } 22 | } 23 | return count; 24 | } 25 | } -------------------------------------------------------------------------------- /Easy/896. Monotonic Array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | bool isMonotonic(vector& nums) { 9 | 10 | if (nums[0] < nums[nums.size()-1]) { 11 | for (int i = 1; i < nums.size(); i++) { 12 | if (nums[i] < nums[i-1]) { 13 | return false; 14 | } 15 | } 16 | } else { 17 | for (int i = 1; i < nums.size(); i++) { 18 | if (nums[i] > nums[i-1]) { 19 | return false; 20 | } 21 | } 22 | } 23 | 24 | return true; 25 | } 26 | }; 27 | 28 | int main() { 29 | 30 | //call your fn here 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /Easy/896. Monotonic Array/sol.java: -------------------------------------------------------------------------------- 1 | public class sol{ 2 | public static void main(String[] args) { 3 | // call your fn here 4 | } 5 | } 6 | class Solution { 7 | public boolean isMonotonic(int[] nums) { 8 | if (nums[0] < nums[nums.length-1]) { 9 | for (int i = 1; i < nums.length; i++) { 10 | if (nums[i] < nums[i-1]) { 11 | return false; 12 | } 13 | } 14 | } else { 15 | for (int i = 1; i < nums.length; i++) { 16 | if (nums[i] > nums[i-1]) { 17 | return false; 18 | } 19 | } 20 | } 21 | return true; 22 | } 23 | } -------------------------------------------------------------------------------- /Medium/34. First and Last Position of Element in an Array/New Approach/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] searchRange(int[] nums, int target) { 3 | 4 | int n=nums.length; 5 | int arr[] =new int[2]; 6 | int arr1[] =new int[]{-1,-1}; 7 | arr[0] = -1; arr[1] = -1; 8 | for (int i = 0; i < n; i++) { 9 | if (target != nums[i]) 10 | continue; 11 | if (arr[0] == -1) 12 | arr[0] = i; 13 | arr[1] = i; 14 | } 15 | if (arr[0] != -1) { 16 | return arr; 17 | 18 | } 19 | else 20 | return arr1; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Medium/48. Rotate Image/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[][] matrix) { 3 | for(int i = 0; i < matrix.length; i++){ 4 | for(int j = i; j < matrix[0].length; j++){ 5 | int t = matrix[i][j]; 6 | matrix[i][j] = matrix[j][i]; 7 | matrix[j][i] = t; 8 | } 9 | } 10 | 11 | for(int i = 0; i < matrix.length; i++){ 12 | for(int j = 0; j < matrix.length/2; j++){ 13 | int t = matrix[i][j]; 14 | matrix[i][j] = matrix[i][matrix.length - 1 - j]; 15 | matrix[i][matrix.length - 1 - j] = t; 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Easy/14. Longest Common Prefix/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String longestCommonPrefix(String[] strs) { 3 | int k=0; 4 | String result= ""; 5 | for(int i=0;i 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | long long minimumReplacement(vector &nums) 10 | { 11 | 12 | long long ops = 0; 13 | long long prev = nums.back(); 14 | 15 | for (int i = nums.size() - 2; i >= 0; i--) 16 | { 17 | 18 | long long num = nums[i]; 19 | long long times = (num + prev - 1) / prev; 20 | ops += times - 1; 21 | 22 | prev = num / times; 23 | } 24 | 25 | return ops; 26 | } 27 | }; 28 | 29 | int main() 30 | { 31 | // call the fn here 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Easy/141.Linked List Cycle/solution.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | 10 | 11 | class Solution { 12 | public: 13 | bool hasCycle(ListNode *head) { 14 | ListNode *slow_pointer = head, *fast_pointer = head; 15 | while (fast_pointer != nullptr && fast_pointer->next != nullptr) { 16 | slow_pointer = slow_pointer->next; 17 | fast_pointer = fast_pointer->next->next; 18 | if (slow_pointer == fast_pointer) { 19 | return true; 20 | } 21 | } 22 | return false; 23 | } 24 | }; -------------------------------------------------------------------------------- /Hard/2366. Min Replacements to Sort an Array/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | public class Solution { 7 | public long minimumReplacement(int[] nums) { 8 | long operations = 0; 9 | long prev_bound = nums[nums.length - 1]; 10 | 11 | for (int i = nums.length - 2; i >= 0; i--) { 12 | long num = nums[i]; 13 | long no_of_times = (num + prev_bound - 1) / prev_bound; 14 | operations += no_of_times - 1; 15 | prev_bound = num / no_of_times; 16 | } 17 | 18 | return operations; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Easy/119. Pascal's Triangle II/solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getRow(self, rowIndex): 3 | 4 | pascal_triangle = [[] for _ in range(rowIndex + 1)] 5 | 6 | pascal_triangle[0].append(1) 7 | 8 | 9 | for current_row in range(1, rowIndex + 1): 10 | 11 | pascal_triangle[current_row].append(1) 12 | 13 | for j in range(1, len(pascal_triangle[current_row - 1])): 14 | sum_val = pascal_triangle[current_row - 1][j] + pascal_triangle[current_row - 1][j - 1] 15 | pascal_triangle[current_row].append(sum_val) 16 | 17 | pascal_triangle[current_row].append(1) 18 | 19 | return pascal_triangle[rowIndex] -------------------------------------------------------------------------------- /Medium/1996. The Number of Weak Characters in the Game/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static bool compare(vector& a, vector& b){ 4 | if(a[0] == b[0]) 5 | return a[1] < b[1]; 6 | return a[0] > b[0]; 7 | } 8 | 9 | int numberOfWeakCharacters(vector>& properties) { 10 | int n = properties.size(); 11 | int count = 0; 12 | sort(properties.begin(), properties.end(), compare); 13 | int maxN = INT_MIN; 14 | for(int i = 0; i < n; i++){ 15 | if(properties[i][1] < maxN) 16 | count++; 17 | maxN = max(maxN, properties[i][1]); 18 | } 19 | return count; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Medium/48. Rotate Image/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector>& matrix) { 4 | for(int i = 0; i < matrix.size(); i++){ 5 | for(int j = i; j < matrix[0].size(); j++){ 6 | int t = matrix[i][j]; 7 | matrix[i][j] = matrix[j][i]; 8 | matrix[j][i] = t; 9 | } 10 | } 11 | 12 | for(int i = 0; i < matrix.size(); i++){ 13 | for(int j = 0; j < matrix.size()/2; j++){ 14 | int t = matrix[i][j]; 15 | matrix[i][j] = matrix[i][matrix.size() - 1 - j]; 16 | matrix[i][matrix.size() - 1 - j] = t; 17 | } 18 | } 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Easy/342. Power of Four/Approach 1/Readme.md: -------------------------------------------------------------------------------- 1 | 2 | +Check if the input integer n is equal to 1. If it is, return true since 1 is a power of four. 3 | +If n is non-positive (less than or equal to 0), return false since powers of four are positive integers. 4 | +Calculate the logarithm of 'n' with a base of 4 and store the result in the variable 'logarithmBase4.' 5 | +Check if 'logarithmBase4' is an integer by comparing it to its integer cast. If they are equal, return true; otherwise, return false. 6 | 7 | Complexity 8 | 9 | --Time complexity: O(1)O(1)O(1) 10 | Since we are only doing math operations without any loops or recursion. 11 | --Space complexity: O(1)O(1)O(1) 12 | Since we are only storing constant variables. 13 | -------------------------------------------------------------------------------- /Medium/287. Find Duplicate Number/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int findDuplicate(vector &nums) 10 | { 11 | 12 | int slow = nums[0]; 13 | int fast = nums[0]; 14 | 15 | do 16 | { 17 | slow = nums[slow]; 18 | fast = nums[nums[fast]]; 19 | } while (slow != fast); 20 | 21 | fast = nums[0]; 22 | 23 | while (slow != fast) 24 | { 25 | slow = nums[slow]; 26 | fast = nums[fast]; 27 | } 28 | 29 | return slow; 30 | } 31 | }; 32 | 33 | int main() 34 | { 35 | 36 | // call the fn here 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Hard/273. Integer to English Words/README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 273. Integer to English Words 2 | 3 | ## Problem Description 4 | Convert a non-negative integer num to its English words representation. 5 | 6 | ## Test Cases 7 | 8 | ### Example 1: 9 | 10 | - **Input:** `num = 123` 11 | - **Output:** `One Hundred Twenty Three` 12 | 13 | ### Example 2: 14 | 15 | - **Input:** `num = 12345` 16 | - **Output:** `Twelve Thousand Three Hundred Forty Five` 17 | 18 | ### Example 3: 19 | 20 | - **Input:** `num = 1234567` 21 | - **Output:** `One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven` 22 | 23 | ### Constraints: 24 | 25 | `0 <= num <= 231 - 1` 26 | 27 | ### Link 28 | 29 | https://leetcode.com/problems/integer-to-english-words/ 30 | -------------------------------------------------------------------------------- /Medium/287. Find Duplicate Number/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int findDuplicate(int[] arr) { 8 | int slowPtr = arr[0]; 9 | int fastPtr = arr[0]; 10 | 11 | do { 12 | fastPtr = arr[arr[fastPtr]]; 13 | slowPtr = arr[slowPtr]; 14 | } while (fastPtr != slowPtr); 15 | 16 | fastPtr = arr[0]; 17 | 18 | while (fastPtr != slowPtr) { 19 | fastPtr = arr[fastPtr]; 20 | slowPtr = arr[slowPtr]; 21 | } 22 | 23 | return fastPtr; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Medium/7. Reverse Integer/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int reverse(int x) 10 | { 11 | 12 | string s = to_string(x); 13 | 14 | string reversed; 15 | int start = s[0] == '-' ? 1 : 0; 16 | 17 | for (int i = s.length() - 1; i >= start; i--) 18 | { 19 | reversed += s[i]; 20 | } 21 | 22 | try 23 | { 24 | return x >= 0 ? stoi(reversed) : -stoi(reversed); 25 | } 26 | catch (exception e) 27 | { 28 | return 0; 29 | } 30 | } 31 | }; 32 | 33 | int main() 34 | { 35 | // call the fn here 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Easy/637. Average of Levels in Binary Tree/Solution.cpp: -------------------------------------------------------------------------------- 1 | // Breadth First Search 2 | class Solution { 3 | public: 4 | vector averageOfLevels(TreeNode* root) { 5 | vector list; 6 | queue q; 7 | q.push(root); 8 | while(!q.empty()){ 9 | int n = q.size(); 10 | double sum = 0.0; 11 | for(int i = 0; i < n; i++){ 12 | TreeNode* node = q.front(); 13 | q.pop(); 14 | sum += node->val; 15 | if(node->left) q.push(node->left); 16 | if(node->right) q.push(node->right); 17 | } 18 | list.push_back(sum/n); 19 | } 20 | return list; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Hard/2227. Encrypt and Decrypt String/solution.py: -------------------------------------------------------------------------------- 1 | class Encrypter: 2 | 3 | def __init__(self, keys: List[str], values: List[str], dictionary: List[str]): 4 | self.ktov = {} 5 | 6 | for k, v in zip(keys, values): 7 | self.ktov[k] = v 8 | 9 | self.count = Counter(self.encrypt(x) for x in dictionary) 10 | 11 | 12 | def encrypt(self, word1: str) -> str: 13 | res = [] 14 | 15 | for x in word1: 16 | if x in self.ktov: 17 | res.append(self.ktov[x]) 18 | else: 19 | return "" 20 | 21 | return "".join(res) 22 | 23 | def decrypt(self, word2: str) -> int: 24 | return self.count[word2] -------------------------------------------------------------------------------- /Medium/179. Largest Number/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class sol { 4 | public static void main(String[] args) { 5 | // call the fn here 6 | } 7 | 8 | class Solution { 9 | public String largestNumber(int[] nums) { 10 | String ans = ""; 11 | ArrayList list = new ArrayList<>(); 12 | 13 | for (int i = 0; i < nums.length; i++) { 14 | list.add(String.valueOf(nums[i])); 15 | } 16 | 17 | Collections.sort(list, (a, b) -> (b + a).compareTo(a + b)); 18 | 19 | for (String s : list) { 20 | ans += s; 21 | } 22 | 23 | return ans.charAt(0) == '0' ? "0" : ans; 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /Easy/141. Linked List Cycle/sol.java: -------------------------------------------------------------------------------- 1 | 2 | class ListNode { 3 | int val; 4 | ListNode next; 5 | 6 | ListNode(int x) { 7 | val = x; 8 | next = null; 9 | } 10 | } 11 | 12 | public class sol { 13 | public static void main(String[] args) { 14 | // call your fn here 15 | } 16 | } 17 | 18 | class Solution { 19 | public boolean hasCycle(ListNode head) { 20 | 21 | ListNode slow = head; 22 | ListNode fast = head; 23 | 24 | while (fast != null && fast.next != null) { 25 | slow = slow.next; 26 | fast = fast.next.next; 27 | 28 | if (fast == slow) { 29 | return true; 30 | } 31 | } 32 | return false; 33 | } 34 | } -------------------------------------------------------------------------------- /Medium/2038. Remove Colored Pieces if Both Neighbors are the Same Color/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean winnerOfGame(String colors) { 3 | Map c = new HashMap<>(); 4 | c.put('A', 0); 5 | c.put('B', 0); 6 | 7 | for (int i = 0; i < colors.length(); i++) { 8 | char x = colors.charAt(i); 9 | int count = 0; 10 | 11 | while (i < colors.length() && colors.charAt(i) == x) { 12 | i++; 13 | count++; 14 | } 15 | 16 | c.put(x, c.get(x) + Math.max(count - 2, 0)); 17 | i--; 18 | } 19 | 20 | return c.get('A') > c.get('B'); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Easy/141.Linked List Cycle/solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | 13 | 14 | 15 | public class Solution { 16 | public boolean hasCycle(ListNode head) { 17 | ListNode slow_pointer = head, fast_pointer = head; 18 | while (fast_pointer != null && fast_pointer.next != null) { 19 | slow_pointer = slow_pointer.next; 20 | fast_pointer = fast_pointer.next.next; 21 | if (slow_pointer == fast_pointer) { 22 | return true; 23 | } 24 | } 25 | return false; 26 | } 27 | } -------------------------------------------------------------------------------- /Easy/2373. Largest Local Values in a Matrix/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] largestLocal(int[][] grid) { 3 | int n=grid.length; 4 | 5 | int[][] ans=new int[n-2][n-2]; 6 | 7 | for(int i=0;i averageOfLevels(TreeNode root) { 4 | List list = new ArrayList(); 5 | Queue q = new LinkedList(); 6 | q.add(root); 7 | while(!q.isEmpty()){ 8 | int n = q.size(); 9 | double sum = 0.0; 10 | for(int i = 0; i < n; i++){ 11 | TreeNode curr = q.poll(); 12 | sum += curr.val; 13 | if(curr.left != null) q.add(curr.left); 14 | if(curr.right != null) q.add(curr.right); 15 | } 16 | list.add(sum/n); 17 | } 18 | return list; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Easy/88. Merge Sorted Array/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void merge(vector &nums1, int m, vector &nums2, int n) 5 | { 6 | int i = m - 1; 7 | int j = n - 1; 8 | int k = m + n - 1; 9 | 10 | while (i >= 0 && j >= 0) 11 | { 12 | if (nums1[i] > nums2[j]) 13 | { 14 | nums1[k] = nums1[i]; 15 | i--; 16 | } 17 | else 18 | { 19 | nums1[k] = nums2[j]; 20 | j--; 21 | } 22 | k--; 23 | } 24 | 25 | while (j >= 0) 26 | { 27 | nums1[k] = nums2[j]; 28 | k--; 29 | j--; 30 | } 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Hard/1458. Max Dot Product of Two Subsequences/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int: 3 | n, m = len(nums1), len(nums2) 4 | memo = [[float('-inf')] * m for _ in range(n)] 5 | 6 | def dp(i, j): 7 | if i == n or j == m: 8 | return float('-inf') 9 | 10 | if memo[i][j] != float('-inf'): 11 | return memo[i][j] 12 | 13 | memo[i][j] = max( 14 | nums1[i] * nums2[j] + max(dp(i + 1, j + 1), 0), 15 | dp(i + 1, j), 16 | dp(i, j + 1), 17 | ) 18 | 19 | return memo[i][j] 20 | 21 | return dp(0, 0) -------------------------------------------------------------------------------- /Easy/108. Convert Sorted Array to Binary Search Tree/Solution.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, val=0, left=None, right=None): 3 | self.val = val 4 | self.left = left 5 | self.right = right 6 | 7 | class Solution: 8 | def sortedArrayToBST(self, nums): 9 | if not nums: 10 | return None 11 | head = self.helper(nums, 0, len(nums) - 1) 12 | return head 13 | 14 | def helper(self, nums, low, high): 15 | if low > high: 16 | return None 17 | mid = low + (high - low) // 2 18 | node = TreeNode(nums[mid]) 19 | node.left = self.helper(nums, low, mid - 1) 20 | node.right = self.helper(nums, mid + 1, high) 21 | return node 22 | 23 | -------------------------------------------------------------------------------- /Hard/135. Candy/Approach 1/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int candy(std::vector& ratings) { 4 | int n = ratings.size(); 5 | std::vector candies(n, 1); 6 | 7 | for (int i = 1; i < n; ++i) { 8 | if (ratings[i] > ratings[i - 1]) { 9 | candies[i] = candies[i - 1] + 1; 10 | } 11 | } 12 | 13 | for (int i = n - 2; i >= 0; --i) { 14 | if (ratings[i] > ratings[i + 1]) { 15 | candies[i] = std::max(candies[i], candies[i + 1] + 1); 16 | } 17 | } 18 | 19 | int totalCandies = 0; 20 | for (int candy : candies) { 21 | totalCandies += candy; 22 | } 23 | 24 | return totalCandies; 25 | } 26 | }; -------------------------------------------------------------------------------- /Medium/62. Unique Paths/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int uniquePaths(int m, int n) { 8 | int[][] temp = new int[m][n]; 9 | 10 | for (int i = 0; i < m; i++) { 11 | temp[i][0] = 1; 12 | } 13 | for (int j = 0; j < n; j++) { 14 | temp[0][j] = 1; 15 | } 16 | 17 | for (int i = 1; i < m; i++) { 18 | for (int j = 1; j < n; j++) { 19 | temp[i][j] = temp[i - 1][j] + temp[i][j - 1]; 20 | } 21 | } 22 | 23 | return temp[m - 1][n - 1]; 24 | } 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Hard/2251. Number Of Flowers In Full Bloom/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector fullBloomFlowers(vector>& flowers, vector& persons) { 4 | 5 | vector start, end; 6 | 7 | for (auto& t : flowers) 8 | start.push_back(t[0]), end.push_back(t[1]); 9 | 10 | sort(start.begin(), start.end()); 11 | sort(end.begin(), end.end()); 12 | vector res; 13 | 14 | for (int t : persons) { 15 | 16 | int started = upper_bound(start.begin(), start.end(), t) - start.begin(); 17 | int ended = lower_bound(end.begin(), end.end(), t) - end.begin(); 18 | res.push_back(started - ended); 19 | 20 | } 21 | 22 | return res; 23 | 24 | } 25 | }; -------------------------------------------------------------------------------- /Medium/1647. Min Deletions to Make Char Frequencies Unique/sol.md: -------------------------------------------------------------------------------- 1 | Create an array to store the frequency of each character in the string. 2 | Sort the frequencies in ascending order. 3 | Initialize the deletion count to zero. 4 | Iterate over the frequencies in reverse order. 5 | If the current frequency is equal to or greater than the next frequency, then decrement the current frequency by the maximum of zero and the next frequency minus one. Update the deletion count by the difference between the previous and current frequencies. 6 | Return the deletion count. 7 | 8 | 9 | his algorithm works by greedily reducing the frequency of the most common characters until all frequencies are distinct. This ensures that the minimum number of deletions is required to achieve a unique frequency distribution. -------------------------------------------------------------------------------- /Medium/2038. Remove Colored Pieces if/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public boolean winnerOfGame(String colors) { 8 | int countA = 0; 9 | int countB = 0; 10 | for (int i = 1; i < colors.length() - 1; i++) { 11 | if (colors.charAt(i - 1) == colors.charAt(i) && colors.charAt(i) == colors.charAt(i + 1)) { 12 | if (colors.charAt(i) == 'A') { 13 | countA++; 14 | } else { 15 | countB++; 16 | } 17 | } 18 | } 19 | return countA > countB; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /Hard/115. Distinct Subsequences/Approach 1/solution.scala: -------------------------------------------------------------------------------- 1 | object Solution { 2 | def numDistinct(s: String, t: String): Int = { 3 | val m = s.length 4 | val n = t.length 5 | 6 | if (m < n) { 7 | return 0 8 | } 9 | 10 | val dp: Array[Array[Int]] = Array.fill(m + 1, n + 1)(0) 11 | for (i <- 0 to m) { 12 | dp(i)(0) = 1 13 | } 14 | 15 | for (i <- 1 to m) { 16 | for (j <- 1 to n) { 17 | if (s(i-1) == t(j-1)) { 18 | dp(i)(j) = dp(i-1)(j-1) + dp(i-1)(j) 19 | } else { 20 | dp(i)(j) = dp(i-1)(j) 21 | } 22 | } 23 | } 24 | 25 | dp(m)(n) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Medium/19. Remove nth Node From the End/sol.md: -------------------------------------------------------------------------------- 1 | 1. Create a dummy node and set its next pointer to the head of the linked list. 2 | 2. Initialize two pointers, `first` and `second`, to the dummy node. 3 | 3. Advance the `first` pointer `n + 1` nodes forward. 4 | 4. While the `first` pointer is not null: 5 | * Advance both the `first` and `second` pointers one node forward. 6 | 5. Set the `next` pointer of the `second` node to the `next` pointer of the `second.next` node. 7 | 6. Return the next pointer of the dummy node. 8 | 9 | The time complexity of the algorithm is O(n), where n is the length of the linked list. This is because the algorithm needs to traverse the linked list twice. 10 | 11 | The space complexity of the algorithm is O(1), since it only needs to store three pointers. 12 | -------------------------------------------------------------------------------- /Hard/135. Candy/Approach 1/sloution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int candy(int[] ratings) { 3 | int n = ratings.length; 4 | int[] candies = new int[n]; 5 | Arrays.fill(candies, 1); 6 | 7 | for (int i = 1; i < n; i++) { 8 | if (ratings[i] > ratings[i - 1]) { 9 | candies[i] = candies[i - 1] + 1; 10 | } 11 | } 12 | 13 | for (int i = n - 2; i >= 0; i--) { 14 | if (ratings[i] > ratings[i + 1]) { 15 | candies[i] = Math.max(candies[i], candies[i + 1] + 1); 16 | } 17 | } 18 | 19 | int totalCandies = 0; 20 | for (int candy : candies) { 21 | totalCandies += candy; 22 | } 23 | 24 | return totalCandies; 25 | } 26 | } -------------------------------------------------------------------------------- /Hard/920. Number of Music Playlists/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int numMusicPlaylists(int n, int goal, int k) { 9 | const int MOD = 1000000007; 10 | vector> temp(goal + 1, vector(n + 1, 0)); 11 | temp[0][0] = 1; 12 | 13 | for (int i = 1; i <= goal; i++) { 14 | for (int j = 1; j <= n; j++) { 15 | temp[i][j] = (temp[i][j] + temp[i - 1][j - 1] * (n - j + 1)) % MOD; 16 | if (j > k) { 17 | temp[i][j] = (temp[i][j] + temp[i - 1][j] * (j - k)) % MOD; 18 | } 19 | } 20 | } 21 | 22 | return static_cast(temp[goal][n]); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Medium/2. Add Two Numbers/Approach 1/Readme.md: -------------------------------------------------------------------------------- 1 | It's time to sum up these node value, for that we will create one another variable let's called it sum and put the sum of l1 & l2 them into our dummy list. So, we start it from all the way left go to all the way right. 2 | Now you will ask, dude what about the carry values we get after sum up. 3 | Well, hold on i'm coming on that point don't worry. 4 | 5 | So, for that what you have to do is, we will intialize one more variable name carry if we found carry of let's say 10. First we will modulo it like carry = sum % 10 i.e. carry = 10 % 10 i.e. 0 we will add 0 into our node and after that what we will do is get the carry as carry = sum / 10 i.e. carry = 10 / 10 i.e. 1. Now we are having carry as 1. So, in the next node sum of l1 & l2 we will add carry as well. -------------------------------------------------------------------------------- /Medium/341. Flatten Nested List Iterator/soln.cpp: -------------------------------------------------------------------------------- 1 | class NestedIterator { 2 | public: 3 | NestedIterator(vector &nestedList) { 4 | flatten(nestedList); 5 | current = 0; 6 | } 7 | 8 | int next() { 9 | return flatList[current++]; 10 | } 11 | 12 | bool hasNext() { 13 | return current < flatList.size(); 14 | } 15 | 16 | private: 17 | vector flatList; 18 | int current; 19 | 20 | void flatten(const vector& nestedList) { 21 | for (const auto &item : nestedList) { 22 | if (item.isInteger()) { 23 | flatList.push_back(item.getInteger()); 24 | } else { 25 | flatten(item.getList()); 26 | } 27 | } 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Medium/853. Car Fleet/Solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} target 3 | * @param {number[]} position 4 | * @param {number[]} speed 5 | * @return {number} 6 | */ 7 | 8 | var carFleet = function (target, position, speed) { 9 | const n = position.length; 10 | if (n === 1) return 1; 11 | 12 | const cars = new Array(n); 13 | for (let i = 0; i < n; i++) cars[i] = i; 14 | cars.sort((a, b) => position[b] - position[a]); 15 | 16 | const timeNeeded = (carIndex) => { 17 | return (target - position[cars[carIndex]]) / speed[cars[carIndex]]; 18 | }; 19 | 20 | let counter = 1; 21 | let leader = 0; 22 | for (let i = 1; i < n; i++) { 23 | if (timeNeeded(i) > timeNeeded(leader)) { 24 | leader = i; 25 | counter++; 26 | } 27 | } 28 | return counter; 29 | }; 30 | -------------------------------------------------------------------------------- /Easy/1672. Richest Customer Wealth/Solution.java: -------------------------------------------------------------------------------- 1 | // Using Steam API 2 | class Solution { 3 | public int maximumWealth(int[][] accounts) { 4 | int max = 0; 5 | for(int[] account: accounts){ 6 | max = Math.max(max, Arrays.stream(account).sum()); 7 | } 8 | return max; 9 | } 10 | } 11 | 12 | // Using for loop 13 | class Solution { 14 | public int maximumWealth(int[][] accounts) { 15 | int max = 0; 16 | 17 | for(int i = 0; i < accounts.length; i++){ 18 | int sum = 0; 19 | for(int j = 0; j < accounts[i].length; j++){ 20 | sum += accounts[i][j]; 21 | } 22 | max = max > sum ? max : sum; 23 | } 24 | 25 | return max; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Medium/179. Largest Number/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | string largestNumber(vector &nums) 11 | { 12 | 13 | vector strNums; 14 | for (int num : nums) 15 | { 16 | strNums.push_back(to_string(num)); 17 | } 18 | 19 | sort(strNums.begin(), strNums.end(), [](string &a, string &b) 20 | { return a + b > b + a; }); 21 | 22 | string ans; 23 | for (string s : strNums) 24 | { 25 | ans += s; 26 | } 27 | 28 | return ans[0] == '0' ? "0" : ans; 29 | } 30 | }; 31 | 32 | int main() 33 | { 34 | 35 | // call the fn here 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /Medium/7. Reverse Integer/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int reverse(int x) { 8 | String s = String.valueOf(x); 9 | StringBuilder reversed = new StringBuilder(); 10 | 11 | int start = s.charAt(0) == '-' ? 1 : 0; 12 | 13 | for (int i = s.length() - 1; i >= start; i--) { 14 | reversed.append(s.charAt(i)); 15 | } 16 | 17 | try { 18 | return x >= 0 ? Integer.parseInt(reversed.toString()) : -Integer.parseInt(reversed.toString()); 19 | } catch (NumberFormatException e) { 20 | return 0; 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Easy/121. Best Time to buy and sell stock/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxProfit(int[] prices) { 3 | 4 | int minprice = Integer.MAX_VALUE; 5 | int maxprofit = 0; 6 | 7 | // Iterate through the array of stock prices. 8 | for (int i=0;i maxprofit) 13 | 14 | // Calculate and update the maximum profit. 15 | maxprofit = prices[i] - minprice; 16 | } 17 | // Return the maximum profit. 18 | return maxprofit; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Easy/58. Length of Last Word/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int lengthOfLastWord(string s) { 9 | 10 | int count = 0; 11 | int i = s.length() - 1; 12 | 13 | while(i >= 0) { 14 | char ch = s[i]; 15 | 16 | if(ch == ' ' && count == 0) { 17 | i--; 18 | continue; 19 | } 20 | 21 | if(ch != ' ') { 22 | count++; 23 | i--; 24 | } else { 25 | return count; 26 | } 27 | } 28 | 29 | return count; 30 | } 31 | }; 32 | 33 | int main() { 34 | string s = "Hello World"; 35 | 36 | Solution sol; 37 | int result = sol.lengthOfLastWord(s); 38 | 39 | cout << result << endl; 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /Medium/560. Subarray Sum Equals K/readme.md: -------------------------------------------------------------------------------- 1 | # Subarray Sum Equals K 2 | 3 | ## Problem 4 | 5 | Given an array of integers `nums` and an integer `k`, the task is to find and return the total number of subarrays whose sum is equal to `k`. A subarray is a contiguous non-empty sequence of elements within the array. 6 | 7 | ### Example 8 | 9 | #### Input 10 | 11 | ```javascript 12 | const nums = [1, 1, 1]; 13 | const k = 2; 14 | console.log(subarraySum(nums, k)); // Output: 2 15 | ``` 16 | 17 | The solution uses a hash table to keep track of cumulative sums. It iterates through the array, updating the cumulative sum and checking if there are subarrays with a sum of (current_sum - k). The count of such subarrays is accumulated, and the hash table is updated with the current cumulative sum. 18 | -------------------------------------------------------------------------------- /Hard/34. Find First and Last Position of Element in Sorted Array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Solution { 4 | public: 5 | std::vector searchRange(std::vector& N, int T) { 6 | int Tleft = find(T, N, 0); 7 | if (Tleft == N.size() || N[Tleft] != T) { 8 | return {-1, -1}; 9 | } 10 | return {Tleft, find(T + 1, N, Tleft) - 1}; 11 | } 12 | 13 | int find(int target, std::vector& arr, int left) { 14 | int right = arr.size() - 1; 15 | while (left <= right) { 16 | int mid = left + (right - left) / 2; 17 | if (arr[mid] < target) { 18 | left = mid + 1; 19 | } else { 20 | right = mid - 1; 21 | } 22 | } 23 | return left; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Easy/706. Design HashMap/solution.js: -------------------------------------------------------------------------------- 1 | 2 | var MyHashMap = function() { 3 | object = {}; 4 | }; 5 | 6 | /** 7 | * @param {number} key 8 | * @param {number} value 9 | * @return {void} 10 | */ 11 | MyHashMap.prototype.put = function(key, value) { 12 | object[key] = value; 13 | }; 14 | 15 | /** 16 | * @param {number} key 17 | * @return {number} 18 | */ 19 | MyHashMap.prototype.get = function(key) { 20 | return object[key] ?? -1; 21 | }; 22 | 23 | /** 24 | * @param {number} key 25 | * @return {void} 26 | */ 27 | MyHashMap.prototype.remove = function(key) { 28 | delete object[key] 29 | }; 30 | 31 | /** 32 | * Your MyHashMap object will be instantiated and called as such: 33 | * var obj = new MyHashMap() 34 | * obj.put(key,value) 35 | * var param_2 = obj.get(key) 36 | * obj.remove(key) 37 | */ -------------------------------------------------------------------------------- /Medium/22. Generate Parentheses/README.md: -------------------------------------------------------------------------------- 1 |

22. Generate Parentheses

Medium

2 |

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

3 | 4 |

 

5 |

Example 1:

6 |
Input: n = 3
 7 | Output: ["((()))","(()())","(())()","()(())","()()()"]
 8 | 

Example 2:

9 |
Input: n = 1
10 | Output: ["()"]
11 | 
12 |

 

13 |

Constraints:

14 | 15 |
    16 |
  • 1 <= n <= 8
  • 17 |
18 |
-------------------------------------------------------------------------------- /Medium/36. Valid Sudoku/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isValidSudoku(char[][] board) { 3 | for(int i = 0; i < 9; i++){ 4 | Set row = new HashSet(); 5 | Set col = new HashSet(); 6 | Set sqr = new HashSet(); 7 | for(int j = 0; j < 9; j++){ 8 | if(board[i][j] != '.' && !row.add(board[i][j])) return false; 9 | if(board[j][i] != '.' && !col.add(board[j][i])) return false; 10 | int rowIdx = 3*(i/3); 11 | int colIdx = 3*(i%3); 12 | if(board[rowIdx + j/3][colIdx + j%3] != '.' && !sqr.add(board[rowIdx + j/3][colIdx + j%3])) return false; 13 | } 14 | } 15 | return true; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Easy/169. Majority Element/solution.md: -------------------------------------------------------------------------------- 1 | # PROBLEM 2 | 3 | Given an array nums of size n, return the majority element. 4 | 5 | The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. 6 | 7 | # EXPLANATION 8 | 9 | 1. The code begins by sorting the array nums in non-decreasing order using the sort function from the C++ Standard Library. This rearranges the elements such that identical elements are grouped together. 10 | 11 | 2. Once the array is sorted, the majority element will always be present at index n/2, where n is the size of the array. 12 | This is because the majority element occurs more than n/2 times, and when the array is sorted, it will occupy the middle position. 13 | 14 | 3. The code returns the element at index n/2 as the majority element. -------------------------------------------------------------------------------- /Easy/326. Power of Three/README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 326. Power of three 2 | 3 | ## Problem Description 4 | Given an integer `n`, return `true` if it is a power of three. Otherwise, return `false`. 5 | 6 | An integer n is a power of three, if there exists an integer `x` such that `n == 3x`. 7 | 8 | ## Test Cases 9 | 10 | ### Example 1: 11 | 12 | - **Input:** `n = 27` 13 | - **Output:** `true` 14 | - **Explanation:** `27 = 33` 15 | 16 | ### Example 2: 17 | 18 | - **Input:** `n = 0` 19 | - **Output:** `false` 20 | - **Explanation:** `There is no x where 3x = 0.` 21 | 22 | ### Example 3: 23 | 24 | - **Input:** `n = -1` 25 | - **Output:** `false` 26 | - **Explanation:** `There is no x where 3x = (-1).` 27 | 28 | ### Constraints: 29 | 30 | `-231 <= n <= 231 - 1` 31 | 32 | ### Link 33 | 34 | https://leetcode.com/problems/power-of-three/ 35 | -------------------------------------------------------------------------------- /Medium/98. Valid BST/README.md: -------------------------------------------------------------------------------- 1 | 98. Validate Binary Search Tree 2 | 3 | 4 | Given the root of a binary tree, determine if it is a valid binary search tree (BST). 5 | 6 | A valid BST is defined as follows: 7 | 8 | The left 9 | subtree 10 | of a node contains only nodes with keys less than the node's key. 11 | The right subtree of a node contains only nodes with keys greater than the node's key. 12 | Both the left and right subtrees must also be binary search trees. 13 | 14 | 15 | Example 1: 16 | 17 | 18 | Input: root = [2,1,3] 19 | Output: true 20 | Example 2: 21 | 22 | 23 | Input: root = [5,1,4,null,null,3,6] 24 | Output: false 25 | Explanation: The root node's value is 5 but its right child's value is 4. 26 | 27 | 28 | Constraints: 29 | 30 | The number of nodes in the tree is in the range [1, 104]. 31 | -231 <= Node.val <= 231 - 1 -------------------------------------------------------------------------------- /Easy/2703. Return Length of Arguments Passed/README.md: -------------------------------------------------------------------------------- 1 | # Problem #2703 ([Return Length of Arguments Passed](https://leetcode.com/problems/return-length-of-arguments-passed/) | Arguments, Length) 2 | 3 | 4 | Write a function `argumentsLength` that returns the count of arguments passed to it. 5 | 6 | 7 | 8 | **Example 1:** 9 | 10 | **Input**: `args = [5]` 11 | **Output**: 1 12 | **Explanation**: 13 | `argumentsLength(5);` // 1 14 | 15 | One value was passed to the function so it should return `1`. 16 | 17 | **Example 2:** 18 | 19 | **Input**: args = [{}, null, "3"] 20 | **Output**: 3 21 | **Explanation**: 22 | `argumentsLength({}, null, "3");` // 3 23 | 24 | Three values were passed to the function so it should return `3`. 25 | 26 | 27 | 28 | Constraints: 29 | 30 | `args` is a valid JSON array 31 | `0 <= args.length <= 100` 32 | -------------------------------------------------------------------------------- /Medium/2. Add Two Numbers/Approach 1/Solution..cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 4 | ListNode *dummy = new ListNode(0); 5 | ListNode *curr = dummy; 6 | int carry = 0; 7 | 8 | while(l1 != NULL || l2 != NULL || carry == 1){ 9 | int sum = 0; 10 | if(l1 != NULL){ 11 | sum += l1->val; 12 | l1 = l1->next; 13 | } 14 | if(l2 != NULL){ 15 | sum += l2->val; 16 | l2 = l2->next; 17 | } 18 | sum += carry; 19 | carry = sum/10; 20 | ListNode *node = new ListNode(sum % 10); 21 | curr->next = node; 22 | curr = curr->next; 23 | } 24 | return dummy->next; 25 | } 26 | }; -------------------------------------------------------------------------------- /Easy/73. Set Matrix Zeroes/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void setZeroes(int[][] matrix) { 3 | int rows = matrix.length, cols = matrix[0].length; 4 | boolean colu=true; 5 | 6 | for (int i = 0; i < rows; i++) { 7 | if (matrix[i][0] == 0) colu = false; 8 | for (int j = 1; j < cols; j++){ 9 | if (matrix[i][j] == 0){ 10 | matrix[i][0] = matrix[0][j] = 0; 11 | } 12 | } 13 | } 14 | 15 | for (int i = rows - 1; i >= 0; i--) { 16 | for (int j = cols - 1; j >= 1; j--){ 17 | if (matrix[i][0] == 0 || matrix[0][j] == 0){ 18 | matrix[i][j] = 0; 19 | } 20 | } 21 | if (colu == false) matrix[i][0] = 0; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Medium/15. 3sum/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> threeSum(int[] arr) { 3 | 4 | 5 | if (arr == null || arr.length < 3) return new ArrayList<>(); 6 | 7 | Arrays.sort(arr); 8 | Set> result = new HashSet<>(); 9 | 10 | for (int i = 0; i < arr.length - 2; i++) 11 | { 12 | 13 | int left = i + 1; 14 | int right = arr.length - 1; 15 | 16 | while (left < right) { 17 | int sum = arr[i] + arr[left] + arr[right]; 18 | 19 | if (sum == 0) { 20 | 21 | result.add(Arrays.asList(arr[i], arr[left], arr[right])); 22 | left++; 23 | right--; 24 | } else if (sum < 0) 25 | left++; 26 | else 27 | right--; 28 | 29 | } 30 | } 31 | 32 | return new ArrayList<>(result); 33 | 34 | } 35 | } -------------------------------------------------------------------------------- /Medium/153. Find Minimum in Rotated Sorted Array/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int findMin(int[] nums) { 8 | int start = 0, end = nums.length - 1, ans = start; 9 | while (nums[start] > nums[end]) { 10 | int mid = (start + end) / 2; 11 | if (nums[mid] <= nums[start] && nums[mid] <= nums[end]) { 12 | end = mid; 13 | } else if (nums[mid] >= nums[start] && nums[mid] >= nums[end]) { 14 | start = mid + 1; 15 | } else { 16 | return nums[mid]; 17 | } 18 | ans = start; 19 | } 20 | return nums[ans]; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Medium/2186. Minimum Number of Steps to Make Two Strings Anagram II/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minSteps(String s, String s1) { 3 | int[] freq1 = new int[26]; 4 | int[] freq2 = new int[26]; 5 | 6 | // Count the frequency of characters in the first string 7 | for (char c : s.toCharArray()) { 8 | freq1[c - 'a']++; 9 | } 10 | 11 | // Count the frequency of characters in the second string 12 | for (char c : s1.toCharArray()) { 13 | freq2[c - 'a']++; 14 | } 15 | 16 | int delete = 0; 17 | 18 | // Calculate the difference in character frequencies 19 | for (int i = 0; i < 26; i++) { 20 | delete += Math.abs(freq1[i] - freq2[i]); 21 | } 22 | return delete; 23 | 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Hard/1425. Constrained Subsequence Sum/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | int constrainedSubsetSum(vector &nums, int k) 11 | { 12 | vector dp(nums); 13 | deque q; 14 | q.push_back(0); 15 | for (int i = 1; i < nums.size(); i++) 16 | { 17 | while (!q.empty() && q.back() < i - k) 18 | { 19 | q.pop_back(); 20 | } 21 | dp[i] = max(dp[i], dp[q.back()] + nums[i]); 22 | while (!q.empty() && dp[q.front()] <= dp[i]) 23 | { 24 | q.pop_front(); 25 | } 26 | q.push_front(i); 27 | } 28 | return *max_element(dp.begin(), dp.end()); 29 | } 30 | }; -------------------------------------------------------------------------------- /Easy/1470. Shuffle the Array/Solution.java: -------------------------------------------------------------------------------- 1 | // Using new array 2 | class Solution { 3 | public int[] shuffle(int[] nums, int n) { 4 | int[] newNums = new int[nums.length]; 5 | int i = 0, j, k; 6 | while (i < nums.length) { 7 | j = i/2; 8 | k = j + n; 9 | newNums[i++] = nums[j]; 10 | newNums[i++] = nums[k]; 11 | } 12 | return newNums; 13 | } 14 | } 15 | 16 | // In-place 17 | class Solution { 18 | public int[] shuffle(int[] nums, int n) { 19 | for(int i = 0; i < n; i++){ 20 | nums[i] += nums[n + i] * 10000; 21 | } 22 | 23 | for(int i = n - 1; i >= 0; i--){ 24 | nums[2 * i + 1] = nums[i] / 10000; 25 | nums[2 * i] = nums[i] % 10000; 26 | } 27 | 28 | return nums; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Hard/4. Median of Two Sorted Arrays/New approach[Arraylist]/sol.md: -------------------------------------------------------------------------------- 1 | ### `findMedianSortedArrays` Function Explanation 2 | 3 | 1. Create an `ArrayList` called `list` to merge both sorted arrays into a single list. 4 | 2. Iterate through the elements of `nums1`, and for each element, add it to the `list`. 5 | 3. Iterate through the elements of `nums2`, and for each element, add it to the `list`. This effectively combines both input arrays into a single merged list. 6 | 4. Create a variable `sum` to store the sum of all elements in the merged list. Initialize it to 0. 7 | 5. Iterate through the merged `list`, and for each element, add its value to the `sum`. 8 | 6. Calculate the average (mean) of all elements in the merged list by dividing the `sum` by the total number of elements in the list. 9 | 7. Return the calculated average (mean) as the median value of the merged sorted arrays. -------------------------------------------------------------------------------- /Hard/920. Number of Music Playlists/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | private static final int MOD = 1000000007; 8 | 9 | public int numMusicPlaylists(int n, int goal, int k) { 10 | long[][] temp = new long[goal + 1][n + 1]; 11 | temp[0][0] = 1; 12 | 13 | for (int i = 1; i <= goal; i++) { 14 | for (int j = 1; j <= n; j++) { 15 | temp[i][j] = (temp[i][j] + temp[i - 1][j - 1] * (n - j + 1)) % MOD; 16 | if (j > k) { 17 | temp[i][j] = (temp[i][j] + temp[i - 1][j] * (j - k)) % MOD; 18 | } 19 | } 20 | } 21 | 22 | return (int) temp[goal][n]; 23 | } 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /Hard/115. Distinct Subsequences/Approach 1/solution.rust: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn num_distinct(s: String, t: String) -> i32 { 3 | let m = s.len(); 4 | let n = t.len(); 5 | let s_bytes = s.as_bytes(); 6 | let t_bytes = t.as_bytes(); 7 | 8 | if m < n { 9 | return 0; 10 | } 11 | 12 | let mut dp = vec![vec![0; n + 1]; m + 1]; 13 | 14 | for i in 0..=m { 15 | dp[i][0] = 1; 16 | } 17 | 18 | for i in 1..=m { 19 | for j in 1..=n { 20 | if s_bytes[i - 1] == t_bytes[j - 1] { 21 | dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]; 22 | } else { 23 | dp[i][j] = dp[i - 1][j]; 24 | } 25 | } 26 | } 27 | 28 | dp[m][n] 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Hard/135. Candy/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class sol { 4 | public static void main(String[] args) { 5 | // call the fn here 6 | } 7 | 8 | class Solution { 9 | public int candy(int[] arr) { 10 | int n = arr.length; 11 | int a[] = new int[n]; 12 | Arrays.fill(a, 1); 13 | for (int i = 0; i < n - 1; i++) { 14 | if (arr[i] < arr[i + 1]) { 15 | a[i + 1] = 1 + a[i]; 16 | } 17 | } 18 | for (int i = n - 1; i > 0; i--) { 19 | if (arr[i] < arr[i - 1] && a[i - 1] <= a[i]) { 20 | a[i - 1] = a[i] + 1; 21 | } 22 | } 23 | int sum = 0; 24 | for (int i : a) 25 | sum += i; 26 | return sum; 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Hard/1420. build array where you can find maximum exactly k comparison/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | typedef long long LL; 3 | LL dp[51][101][51] = {}; 4 | public: 5 | int numOfArrays(int n, int m, int k) { 6 | int mod = 1e9+7; 7 | for (int i = 0; i <= m; ++i) dp[1][i][1] = 1; 8 | for (int i = 1; i <= n; ++i) { 9 | for (int j = 1; j <= m; ++j) { 10 | for (int t = 1; t <= k; ++t) { 11 | LL s = 0; 12 | s = (s + j * dp[i - 1][j][t]) % mod; 13 | for (int x = 1; x < j; ++x) s = (s + dp[i - 1][x][t - 1]) %mod; 14 | dp[i][j][t] = (dp[i][j][t] + s) % mod; 15 | } 16 | } 17 | } 18 | LL ans = 0; 19 | for (int i = 1; i <= m; ++i) ans = (ans + dp[n][i][k]) % mod; 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /Medium/1695. Maximum Erasure Value/README.md: -------------------------------------------------------------------------------- 1 | # 1695. Maximum Erasure Value 2 | You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements. 3 | 4 | Return *the **maximum score** you can get by erasing **exactly one** subarray*. 5 | 6 | An array `b` is called to be a subarray of `a` if it forms a contiguous subsequence of `a`, that is, if it is equal to`a[l],a[l+1],...,a[r]` for some `(l,r)`. 7 | 8 | Example 1: 9 | > Input: nums = [4,2,4,5,6] 10 | > Output: 17 11 | > Explanation: The optimal subarray here is [2,4,5,6]. 12 | 13 | Example 2: 14 | > Input: nums = [5,2,1,2,5,2,1,2,5] 15 | > Output: 8 16 | > Explanation: The optimal subarray here is [5,2,1] or [1,2,5]. 17 | 18 | Constraints: 19 | * `1 <= nums.length <= 10^5` 20 | * `1 <= nums[i] <= 10^4` -------------------------------------------------------------------------------- /Medium/200. Number of Islands/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numIslands(vector>& grid) { 4 | int n = 0; 5 | for(int i = 0; i < grid.size(); i++){ 6 | for(int j = 0; j < grid[0].size(); j++){ 7 | if(grid[i][j] == '1'){ 8 | n++; 9 | visitIsland(grid, i, j); 10 | } 11 | } 12 | } 13 | return n; 14 | } 15 | 16 | private: 17 | void visitIsland(vector>& grid, int r, int c){ 18 | if(r < 0 || c < 0 || r >= grid.size() || c >= grid[0].size() || grid[r][c] == '0') 19 | return; 20 | grid[r][c] = '0'; 21 | visitIsland(grid, r + 1, c); 22 | visitIsland(grid, r - 1, c); 23 | visitIsland(grid, r, c + 1); 24 | visitIsland(grid, r, c - 1); 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Medium/98. Valid BST/solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public boolean isValidBST(TreeNode root) { 18 | return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE); 19 | } 20 | 21 | public boolean isValidBST(TreeNode root, long minVal, long maxVal) 22 | { 23 | if(root==null) return true; 24 | if(root.val>=maxVal || root.val<=minVal) return false; 25 | return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal); 26 | } 27 | } -------------------------------------------------------------------------------- /Easy/2591. Distribute Money to Maximum Children/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int distMoney(int money, int children) { 4 | if(money < children) return -1; 5 | 6 | money -= children; //Distributing one coin to each children 7 | int ans = money/7; // only 7 coins left to make it 8 hence divide to by 7 to get the number of children with 8 coins 8 | 9 | // If number of children with 8 coins i.e ans is more than the given children then we can simply give all the remaining coins to one child and rest will have 8 coins hence returning children - 1; 10 | if(ans > children) return children - 1; 11 | 12 | int remaning = money%7; 13 | children -= ans; 14 | if((remaning > 0 && children == 0) || 15 | (remaning == 3 && children == 1)) return ans - 1; 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Hard/1458. Max Dot Product of Two Subsequences/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDotProduct(vector& nums1, vector& nums2) { 4 | int n = nums1.size(); 5 | int m = nums2.size(); 6 | vector> memo(n, vector(m, INT_MIN)); 7 | 8 | function dp = [&](int i, int j) { 9 | if (i == n || j == m) { 10 | return INT_MIN; 11 | } 12 | 13 | if (memo[i][j] != INT_MIN) { 14 | return memo[i][j]; 15 | } 16 | 17 | memo[i][j] = max( 18 | nums1[i] * nums2[j] + max(dp(i + 1, j + 1), 0), 19 | max(dp(i + 1, j), dp(i, j + 1)) 20 | ); 21 | 22 | return memo[i][j]; 23 | }; 24 | 25 | return dp(0, 0); 26 | } 27 | }; -------------------------------------------------------------------------------- /Medium/967. Numbers With Same Consecutive Differences/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector numsSameConsecDiff(int n, int k) { 4 | if(n == 1) return vector{k}; 5 | vector list; 6 | int min = pow(10, n - 1); 7 | for(int i = 1; i < 10; i++){ 8 | queue q; 9 | q.push(i); 10 | while(!q.empty()){ 11 | int num = q.front(); 12 | q.pop(); 13 | if(num >= min){ 14 | list.push_back(num); 15 | continue; 16 | } 17 | int x = num % 10; 18 | if(k > 0 && x - k >= 0) 19 | q.push(num * 10 + x - k); 20 | if(x + k < 10) 21 | q.push(num * 10 + x + k); 22 | } 23 | } 24 | return list; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Hard/41. First Missing Positive/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int firstMissingPositive(vector& nums) { 10 | 11 | int n = nums.size(); 12 | 13 | for(int i=0; i 0){ 28 | return i+1; 29 | } 30 | } 31 | 32 | return n+1; 33 | } 34 | }; 35 | 36 | int main() { 37 | 38 | /// call the fn here 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /Medium/151. Reverse Words in a String/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String reverseWords(String s) { 3 | String [] words = s.split(" "); 4 | 5 | //StringBuilder to store the result. 6 | StringBuilder result = new StringBuilder(); 7 | 8 | int end = words.length - 1; 9 | 10 | for(int i = 0; i<= end; i++){ 11 | // Check if the current word is not empty. 12 | if(!words[i].isEmpty()) { 13 | // Insert the current word at the beginning of the 'result'. 14 | result.insert(0, words[i]); 15 | if(i < end) { 16 | // Add a space before the current word if it's not the last word. 17 | result.insert(0, " "); 18 | } 19 | } 20 | } 21 | 22 | return result.toString(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Medium/200. Number of Islands/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | char[][] mat; 3 | int[] DIR = {1, 0, -1, 0, 1}; 4 | public int numIslands(char[][] grid) { 5 | int n = 0; 6 | mat = grid; 7 | int rows = mat.length; 8 | int cols = mat[0].length; 9 | for(int i = 0; i < rows; i++){ 10 | for(int j = 0; j < cols; j++){ 11 | if(mat[i][j] == '1') { 12 | visitIsland(i, j); 13 | n++; 14 | } 15 | } 16 | } 17 | return n; 18 | } 19 | 20 | public void visitIsland(int r, int c){ 21 | if(r < 0 || c < 0 || r >= mat.length || c >= mat[r].length || mat[r][c] == '0') return; 22 | mat[r][c] = '0'; 23 | for(int i = 0; i < DIR.length - 1; i++){ 24 | visitIsland(r + DIR[i], c + DIR[i + 1]); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Medium/229. MajorityElement-ll/Solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | vector majorityElement(vector& nums) { 11 | vector vec; 12 | int n= floor(nums.size()/3)+1; 13 | map mp; 14 | map::iterator it; 15 | for(int i=0;i(nums[i],1)); 19 | else it->second=mp[nums[i]]+1; 20 | } 21 | for(it=mp.begin();it!=mp.end();it++){ 22 | if(it->second>=n) 23 | vec.push_back(it->first); 24 | } 25 | return vec; 26 | } 27 | }; 28 | 29 | int main() 30 | { 31 | 32 | // call the fn here 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Hard/41. First Missing Positive/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int firstMissingPositive(int[] nums) { 8 | int n = nums.length; 9 | 10 | for (int i = 0; i < n; i++) { 11 | if (nums[i] <= 0) { 12 | nums[i] = n + 1; 13 | } 14 | } 15 | 16 | for (int i = 0; i < n; i++) { 17 | int num = Math.abs(nums[i]); 18 | if (num <= n) { 19 | nums[num - 1] = -Math.abs(nums[num - 1]); 20 | } 21 | } 22 | 23 | for (int i = 0; i < n; i++) { 24 | if (nums[i] > 0) { 25 | return i + 1; 26 | } 27 | } 28 | 29 | return n + 1; 30 | } 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /Medium/1361. Validate Binary Tree Nodes/Readme.md: -------------------------------------------------------------------------------- 1 | You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree. 2 | 3 | If node i has no left child then leftChild[i] will equal -1, similarly for the right child. 4 | 5 | Note that the nodes have no values and that we only use the node numbers in this problem. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | 12 | Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1] 13 | Output: true 14 | Example 2: 15 | 16 | 17 | Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1] 18 | Output: false 19 | Example 3: 20 | 21 | 22 | Input: n = 2, leftChild = [1,0], rightChild = [-1,-1] 23 | Output: false 24 | 25 | 26 | Constraints: 27 | 28 | n == leftChild.length == rightChild.length 29 | 1 <= n <= 104 30 | -1 <= leftChild[i], rightChild[i] <= n - 1 -------------------------------------------------------------------------------- /Medium/341. Flatten Nested List Iterator/soln.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class NestedIterator { 4 | private List flatList; 5 | private int current; 6 | 7 | public NestedIterator(List nestedList) { 8 | flatList = new ArrayList<>(); 9 | current = 0; 10 | flatten(nestedList); 11 | } 12 | 13 | public int next() { 14 | int result = flatList.get(current); 15 | current++; 16 | return result; 17 | } 18 | 19 | public boolean hasNext() { 20 | return current < flatList.size(); 21 | } 22 | 23 | private void flatten(List nestedList) { 24 | for (NestedInteger item : nestedList) { 25 | if (item.isInteger()) { 26 | flatList.add(item.getInteger()); 27 | } else { 28 | flatten(item.getList()); 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Easy/746.Min Cost Climbing Stairs/Min Cost Climbing Stairs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int minCostClimbingStairs(vector& cost) { 8 | int n = cost.size(); 9 | 10 | for (int i = 2; i < n; i++) { 11 | cost[i] += min(cost[i - 1], cost[i - 2]); 12 | } 13 | 14 | return min(cost[n - 1], cost[n - 2]); 15 | } 16 | }; 17 | 18 | int main() { 19 | int n; 20 | cout << "Enter the number of steps: "; 21 | cin >> n; 22 | 23 | vector cost(n); 24 | 25 | cout << "Enter the cost for each step:" << endl; 26 | for (int i = 0; i < n; i++) { 27 | cin >> cost[i]; 28 | } 29 | 30 | Solution solution; 31 | int result = solution.minCostClimbingStairs(cost); 32 | 33 | cout << "Minimum cost to reach the top: " << result << endl; 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Easy/1512. Number of Good Pairs/explanation.md.txt: -------------------------------------------------------------------------------- 1 | Algorithm: 2 | 3 | 1)Use a count array to store the frequency of each number in the input array. 4 | 2)Iterate through the count array. 5 | 3)For each frequency n, calculate the number of identical pairs as n*(n-1)/2. 6 | 4)Keep adding this to the answer. 7 | 5)Return the answer. 8 | 9 | The reason we can calculate the number of identical pairs as n*(n-1)/2 is because we are counting each pair twice. For example, if we have two identical numbers, we can count them as a pair once for each index. But this means that we have counted them twice, so we need to divide by 2 to get the correct number of pairs. 10 | 11 | Time complexity: O(n) where n is the length of the input array. We traverse the input array only once to populate the count array. Then we traverse the count array which has size 101. So the overall time complexity is O(n). 12 | 13 | Space complexity: O(1) as we use a constant size count array. -------------------------------------------------------------------------------- /Medium/229. MajorityElement-ll/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public List majorityElement(int[] nums) { 3 | List result = new ArrayList<>(); 4 | if(nums.length < 3){ 5 | int n = nums.length; 6 | for(int i=0; i 1 && nums[i] != nums[i+1]){ 21 | count = 1; 22 | } 23 | if(count >= gt+1){ 24 | if(!result.contains(nums[i])){ 25 | result.add(nums[i]); 26 | count = 1; 27 | } 28 | } 29 | } 30 | return result; 31 | } 32 | } -------------------------------------------------------------------------------- /Medium/43. Multiply Strings/README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 43. Multiply Strings 2 | 3 | ## Problem Description 4 | Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`. 5 | 6 | Each number in `candidates` may only be used once in the combination. 7 | 8 | **Note:** The solution set must not contain duplicate combinations. 9 | 10 | ### Test Cases 11 | 12 | **Example 1:** 13 | 14 | > **Input:** num1 = "2", num2 = "3" 15 | > 16 | > **Output:** "6" 17 | 18 | **Example 2:** 19 | 20 | > **Input:** num1 = "123", num2 = "456" 21 | > 22 | > **Output:** "56088" 23 | 24 | 25 | **Constraints:** 26 | 27 | - `1 <= num1.length, num2.length <= 200` 28 | - `num1` and `num2` consist of digits only. 29 | - Both `num1` and `num2` do not contain any leading zero, except the number `0` itself. 30 | 31 | ### Link 32 | 33 | https://leetcode.com/problems/multiply-strings/ 34 | -------------------------------------------------------------------------------- /Hard/1420. build array where you can find maximum exactly k comparison/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numOfArrays(int n, int m, int k) { 3 | final int MODULO = 1000000007; 4 | int[][][] dp = new int[n + 1][m + 1][k + 2]; 5 | dp[0][0][0] = 1; 6 | for (int i = 0; i < n; i++) { 7 | for (int j = 0; j <= m; j++) { 8 | for (int p = 0; p <= k; p++) { 9 | for (int q = 1; q <= m; q++) { 10 | if (q > j) 11 | dp[i + 1][q][p + 1] = (dp[i + 1][q][p + 1] + dp[i][j][p]) % MODULO; 12 | else 13 | dp[i + 1][j][p] = (dp[i + 1][j][p] + dp[i][j][p]) % MODULO; 14 | } 15 | } 16 | } 17 | } 18 | int count = 0; 19 | for (int i = 1; i <= m; i++) 20 | count = (count + dp[n][i][k]) % MODULO; 21 | return count; 22 | } 23 | } -------------------------------------------------------------------------------- /Hard/34. Find First and Last Position of Element in Sorted Array/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class sol { 4 | public static void main(String[] args) { 5 | // call the fn here 6 | } 7 | 8 | class Solution { 9 | public int[] searchRange(int[] N, int T) { 10 | int Tleft = find(T, N, 0); 11 | if (Tleft == N.length || N[Tleft] != T) return new int[] { 12 | -1, -1 13 | }; 14 | return new int[] { 15 | Tleft, 16 | find(T + 1, N, Tleft) - 1 17 | }; 18 | } 19 | public int find(int target, int[] arr, int left) { 20 | int right = arr.length - 1; 21 | while (left <= right) { 22 | int mid = left + right >> 1; 23 | if (arr[mid] < target) left = mid + 1; 24 | else right = mid - 1; 25 | } 26 | return left; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Easy/746.Min Cost Climbing Stairs/READme.md: -------------------------------------------------------------------------------- 1 | You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. 2 | 3 | You can either start from the step with index 0, or the step with index 1. 4 | 5 | Return the minimum cost to reach the top of the floor. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: cost = [10,15,20] 12 | Output: 15 13 | Explanation: You will start at index 1. 14 | - Pay 15 and climb two steps to reach the top. 15 | The total cost is 15. 16 | Example 2: 17 | 18 | Input: cost = [1,100,1,1,1,100,1,1,100,1] 19 | Output: 6 20 | Explanation: You will start at index 0. 21 | - Pay 1 and climb two steps to reach index 2. 22 | - Pay 1 and climb two steps to reach index 4. 23 | - Pay 1 and climb two steps to reach index 6. 24 | - Pay 1 and climb one step to reach index 7. 25 | - Pay 1 and climb two steps to reach index 9. 26 | - Pay 1 and climb one step to reach the top. 27 | The total cost is 6. -------------------------------------------------------------------------------- /Hard/42. Trapping Rain Water/sol.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} 3 | * @return {number} 4 | */ 5 | var trap =function (height) { 6 | if (height.length < 3) { 7 | return 0; // Not enough bars to trap water 8 | } 9 | 10 | let left = 0; 11 | let right = height.length - 1; 12 | let leftMax = 0; 13 | let rightMax = 0; 14 | let trappedWater = 0; 15 | 16 | while (left < right) { 17 | if (height[left] < height[right]) { 18 | if (height[left] >= leftMax) { 19 | leftMax = height[left]; 20 | } else { 21 | trappedWater += leftMax - height[left]; 22 | } 23 | left++; 24 | } else { 25 | if (height[right] >= rightMax) { 26 | rightMax = height[right]; 27 | } else { 28 | trappedWater += rightMax - height[right]; 29 | } 30 | right--; 31 | } 32 | } 33 | 34 | return trappedWater; 35 | }; -------------------------------------------------------------------------------- /Medium/47. Permutations II/README.md: -------------------------------------------------------------------------------- 1 |

47. Permutations II

Medium

2 |

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

3 | 4 |

 

5 |

Example 1:

6 | 7 |
Input: nums = [1,1,2]
 8 | Output:
 9 | [[1,1,2],
10 |  [1,2,1],
11 |  [2,1,1]]
12 | 
13 | 14 |

Example 2:

15 | 16 |
Input: nums = [1,2,3]
17 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= nums.length <= 8
  • 25 |
  • -10 <= nums[i] <= 10
  • 26 |
27 |
-------------------------------------------------------------------------------- /Medium/5. Longest Palindromic Substring/chiku011solution.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution { 4 | public: 5 | bool check (int i,int j , string s){ 6 | while(i<=j){ 7 | if(s[i] != s[j]){ 8 | return false; 9 | }else{ 10 | i++; 11 | j--; 12 | } 13 | } 14 | return true; 15 | } 16 | string longestPalindrome(string s) { 17 | int maxlen=0; 18 | int index =0; 19 | for(int i =0;i maxlen){ 25 | maxlen = j-i+1; 26 | index =i; 27 | } 28 | } 29 | } 30 | } 31 | } 32 | return s.substr(index,maxlen); 33 | } 34 | }; -------------------------------------------------------------------------------- /Medium/515. Find Largest Value in Each Tree Row/sol.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector largestValues(TreeNode *root) 5 | { 6 | if (!root) 7 | return {}; 8 | 9 | std::vector result; 10 | std::queue queue; 11 | queue.push(root); 12 | 13 | while (!queue.empty()) 14 | { 15 | int curr_level_size = queue.size(); 16 | int max_val = INT_MIN; 17 | 18 | for (int i = 0; i < curr_level_size; ++i) 19 | { 20 | TreeNode *node = queue.front(); 21 | queue.pop(); 22 | max_val = std::max(max_val, node->val); 23 | 24 | if (node->left) 25 | queue.push(node->left); 26 | if (node->right) 27 | queue.push(node->right); 28 | } 29 | 30 | result.push_back(max_val); 31 | } 32 | 33 | return result; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Hard/135. Candy/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int candy(vector &ratings) 10 | { 11 | 12 | int n = ratings.size(); 13 | vector candies(n, 1); 14 | 15 | for (int i = 1; i < n; i++) 16 | { 17 | if (ratings[i] > ratings[i - 1]) 18 | { 19 | candies[i] = candies[i - 1] + 1; 20 | } 21 | } 22 | 23 | for (int i = n - 1; i > 0; i--) 24 | { 25 | if (ratings[i - 1] > ratings[i] && candies[i - 1] <= candies[i]) 26 | { 27 | candies[i - 1] = candies[i] + 1; 28 | } 29 | } 30 | 31 | int total = 0; 32 | for (int candy : candies) 33 | { 34 | total += candy; 35 | } 36 | 37 | return total; 38 | } 39 | }; 40 | 41 | int main() 42 | { 43 | 44 | // call the fn here 45 | return 0; 46 | } -------------------------------------------------------------------------------- /Medium/823. Binary Trees With Factors/README.md: -------------------------------------------------------------------------------- 1 |

823. Binary Trees With Factors


2 | Medium

3 | 4 | Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1. 5 | 6 | We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. 7 | 8 | Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7. 9 |
10 | 11 | Example 1:
12 | Input: arr = [2,4]
13 | Output: 3
14 | Explanation: We can make these trees: [2], [4], [4, 2, 2] 15 |
16 | 17 | Example 2:
18 | Input: arr = [2,4,5,10
19 | Output: 7
20 | Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]. 21 |
22 | 23 | Constraints:
24 | 1. <= arr.length <= 1000
25 | 2. <= arr[i] <= 109
26 | All the values of arr are unique. 27 | -------------------------------------------------------------------------------- /Medium/967. Numbers With Same Consecutive Differences/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] numsSameConsecDiff(int n, int k) { 3 | if(n == 1) return new int[]{k}; 4 | List list = new ArrayList(); 5 | int min = (int) Math.pow(10, n - 1); 6 | for(int i = 1; i < 10; i++){ 7 | Queue q = new LinkedList(); 8 | q.add(i); 9 | while(!q.isEmpty()){ 10 | int num = q.poll(); 11 | if (num >= min){ 12 | list.add(num); 13 | continue; 14 | } 15 | int x = num%10; 16 | if(k > 0 && x - k >= 0) 17 | q.add(num * 10 + x - k); 18 | if(x + k < 10) 19 | q.add(num * 10 + x + k); 20 | } 21 | } 22 | return list.stream() 23 | .mapToInt(i -> i) 24 | .toArray(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Hard/1269. Number of Ways to Stay in the Same Place After Some Steps/Readme.md: -------------------------------------------------------------------------------- 1 | You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). 2 | 3 | Given two integers steps and arrLen, return the number of ways such that your pointer is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: steps = 3, arrLen = 2 10 | Output: 4 11 | Explanation: There are 4 differents ways to stay at index 0 after 3 steps. 12 | Right, Left, Stay 13 | Stay, Right, Left 14 | Right, Stay, Left 15 | Stay, Stay, Stay 16 | Example 2: 17 | 18 | Input: steps = 2, arrLen = 4 19 | Output: 2 20 | Explanation: There are 2 differents ways to stay at index 0 after 2 steps 21 | Right, Left 22 | Stay, Stay 23 | Example 3: 24 | 25 | Input: steps = 4, arrLen = 2 26 | Output: 8 -------------------------------------------------------------------------------- /Medium/29. Divide Two Integers/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int divide(int dividend, int divisor) { 4 | 5 | //Handling corner cases 6 | if(dividend==INT_MIN && divisor==-1) return INT_MAX; 7 | if(dividend==INT_MIN && divisor==1) return INT_MIN; 8 | 9 | 10 | //Converting divisors and dividend to their positive values 11 | long int dd = abs(dividend), dv = abs(divisor); 12 | 13 | //Result Variables 14 | int res=0; 15 | while(dv<=dd) { 16 | long int mul=dv, tmp=1; 17 | while(mul<=dd-mul) { 18 | mul+=mul; 19 | tmp+=tmp; 20 | } 21 | res+=tmp; 22 | dd-=mul; 23 | } 24 | 25 | //If either of dividend or divisor is negative our result will be negative 26 | if((dividend<0&&divisor>0) || (dividend>0&&divisor<0)) return -res; 27 | 28 | return res; 29 | 30 | } 31 | }; -------------------------------------------------------------------------------- /Hard/664. Strange Printer/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | int strangePrinter(string s) 11 | { 12 | 13 | int n = s.size(); 14 | vector> dp(n, vector(n, 0)); 15 | 16 | return solve(s, 0, n - 1, dp); 17 | } 18 | 19 | private: 20 | int solve(string &s, int i, int j, vector> &dp) 21 | { 22 | 23 | if (i > j) 24 | return 0; 25 | 26 | if (dp[i][j] != 0) 27 | return dp[i][j]; 28 | 29 | int ans = solve(s, i, j - 1, dp) + 1; 30 | 31 | for (int k = i; k < j; k++) 32 | { 33 | if (s[k] == s[j]) 34 | { 35 | ans = min(ans, solve(s, i, k, dp) + solve(s, k + 1, j - 1, dp)); 36 | } 37 | } 38 | 39 | return dp[i][j] = ans; 40 | } 41 | }; 42 | 43 | int main() 44 | { 45 | // call the fn here 46 | return 0; 47 | } -------------------------------------------------------------------------------- /Medium/153. Find Minimum in Rotated Sorted Array/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int findMin(vector &nums) 10 | { 11 | 12 | int start = 0; 13 | int end = nums.size() - 1; 14 | int ans = start; 15 | 16 | while (nums[start] > nums[end]) 17 | { 18 | int mid = (start + end) / 2; 19 | 20 | if (nums[mid] <= nums[start] && nums[mid] <= nums[end]) 21 | { 22 | end = mid; 23 | } 24 | else if (nums[mid] >= nums[start] && nums[mid] >= nums[end]) 25 | { 26 | start = mid + 1; 27 | } 28 | else 29 | { 30 | return nums[mid]; 31 | } 32 | 33 | ans = start; 34 | } 35 | 36 | return nums[ans]; 37 | } 38 | }; 39 | 40 | int main() 41 | { 42 | 43 | // call the fn here 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/add-a-problem.yml: -------------------------------------------------------------------------------- 1 | name: "❔ Add a Problem" 2 | description: "Add a LeetCode problem." 3 | title: "[PROBLEM] 0. Problem Title" 4 | labels: 5 | # - "hacktoberfest" 6 | - "problem" 7 | body: 8 | - type: dropdown 9 | id: problem-difficulty 10 | attributes: 11 | label: Difficulty 12 | description: "The difficulty of the problem." 13 | options: 14 | - Easy 15 | - Medium 16 | - Hard 17 | validations: 18 | required: true 19 | 20 | - type: textarea 21 | id: problem-description 22 | attributes: 23 | label: Problem Description 24 | description: "The description of the problem." 25 | placeholder: "You are given..." 26 | validations: 27 | required: true 28 | 29 | - type: input 30 | id: problem-link 31 | attributes: 32 | label: Link 33 | description: "The link of the problem." 34 | placeholder: "https://leetcode.com/problems/two-sum/" 35 | validations: 36 | required: false 37 | -------------------------------------------------------------------------------- /Medium/204.CountPrimes/Count-Primes.java: -------------------------------------------------------------------------------- 1 | /* 2 | * LeetCode 204. 3 | * Problem Statement-Given an integer n, return the number of prime numbers that are strictly less than n 4 | * 5 | * Test Cases: 6 | * 7 | * Example 1: 8 | Input: n = 10 9 | Output: 4 10 | Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 11 | 12 | Example 2: 13 | Input: n = 0 14 | Output: 0 15 | */ 16 | 17 | //Solution of Sieve of Eratosthenes approach 18 | class Solution { 19 | public int countPrimes(int n) { 20 | //using seive of eratosthenes 21 | boolean prime[]=new boolean[n+1];int c=0; 22 | Arrays.fill(prime,true); 23 | prime[0]=false; 24 | for(int i=2;i*i<=n;i++) 25 | { 26 | if(prime[i]==true) 27 | { 28 | for(int j=i*i;j<=n;j=j+i) 29 | prime[j]=false; 30 | } 31 | } 32 | for(int i=2;i { 3 | const getNextValidCharIndex = (str, index) => { 4 | let backspaceCount = 0; 5 | while (index >= 0) { 6 | if (str[index] === "#") { 7 | backspaceCount++; 8 | index--; 9 | } else if (backspaceCount > 0) { 10 | backspaceCount--; 11 | index--; 12 | } else { 13 | break; 14 | } 15 | } 16 | return index; 17 | }; 18 | 19 | let sPointer = s.length - 1; 20 | let tPointer = t.length - 1; 21 | 22 | while (sPointer >= 0 || tPointer >= 0) { 23 | sPointer = getNextValidCharIndex(s, sPointer); 24 | tPointer = getNextValidCharIndex(t, tPointer); 25 | 26 | if (sPointer < 0 && tPointer < 0) { 27 | return true; 28 | } 29 | 30 | if (sPointer < 0 || tPointer < 0 || s[sPointer] !== t[tPointer]) { 31 | return false; 32 | } 33 | 34 | sPointer--; 35 | tPointer--; 36 | } 37 | 38 | return true; 39 | }; 40 | -------------------------------------------------------------------------------- /Medium/19. Remove nth Node From the End/sol.java: -------------------------------------------------------------------------------- 1 | 2 | class ListNode { 3 | int val; 4 | ListNode next; 5 | 6 | ListNode() { 7 | } 8 | 9 | ListNode(int val) { 10 | this.val = val; 11 | } 12 | 13 | ListNode(int val, ListNode next) { 14 | this.val = val; 15 | this.next = next; 16 | } 17 | } 18 | public class sol { 19 | public static void main(String[] args) { 20 | // call the fn here 21 | } 22 | } 23 | 24 | 25 | class Solution { 26 | public ListNode removeNthFromEnd(ListNode head, int n) { 27 | ListNode dummy = new ListNode(0); 28 | dummy.next = head; 29 | ListNode first = dummy; 30 | ListNode second = dummy; 31 | 32 | for (int i = 0; i <= n; i++) { 33 | first = first.next; 34 | } 35 | 36 | while (first != null) { 37 | first = first.next; 38 | second = second.next; 39 | } 40 | 41 | second.next = second.next.next; 42 | 43 | return dummy.next; 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /Medium/62. Unique Paths/sol.md: -------------------------------------------------------------------------------- 1 | Summary of the algorithm: 2 | 3 | 1. Create a 2D array, `temp`, to store the number of unique paths to each cell in the grid. 4 | 2. Initialize the first row and column of `temp` to 1, since there is only one unique path to each cell in the first row and column. 5 | 3. Iterate over the remaining rows and columns of `temp`: 6 | * For each cell, calculate the number of unique paths to the cell by adding the number of unique paths to the cell to the left and the number of unique paths to the cell above. 7 | 4. Return the value of the last cell in `temp`, which is the number of unique paths to the bottom-right corner of the grid. 8 | 9 | This algorithm works by filling in the `temp` array row-by-row, starting with the first row. For each cell in the `temp` array, the algorithm calculates the number of unique paths to the cell by adding the number of unique paths to the cell to the left and the number of unique paths to the cell above. This is because the only way to reach a cell is to come from the left or from above. 10 | 11 | -------------------------------------------------------------------------------- /Easy/26. Remove Duplicates from Sorted Array/Solution.js: -------------------------------------------------------------------------------- 1 | // Solution # 1 2 | const removeDuplicates = function (nums) { 3 | let uniqueCount = 1; // Initialize the count of unique elements. 4 | 5 | for (let i = 1; i < nums.length; i++) { 6 | if (nums[i] !== nums[i - 1]) { 7 | // If the current element is different from the previous element, it's a new unique element. 8 | nums[uniqueCount] = nums[i]; // Move the unique element to the next position. 9 | uniqueCount++; // Increment the count of unique elements. 10 | } 11 | } 12 | 13 | return uniqueCount; 14 | }; 15 | 16 | // Solution # 2 17 | function removeDuplicates(nums) { 18 | // Use filter to create a new array with unique elements 19 | const uniqueArray = nums.filter((value, index) => nums.indexOf(value) === index); 20 | 21 | // Copy the unique elements back to the original array 22 | for (let i = 0; i < uniqueArray.length; i++) { 23 | nums[i] = uniqueArray[i]; 24 | } 25 | return uniqueArray.length; 26 | } 27 | -------------------------------------------------------------------------------- /Medium/34. First and Last Position of Element in an Array/New Approach/sol.md: -------------------------------------------------------------------------------- 1 | ### `searchRange` Function Explanation 2 | 3 | 1. Get the length of the input array `nums`. 4 | 2. Initialize an array to store the search range. 5 | 3. Initialize an array with [-1, -1] (default return value). 6 | 4. Initialize the start index of the search range as -1. 7 | 5. Initialize the end index of the search range as -1. 8 | 6. Start iterating through the input array. 9 | 7. If the current element is not the target, continue to the next element. 10 | 8. If the current element is not the target, continue to the next iteration. 11 | 9. If the start index of the search range is -1, set it to the current index. 12 | 10. Update the end index of the search range to the current index when a match is found. 13 | 11. If the start index is not -1, return the search range. 14 | 12. Return the search range containing the start and end indices of the target. 15 | 13. If no match was found, return the default [-1, -1] array. 16 | 14. Return the default search range [-1, -1] to indicate no match. -------------------------------------------------------------------------------- /Hard/239. Sliding Window Max/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | vector maxSlidingWindow(vector &nums, int k) 11 | { 12 | 13 | int n = nums.size(); 14 | if (n == 0 || k <= 0) 15 | return {}; 16 | 17 | vector ans; 18 | deque dq; 19 | 20 | for (int i = 0; i < n; i++) 21 | { 22 | 23 | if (!dq.empty() && dq.front() == i - k) 24 | { 25 | dq.pop_front(); 26 | } 27 | 28 | while (!dq.empty() && nums[dq.back()] < nums[i]) 29 | { 30 | dq.pop_back(); 31 | } 32 | 33 | dq.push_back(i); 34 | 35 | if (i >= k - 1) 36 | { 37 | ans.push_back(nums[dq.front()]); 38 | } 39 | } 40 | 41 | return ans; 42 | } 43 | }; 44 | 45 | int main() 46 | { 47 | 48 | // call the fn here 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /Medium/19. Remove nth Node From the End/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct ListNode 6 | { 7 | int val; 8 | ListNode *next; 9 | 10 | ListNode() : val(0), next(nullptr) {} 11 | ListNode(int x) : val(x), next(nullptr) {} 12 | ListNode(int x, ListNode *next) : val(x), next(next) {} 13 | }; 14 | 15 | class Solution 16 | { 17 | public: 18 | ListNode *removeNthFromEnd(ListNode *head, int n) 19 | { 20 | 21 | ListNode *dummy = new ListNode(0); 22 | dummy->next = head; 23 | 24 | ListNode *first = dummy; 25 | ListNode *second = dummy; 26 | 27 | for (int i = 0; i <= n; i++) 28 | { 29 | first = first->next; 30 | } 31 | 32 | while (first != NULL) 33 | { 34 | first = first->next; 35 | second = second->next; 36 | } 37 | 38 | second->next = second->next->next; 39 | 40 | return dummy->next; 41 | } 42 | }; 43 | 44 | int main() 45 | { 46 | // call the fn here 47 | return 0; 48 | } -------------------------------------------------------------------------------- /Easy/13. Roman to Integer/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static int num(int i){ 3 | int l=0; 4 | switch(i){ 5 | case 'I' : l= 1; 6 | break; 7 | case 'V' : l= 5; 8 | break; 9 | case 'X' : l= 10; 10 | break; 11 | case 'L' : l= 50; 12 | break; 13 | case 'C' : l= 100; 14 | break; 15 | case 'D' : l= 500; 16 | break; 17 | case 'M' : l= 1000; 18 | break; 19 | } 20 | return l; 21 | } 22 | public int romanToInt(String s) { 23 | int k1,k2; 24 | k1= num(s.charAt(s.length()-1)); 25 | int k =k1; 26 | for(int i = s.length()-2;i>=0;i--){ 27 | k2 = num(s.charAt(i)); 28 | if(k2 q = new ArrayDeque<>(); 11 | q.offerLast(0); 12 | for (int i = 1; i < nums.length; i++) { 13 | while (!q.isEmpty() && q.peekLast() < i - k) { 14 | q.pollLast(); 15 | } 16 | dp[i] = Math.max(dp[i], dp[q.peekLast()] + nums[i]); 17 | while (!q.isEmpty() && dp[q.peekFirst()] <= dp[i]) { 18 | q.pollFirst(); 19 | } 20 | q.offerFirst(i); 21 | } 22 | int max = Integer.MIN_VALUE; 23 | for (int num : dp) { 24 | max = Math.max(max, num); 25 | } 26 | return max; 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /Medium/5. Longest Palindromic String/longestPalindromic.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestPalindrome(string s) { 4 | int n = s.length(); 5 | int st = 0; 6 | int max_len = 1; 7 | 8 | if(n == 1) return s; 9 | 10 | for(int i=0; i < n-1; i++) { 11 | int l = i, r = i; 12 | while(l >= 0 && r < n && s[l] == s[r]) { 13 | l--; 14 | r++; 15 | } 16 | int len = r-l-1; 17 | if(len > max_len) { 18 | max_len = len; 19 | st = l+1; 20 | } 21 | } 22 | 23 | for(int i=0; i < n-1; i++) { 24 | int l = i, r = i+1; 25 | while(l >= 0 && r < n && s[l] == s[r]) { 26 | l--; 27 | r++; 28 | } 29 | int len = r-l-1; 30 | if(len > max_len) { 31 | max_len = len; 32 | st = l+1; 33 | } 34 | } 35 | 36 | return s.substr(st, max_len); 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Easy/26. Remove Duplicates from Sorted Array/Solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int removeDuplicates(vector& nums) { 7 | int c = 0; 8 | if (nums.size() == 0) { 9 | return 0; 10 | } 11 | for (int i = 0; nums[i] != nums[nums.size() - 1]; i++) { 12 | int curElm = nums[i], nuOfA = 0, pos = i + 1; 13 | while (pos < nums.size()) { 14 | if (curElm == nums[pos]) { 15 | nuOfA++; 16 | } else { 17 | break; 18 | } 19 | pos++; 20 | } 21 | if (nuOfA > 0) { 22 | shiftByNum(nums, nuOfA, i); 23 | } 24 | c++; 25 | } 26 | 27 | return c + 1; 28 | } 29 | 30 | private: 31 | void shiftByNum(vector& nums, int by, int pos) { 32 | for (int i = pos; i + by < nums.size(); i++) { 33 | nums[i] = nums[i + by]; 34 | } 35 | } 36 | }; 37 | 38 | -------------------------------------------------------------------------------- /Hard/1326. Min no of Taps to Open to Water a Garden/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution 8 | { 9 | public: 10 | int minTaps(int n, vector &ranges) 11 | { 12 | 13 | vector taps(n + 1, 0); 14 | 15 | for (int i = 0; i < ranges.size(); i++) 16 | { 17 | if (ranges[i] == 0) 18 | continue; 19 | int left = max(0, i - ranges[i]); 20 | taps[left] = max(taps[left], i + ranges[i]); 21 | } 22 | 23 | int cnt = 0, end = 0, far = 0; 24 | 25 | for (int i = 0; i <= n; i++) 26 | { 27 | if (i > end) 28 | { 29 | if (far <= end) 30 | return -1; 31 | end = far; 32 | cnt++; 33 | } 34 | far = max(far, taps[i]); 35 | } 36 | 37 | return cnt + (end < n ? 1 : 0); 38 | } 39 | }; 40 | 41 | int main() 42 | { 43 | // call the fn here 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /Medium/61. Rotate List/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct ListNode 6 | { 7 | int val; 8 | ListNode *next; 9 | ListNode() : val(0), next(nullptr) {} 10 | ListNode(int x) : val(x), next(nullptr) {} 11 | ListNode(int x, ListNode *next) : val(x), next(next) {} 12 | }; 13 | 14 | class Solution 15 | { 16 | public: 17 | ListNode *rotateRight(ListNode *head, int k) 18 | { 19 | 20 | if (!head || !head->next) 21 | return head; 22 | 23 | int n = 1; 24 | ListNode *temp = head; 25 | while (temp->next) 26 | { 27 | n++; 28 | temp = temp->next; 29 | } 30 | 31 | temp->next = head; 32 | 33 | k = k % n; 34 | k = n - k; 35 | while (k-- > 0) 36 | { 37 | temp = temp->next; 38 | } 39 | 40 | head = temp->next; 41 | 42 | temp->next = nullptr; 43 | 44 | return head; 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | 51 | // call the fn here 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /Hard/664. Strange Printer/sol.java: -------------------------------------------------------------------------------- 1 | public class sol { 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | 6 | class Solution { 7 | public int strangePrinter(String s) { 8 | int n = s.length(); 9 | int[][] temp = new int[n][n]; 10 | return minTurns(s, 0, n - 1, temp); 11 | } 12 | 13 | int minTurns(String s, int start, int end, int[][] temp) { 14 | if (start > end) { 15 | return 0; 16 | } 17 | 18 | if (temp[start][end] > 0) { 19 | return temp[start][end]; 20 | } 21 | 22 | int turns = minTurns(s, start, end - 1, temp) + 1; 23 | for (int i = start; i < end; i++) { 24 | if (s.charAt(i) == s.charAt(end)) { 25 | turns = Math.min(turns, minTurns(s, start, i, temp) + minTurns(s, i + 1, end - 1, temp)); 26 | } 27 | } 28 | 29 | temp[start][end] = turns; 30 | return turns; 31 | } 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /Medium/1631. Path With Minimum Effort/sol.md: -------------------------------------------------------------------------------- 1 | 1. Initialize a priority queue to store the nodes that need to be visited. The priority queue is sorted in descending order of the effort required to reach the node. 2 | 2. Add the source node to the priority queue with an effort of 0. 3 | 3. While the priority queue is not empty: 4 | * Pop the node with the lowest effort from the priority queue. 5 | * If the popped node is the destination node, then return the effort. 6 | * For each neighbor of the popped node: 7 | * Calculate the effort to reach the neighbor. 8 | * If the calculated effort is lower than the current effort for the neighbor, then update the effort for the neighbor and add it to the priority queue. 9 | 4. Return the effort required to reach the destination node, or -1 if the destination node is unreachable. 10 | 11 | The code implements Dijkstra's algorithm efficiently by using a priority queue to store the nodes that need to be visited. Priority queue ensures that the nodes are visited in order of increasing effort, which leads to a more efficient search. -------------------------------------------------------------------------------- /Medium/172. Factorial Trailing Zeroes/sol.md: -------------------------------------------------------------------------------- 1 | ### Simplest, Easy and Optimized java Solution 2 | 3 | Algorithm 4 | 1. Initialize a variable zero to 0. This variable will be used to keep track of the number of trailing zeroes. 5 | 2. Start a loop with i initialized to 5. The loop will continue as long as i is less than or equal to n. 6 | 3. Inside the loop, calculate the number of factors of 5 in n. You can do this by dividing n by i and adding the result to the zero variable. This step accounts for the number of trailing zeroes caused by the multiples of 5 in the factorial of n. 7 | 4. Multiply i by 5 in each iteration of the loop to check for the next power of 5. 8 | 5. Once the loop is finished, return the value of zero, which represents the number of trailing zeroes in the factorial of n. 9 | 10 | Example 1: 11 | 12 | Input: n = 3 13 | 14 | Output: 0 15 | 16 | Explanation: 3! = 6, no trailing zero. 17 | 18 | Example 2: 19 | 20 | Input: n = 5 21 | 22 | Output: 1 23 | 24 | Explanation: 5! = 120, one trailing zero. 25 | 26 | Example 3: 27 | 28 | 29 | Input: n = 0 30 | 31 | Output: 0 -------------------------------------------------------------------------------- /Medium/6. Zigzag Conversion/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String convert(String s, int numRows) { 3 | if(numRows < 2) { 4 | return s; 5 | } 6 | String str =""; 7 | int x = s.length(); 8 | 9 | char ans[][] = new char[numRows][x]; 10 | for(int i = 0 ; i < numRows; i++) { 11 | for(int j = 0; j < x; j++) { 12 | ans[i][j] = '&'; 13 | } 14 | } 15 | for(int i = 0, changer = 1, row = 0; i < s.length(); i++) { 16 | ans[row][i] = s.charAt(i); 17 | if(row == numRows - 1) { 18 | changer = -1; 19 | } 20 | if(row == 0) { 21 | changer = 1; 22 | } 23 | row = row + changer; 24 | } 25 | for(int i = 0 ; i < numRows; i++) { 26 | for(int j = 0; j < x; j++) { 27 | if(ans[i][j] != '&') { 28 | str = str + ans[i][j]; 29 | } 30 | } 31 | } 32 | 33 | return str; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Hard/4. Median of Two Sorted Arrays/sol.java: -------------------------------------------------------------------------------- 1 | public class sol{ 2 | public static void main(String[] args) { 3 | // call the fn here 4 | } 5 | } 6 | class Solution { 7 | public double findMedianSortedArrays(int[] m, int[] n) { 8 | int[] merged = new int[m.length + n.length]; 9 | int i = 0, j = 0, k = 0; 10 | 11 | while (i < m.length && j < n.length) { 12 | if (m[i] <= n[j]) { 13 | merged[k++] = m[i++]; 14 | } else { 15 | merged[k++] = n[j++]; 16 | } 17 | } 18 | 19 | while (i < m.length) { 20 | merged[k++] = m[i++]; 21 | } 22 | 23 | while (j < n.length) { 24 | merged[k++] = n[j++]; 25 | } 26 | 27 | int mid = merged.length / 2; 28 | if (merged.length % 2 == 0){ 29 | int sum = merged[mid] + merged[mid - 1]; 30 | return (double) sum / 2; 31 | } 32 | else{ 33 | return merged[mid]; 34 | } 35 | 36 | 37 | // return avg; 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /Medium/40. Combination Sum II/README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 40. Combination Sum II 2 | 3 | ## Problem Description 4 | Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`. 5 | 6 | Each number in `candidates` may only be used once in the combination. 7 | 8 | **Note:** The solution set must not contain duplicate combinations. 9 | 10 | ### Test Cases 11 | 12 | **Example 1:** 13 | 14 | > **Input:** candidates = [10,1,2,7,6,1,5], target = 8 15 | > 16 | > **Output:** 17 | > 18 | > [ 19 | > 20 | > [1,1,6], 21 | > 22 | > [1,2,5], 23 | > 24 | > [1,7], 25 | > 26 | > [2,6] 27 | > 28 | > ] 29 | 30 | **Example 2:** 31 | 32 | > **Input:** candidates = [2,5,2,1,2], target = 5 33 | > 34 | > **Output:** 35 | > 36 | > [ 37 | > 38 | > [1,2,2], 39 | > 40 | > [5] 41 | > 42 | > ] 43 | 44 | ### Constraints: 45 | 46 | `1 <= candidates.length <= 100` 47 | 48 | `1 <= candidates[i] <= 50` 49 | 50 | `1 <= target <= 30` 51 | 52 | ### Link 53 | 54 | https://leetcode.com/problems/combination-sum-ii/ 55 | -------------------------------------------------------------------------------- /Easy/2423. Remove Letter To Equalize Frequency/Solution.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def equalFrequency(self, word: str) -> bool: 5 | # Step 1: Count the frequencies of each character using Counter. 6 | c = Counter(word) 7 | 8 | # Step 2: Extract the frequencies and sort them. 9 | freq = sorted([c[i] for i in c]) 10 | 11 | # Step 3: Check if there's only one unique frequency. 12 | if len(freq) == 1: 13 | return True 14 | 15 | # Step 4: Check two conditions to determine if it's possible to make frequencies equal. 16 | # Condition 1: Minimum frequency is 1 and all other frequencies are the same. 17 | # Condition 2: All frequencies except the maximum one are the same, and max frequency is one greater. 18 | if (min(freq) == 1 and len(set(freq[1:])) == 1) or (len(set(freq[:-1])) == 1 and freq[-1] == freq[0] + 1): 19 | return True 20 | 21 | # Step 5: If none of the conditions are met, return False. 22 | return False 23 | -------------------------------------------------------------------------------- /Medium/151. Reverse Words in a String/sol.md: -------------------------------------------------------------------------------- 1 | ### Simplest and Easy Approach to Understand and solve a problem 2 | 3 | 1. Split the input string 's' into an array of words using space as the delimiter, and store them in the 'words' array. 4 | 2. Create an empty StringBuilder called 'result' to store the reversed sentence. 5 | 3. Initialize the 'end' variable to the index of the last word in the 'words' array. 6 | 4. Iterate through the 'words' array in a forward order. 7 | 5. Inside the loop, check if the current word is not empty. 8 | 6. If the current word is not empty, insert it at the beginning of the 'result' StringBuilder. 9 | 7. If the current word is not the last word, add a space character before it to separate words. 10 | 8. Repeat steps 5-7 for all words in the 'words' array. 11 | 9. Convert the 'result' StringBuilder to a string using the toString() method. 12 | 10. Return the reversed sentence as the result. 13 | 14 | Example 1: 15 | 16 | Input: s = "the sky is blue" 17 | 18 | Output: "blue is sky the" 19 | 20 | Example 2: 21 | 22 | Input: s = " hello world " 23 | 24 | Output: "world hello" -------------------------------------------------------------------------------- /Medium/5. Longest Palindromic Substring/Solution2.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String longestPalindrome(String s) { 3 | if (s.length() <= 1) { 4 | return s; 5 | } 6 | 7 | int maxLen = 1; 8 | String maxStr = s.substring(0, 1); 9 | 10 | for (int i = 0; i < s.length(); i++) { 11 | for (int j = i + maxLen; j <= s.length(); j++) { 12 | if (j - i > maxLen && isPalindrome(s.substring(i, j))) { 13 | maxLen = j - i; 14 | maxStr = s.substring(i, j); 15 | } 16 | } 17 | } 18 | 19 | return maxStr; 20 | } 21 | 22 | private boolean isPalindrome(String str) { 23 | int left = 0; 24 | int right = str.length() - 1; 25 | 26 | while (left < right) { 27 | if (str.charAt(left) != str.charAt(right)) { 28 | return false; 29 | } 30 | left++; 31 | right--; 32 | } 33 | 34 | return true; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Easy/108. Convert Sorted Array to Binary Search Tree/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public TreeNode sortedArrayToBST(int[] num) { 18 | if (num.length == 0) { 19 | return null; 20 | } 21 | TreeNode head = helper(num, 0, num.length - 1); 22 | return head; 23 | } 24 | 25 | public TreeNode helper(int[] num, int low, int high) { 26 | if (low > high) { 27 | return null; 28 | } 29 | int mid = low + (high-low)/2; 30 | TreeNode node = new TreeNode(num[mid]); 31 | node.left = helper(num, low, mid - 1); 32 | node.right = helper(num, mid + 1, high); 33 | return node; 34 | } 35 | } -------------------------------------------------------------------------------- /Medium/47. Permutations II/Solution.java: -------------------------------------------------------------------------------- 1 | /* 2 | This is a classic backtracking problem except that we need to check for duplicates. 3 | This is solved using two ideas: Hashset and boolean array visited. 4 | */ 5 | class Solution { 6 | List> res; 7 | Set> set = new HashSet(); 8 | public List> permuteUnique(int[] nums) { 9 | boolean[] visited = new boolean[nums.length]; 10 | backtrack(new ArrayList(), visited, nums); 11 | res = new ArrayList(set); 12 | return res; 13 | } 14 | private void backtrack(List sub,boolean[] visited,int[] nums){ 15 | if(sub.size() == nums.length){ 16 | set.add(new ArrayList(sub)); 17 | return; 18 | } 19 | for(int i=0;i=0 && rightreslen){ 11 | res=s.substring(left,right+1); 12 | reslen=right-left+1; 13 | } 14 | left-=1; 15 | right+=1; 16 | } 17 | 18 | // even length; 19 | left=i; 20 | right=i+1; 21 | while(left>=0 && rightreslen){ 23 | res=s.substring(left,right+1); 24 | reslen=right-left+1; 25 | } 26 | left-=1; 27 | right+=1; 28 | } 29 | } 30 | return res; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Hard/72. Edit Distance/Levenshtein/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minDistance(String word1, String word2) { 3 | int row = word1.length(); 4 | int col = word2.length(); 5 | int[][] ed = new int[row + 1][col + 1]; 6 | for(int i = 0; i <= row; i++) 7 | ed[i][0] = i; 8 | for(int j = 0; j <= col; j++) 9 | ed[0][j] = j; 10 | for(int i = 1; i <= row; i++) { 11 | for(int j = 1; j <= col; j++) { 12 | if(word1.charAt(i - 1) == word2.charAt(j - 1)) { 13 | ed[i][j] = ed[i - 1][j - 1]; 14 | } else { 15 | int dia = ed[i - 1][j - 1]; 16 | int hor = ed[i][j - 1]; 17 | int ver = ed[i - 1][j]; 18 | if(dia <= hor && dia <= ver) 19 | ed[i][j] = dia; 20 | else 21 | ed[i][j] = ver < hor ? ver : hor; 22 | ed[i][j]++; 23 | } 24 | } 25 | } 26 | return ed[row][col]; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Medium/204.CountPrimes/README.md: -------------------------------------------------------------------------------- 1 | # LeetCode 204 - Count Primes 2 | 3 | ## Problem Statement 4 | Given an integer `n`, return the number of prime numbers that are strictly less than `n`. 5 | 6 | ### Test Cases 7 | 8 | #### Example 1 9 | - Input: `n = 10` 10 | - Output: `4` 11 | - Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 12 | 13 | #### Example 2 14 | - Input: `n = 0` 15 | - Output: `0` 16 | 17 | ## Solution 18 | This solution utilizes the Sieve of Eratosthenes algorithm to efficiently count the number of prime numbers less than `n`. 19 | 20 | ### Pseudocode 21 | ```java 22 | public int countPrimes(int n) { 23 | // Using Sieve of Eratosthenes 24 | boolean prime[] = new boolean[n + 1]; 25 | int count = 0; 26 | Arrays.fill(prime, true); 27 | prime[0] = false; 28 | for (int i = 2; i * i <= n; i++) { 29 | if (prime[i] == true) { 30 | for (int j = i * i; j <= n; j += i) 31 | prime[j] = false; 32 | } 33 | } 34 | for (int i = 2; i < n; i++) 35 | if (prime[i]) 36 | count++; 37 | return count; 38 | } 39 | -------------------------------------------------------------------------------- /Medium/43. Multiply Strings/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String multiply(String num1, String num2) { 3 | if (num1.equals("0") || num2.equals("0")) { 4 | return "0"; 5 | } 6 | int m = num1.length(); 7 | int n = num2.length(); 8 | int[] product = new int[m + n]; 9 | for (int i = m - 1; i >= 0; i--) { 10 | int digit1 = num1.charAt(i) - '0'; 11 | 12 | for (int j = n - 1; j >= 0; j--) { 13 | int digit2 = num2.charAt(j) - '0'; 14 | int multiply = digit1 * digit2; 15 | int sum = product[i + j + 1] + multiply; 16 | 17 | product[i + j] += sum / 10; 18 | product[i + j + 1] = sum % 10; 19 | } 20 | } 21 | 22 | StringBuilder sb = new StringBuilder(); 23 | 24 | for (int digit : product) { 25 | if (!(sb.length() == 0 && digit == 0)) { 26 | sb.append(digit); 27 | } 28 | } 29 | 30 | return sb.toString(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Medium/2038. Remove Colored Pieces if Both Neighbors are the Same Color/Readme.md: -------------------------------------------------------------------------------- 1 | The given solution approach uses a Counter object to count how many valid moves Alice can make and how many valid moves Bob can make. It iterates through the input string colors to count these moves. 2 | 3 | -->The collections.Counter() is used to count the occurrences of characters in the string. 4 | -->The groupby(colors) function groups consecutive characters in the string. 5 | -->It iterates through the groups and counts how many 'A's and 'B's can be removed according to the game rules. Specifically, it counts the number of 'A's and 'B's that have at least two neighbors of the same color. 6 | -->Finally, it compares the counts of valid moves for Alice ('A') and Bob ('B'). If Alice has more valid moves, it returns True; otherwise, it returns False. 7 | 8 | The idea is that if Alice can make more valid moves than Bob, she has a winning strategy because she will eventually force Bob into a position where he can't make a move. 9 | This solution works under the assumption that both players play optimally and is a good approach to solve the problem efficiently. -------------------------------------------------------------------------------- /Hard/239. Sliding Window Max/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class sol { 3 | public static void main(String[] args) { 4 | // call the fn here 5 | } 6 | 7 | class Solution { 8 | public int[] maxSlidingWindow(int[] nums, int k) { 9 | if (nums == null || nums.length == 0 || k <= 0) { 10 | return new int[0]; 11 | } 12 | 13 | int[] ans = new int[nums.length - k + 1]; 14 | int x = 0; 15 | 16 | Deque deque = new LinkedList<>(); 17 | for (int i = 0; i < nums.length; i++) { 18 | while (!deque.isEmpty() && deque.peek() < i - k + 1) { 19 | deque.poll(); 20 | } 21 | 22 | while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) { 23 | deque.pollLast(); 24 | } 25 | 26 | deque.offer(i); 27 | 28 | if (i >= k - 1) { 29 | ans[x++] = nums[deque.peek()]; 30 | } 31 | } 32 | 33 | return ans; 34 | } 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /Medium/15.3Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | std::vector> threeSum(std::vector& nums) { 5 | std::vector> result; 6 | int n = nums.size(); 7 | 8 | std::sort(nums.begin(), nums.end()); 9 | 10 | for (int i = 0; i < n - 2; ++i) { 11 | if (i > 0 && nums[i] == nums[i - 1]) { 12 | continue; 13 | } 14 | 15 | int target = -nums[i]; 16 | int left = i + 1, right = n - 1; 17 | 18 | while (left < right) { 19 | int sum = nums[left] + nums[right]; 20 | if (sum == target) { 21 | result.push_back({nums[i], nums[left], nums[right]}); 22 | while (left < right && nums[left] == nums[++left]); 23 | while (left < right && nums[right] == nums[--right]); 24 | } else if (sum < target) { 25 | left++; 26 | } else { 27 | right--; 28 | } 29 | } 30 | } 31 | 32 | return result; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Easy/389. Find the Difference/sol.md: -------------------------------------------------------------------------------- 1 | **Algorithm:** 2 | 3 | 1. Calculate the sum of the ASCII codes of all the characters in the first string, `s`. 4 | 2. Calculate the sum of the ASCII codes of all the characters in the second string, `t`. 5 | 3. Subtract the sum of the ASCII codes of `s` from the sum of the ASCII codes of `t`. 6 | 4. Return the character represented by the difference. 7 | 8 | **Time complexity:** O(n), where n is the length of the longer string. 9 | 10 | **Space complexity:** O(1), as we only use a few constant variables. 11 | 12 | for example, consider the following two strings: 13 | 14 | s = "ABCDELMN" 15 | t = "ABCFGLMN" 16 | 17 | 18 | The sum of the ASCII codes of all the characters in `s` is: 19 | 20 | A + B + C + D + E + L + M + N = 65 + 66 + 67 + 68 + 69 + 76 + 77 + 78 = 536 21 | 22 | The sum of the ASCII codes of all the characters in `t` is: 23 | 24 | A + B + C + F + G + L + M + N = 65 + 66 + 67 + 70 + 71 + 76 + 77 + 78 = 540 25 | 26 | The difference between the sum of the ASCII codes of `t` and `s` is 540 - 536 = 4 27 | 28 | The character represented by 4 is `F`. Therefore, the function will return `F`. 29 | 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Jarrian Gojar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Hard/1326. Min no of Taps to Open to Water a Garden/sol.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class sol { 4 | public static void main(String[] args) { 5 | // Call the fn here 6 | } 7 | 8 | public class Solution { 9 | public int minTaps(int n, int[] ranges) { 10 | int[] arr = new int[n + 1]; 11 | Arrays.fill(arr, 0); 12 | 13 | for (int i = 0; i < ranges.length; i++) { 14 | if (ranges[i] == 0) 15 | continue; 16 | int left = Math.max(0, i - ranges[i]); 17 | arr[left] = Math.max(arr[left], i + ranges[i]); 18 | } 19 | 20 | int end = 0, far_can_reach = 0, cnt = 0; 21 | for (int i = 0; i <= n; i++) { 22 | if (i > end) { 23 | if (far_can_reach <= end) 24 | return -1; 25 | end = far_can_reach; 26 | cnt++; 27 | } 28 | far_can_reach = Math.max(far_can_reach, arr[i]); 29 | } 30 | 31 | return cnt + (end < n ? 1 : 0); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Medium/2038. Remove Colored Pieces if/sol.md: -------------------------------------------------------------------------------- 1 | 1. Initialize two variables `countA` and `countB` to keep track of the number of times the characters `A` and `B` appear in consecutive groups of three, respectively. 2 | 2. Iterate over the input string `colors`: 3 | * If the current character and the next two characters are all the same, then increment the corresponding counter `countA` or `countB` depending on the character. 4 | 3. Return `true` if `countA` is greater than `countB`, otherwise return `false`. 5 | 6 | **Example:** 7 | 8 | Consider the following input: 9 | 10 | 11 | colors = "ABBBBAA" 12 | 13 | 14 | The algorithm will work as follows: 15 | 16 | 17 | Iteration | i | colors.charAt(i - 1) | colors.charAt(i) | colors.charAt(i + 1) | countA | countB 18 | -------- | -------- | -------- | -------- | -------- | -------- | -------- 19 | 1 | 1 | A | B | B | 0 | 0 20 | 2 | 2 | B | B | B | 0 | 1 21 | 3 | 3 | B | B | A | 0 | 1 22 | 4 | 4 | B | A | A | 1 | 1 23 | 5 | 5 | A | A | A | 2 | 1 24 | 6 | 6 | A | A | B | 2 | 1 25 | 26 | 27 | The output of the algorithm is `true`, since `countA` is greater than `countB`. -------------------------------------------------------------------------------- /Easy/122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int maxProfit(vector& prices) { 9 | int i = 0; 10 | int j = 1; 11 | int maxProfit = 0; 12 | 13 | while(j < prices.size()){ 14 | if(prices[i] < prices[j]){ 15 | maxProfit += prices[j] - prices[i]; 16 | i++; 17 | j++; 18 | }else{ 19 | i++; 20 | j++; 21 | } 22 | } 23 | 24 | return maxProfit; 25 | } 26 | }; 27 | 28 | int main() { 29 | Solution solution; 30 | vector prices; 31 | int n; 32 | cout << "Enter the number of elements: "; 33 | cin >> n; 34 | 35 | cout << "Enter the elements: "; 36 | for (int i = 0; i < n; i++) { 37 | int price; 38 | cin >> price; 39 | prices.push_back(price); 40 | } 41 | 42 | int result = solution.maxProfit(prices); 43 | cout << "Maximum profit: " << result << endl; 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Medium/142. LinkedList Cycle II/sol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct ListNode 6 | { 7 | int val; 8 | ListNode *next; 9 | ListNode(int x) : val(x), next(NULL) {} 10 | }; 11 | 12 | class Solution 13 | { 14 | public: 15 | ListNode *detectCycle(ListNode *head) 16 | { 17 | 18 | ListNode *slow = head; 19 | ListNode *fast = head; 20 | 21 | while (fast != NULL && fast->next != NULL) 22 | { 23 | slow = slow->next; 24 | fast = fast->next->next; 25 | 26 | if (slow == fast) 27 | { 28 | return getStartingNode(head, slow); 29 | } 30 | } 31 | 32 | return NULL; 33 | } 34 | 35 | private: 36 | ListNode *getStartingNode(ListNode *head, ListNode *meetingPoint) 37 | { 38 | ListNode *slow = head; 39 | while (slow != meetingPoint) 40 | { 41 | slow = slow->next; 42 | meetingPoint = meetingPoint->next; 43 | } 44 | return slow; 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | 51 | // call the fn here 52 | 53 | return 0; 54 | } --------------------------------------------------------------------------------