├── Algorithms ├── Easy │ ├── 104_MaximumDepthOfBinaryTree │ │ └── Solution.cs │ ├── 1078_OccurrencesAfterBigram │ │ └── Solution.py │ ├── 112_PathSum │ │ └── Solution.c │ ├── 118_PascalsTriangle │ │ └── Solution.py │ ├── 121_BestTimeToBuyAndSellStock │ │ └── Solution.c │ ├── 1295_FindNumbersWithEvenNumberOfDigits │ │ ├── Solution.cpp │ │ ├── Solution.cs │ │ └── Solution.java │ ├── 1299_ReplaceElementsWithGreatestElementOnRightSide │ │ ├── Solution.cpp │ │ ├── Solution.cs │ │ └── Solution.java │ ├── 1304_FindNUniqueIntegersSumUpToZero │ │ ├── Resources.md │ │ ├── Solution.cpp │ │ ├── Solution.cs │ │ ├── Solution.java │ │ ├── Solution.py │ │ └── Solution.rb │ ├── 14_LongestCommonPrefix │ │ └── Solution.java │ ├── 1534_CountGoodTriplets │ │ ├── Solution.cpp │ │ ├── Solution.cs │ │ └── Solution.java │ ├── 1588_SumOfAllOddLengthSubarrays │ │ ├── Solution.c │ │ ├── Solution.cpp │ │ ├── Solution.cs │ │ └── Solution.java │ ├── 1646_GetMaximumInGeneratedArray │ │ └── Solution.java │ ├── 167_TwoSumII │ │ └── Solution.cpp │ ├── 1684_CountTheNumberOfConsistentStrings │ │ ├── Solution.cpp │ │ ├── Solution.cs │ │ └── Solution.java │ ├── 1863_SumOfAllSubsetXorTotals │ │ ├── Solution.cpp │ │ ├── Solution.cs │ │ └── Solution.java │ ├── 1_TwoSum │ │ ├── Solution.cpp │ │ ├── Solution.cs │ │ ├── Solution.java │ │ ├── Solution.py │ │ ├── SolutionOne.cpp │ │ └── SolutionOne.py │ ├── 205_IsomorphicStrings │ │ ├── Solution.cpp │ │ ├── Solution.cs │ │ └── Solution.java │ ├── 206_ReverseLinkedList │ │ └── Solution.py │ ├── 20_ValidParentheses │ │ └── Solution.java │ ├── 217_ContainsDuplicate │ │ └── Solution.java │ ├── 21_MergeTwoSortedLists │ │ └── Solution.java │ ├── 234_PalindromeLinkedList │ │ └── Solution.py │ ├── 242_ValidAnagram │ │ └── Solution.py │ ├── 268_MissingNumber │ │ ├── Resources.md │ │ ├── Solution.cpp │ │ ├── Solution.cs │ │ ├── Solution.java │ │ ├── Solution.py │ │ └── Solution.rb │ ├── 26_RemoveDuplicatesFromSortedArray │ │ └── Solution.py │ ├── 278_FirstBadVersion │ │ └── Solution.py │ ├── 414_ThirdMaximumNumber │ │ └── Solution.java │ ├── 561_ArrayPartitionI │ │ ├── Resources.md │ │ ├── Solution.cpp │ │ ├── Solution.cs │ │ ├── Solution.java │ │ ├── Solution.py │ │ └── Solution.rb │ ├── 58_LengthOfLastWord │ │ └── Solution.java │ ├── 645_SetMismatch │ │ ├── Solution.cpp │ │ └── Solution.java │ ├── 70_ClimbingStairs │ │ └── Solution.java │ ├── 746_MinCostClimbingStairs │ │ └── Solution.java │ ├── 7_ReverseInteger │ │ ├── Solution.cpp │ │ ├── Solution.cs │ │ └── Solution.java │ ├── 905_SortArrayByParity │ │ └── Solution.cpp │ ├── 94_BinaryTreeInorderTraversal │ │ └── Solution.py │ └── 9_PalindromeNumber │ │ ├── Solution.cpp │ │ ├── Solution.java │ │ ├── Solution.py │ │ └── SolutionOne.py ├── Hard │ ├── 4_MedianOfTwoSortedArrays │ │ ├── Solution.java │ │ └── Solution.py │ └── 827_MakingALargeIsland │ │ └── Solution.py └── Medium │ ├── 1143_LongestCommonSubsequence │ └── Solution.py │ ├── 11_ContainerWithMostWater │ ├── Solution.java │ └── Soluton.py │ ├── 128_LongestConsecutiveSequence │ └── Solution.py │ ├── 142_LinkedListCycleII │ ├── Resources.md │ └── Solution.cpp │ ├── 22_GenerateParentheses │ └── Solution.py │ ├── 238_ProductOfArrayExceptSelf │ ├── Solution.java │ └── Solution.py │ ├── 287_FindTheDuplicateNumber │ ├── Solution.cpp │ ├── Solution.py │ └── SolutionOne.cpp │ ├── 36_ValidSudoku │ └── Solution.py │ ├── 3_LongestSubstringWithoutRepeatingCharacters │ ├── Solution.cpp │ ├── Solution.cs │ └── Solution.java │ ├── 494_TargetSum │ └── Solution.java │ ├── 49_GroupAnagrams │ └── Solution.py │ ├── 53_MaximumSubarray │ ├── Solution.java │ └── Solution.py │ ├── 57_InsertInterval │ └── Solution.java │ ├── 62_UniquePaths │ └── Solution.py │ └── 983_MinimumCostForTickets │ └── Solution.java ├── CONTRIBUTING.md ├── CONTRIBUTORS.md ├── Database └── Easy │ ├── 175_CombineTwoTables.sql │ ├── 176_SecondHighestSalary.sql │ ├── 181_EmployeesEarningMoreThanTheirManagers.sql │ ├── 182_DuplicateEmails.sql │ ├── 183_CustomersWhoNeverOrder.sql │ ├── 196_DeleteDuplicateEmails.sql │ ├── 595_BigCountries.sql │ ├── 596_ClassesMoreThan5Students.sql │ ├── 620_NotBoringMovies.sql │ └── 627_SwapSalary.sql ├── HOWTO.md ├── LICENSE ├── README.md └── RESOURCES.md /Algorithms/Easy/104_MaximumDepthOfBinaryTree/Solution.cs: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * public int val; 5 | * public TreeNode left; 6 | * public TreeNode right; 7 | * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { 8 | * this.val = val; 9 | * this.left = left; 10 | * this.right = right; 11 | * } 12 | * } 13 | */ 14 | public class Solution { 15 | public int MaxDepth(TreeNode root) { 16 | if (root == null) return 0; 17 | int leftTree = MaxDepth(root.left) + 1; 18 | int rightTree = MaxDepth(root.right) + 1; 19 | return leftTree >= rightTree ? leftTree : rightTree; 20 | } 21 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1078_OccurrencesAfterBigram/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findOcurrences(self, text: str, first: str, second: str) -> List[str]: 3 | array_of_words = text.split() 4 | third_words = list() 5 | 6 | for i in range(1, len(array_of_words) - 1): 7 | if array_of_words[i] == second and array_of_words[i - 1] == first: 8 | third_words.append(array_of_words[i + 1]) 9 | 10 | return third_words -------------------------------------------------------------------------------- /Algorithms/Easy/112_PathSum/Solution.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * struct TreeNode *left; 6 | * struct TreeNode *right; 7 | * }; 8 | */ 9 | 10 | bool hasPathSum(struct TreeNode* root, int targetSum) { 11 | if(root == NULL) 12 | return false; 13 | 14 | if (root->left == NULL && root->right == NULL) { 15 | if (root->val == targetSum) 16 | return true; 17 | 18 | return false; 19 | } 20 | 21 | return (hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val)); 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/Easy/118_PascalsTriangle/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generate(self, numRows: int) -> List[List[int]]: 3 | triangle = [] 4 | first_row = [1] 5 | 6 | triangle.append(first_row) 7 | 8 | for i in range(1, numRows): 9 | prev_row = triangle[i - 1] 10 | new_row = [1] 11 | 12 | for j in range(1, i): 13 | new_row.append(prev_row[j - 1] + prev_row[j]) 14 | 15 | new_row.append(1) 16 | triangle.append(new_row) 17 | 18 | return triangle -------------------------------------------------------------------------------- /Algorithms/Easy/121_BestTimeToBuyAndSellStock/Solution.c: -------------------------------------------------------------------------------- 1 | int maxProfit(int* prices, int pricesSize){ 2 | int answer = 0; 3 | int buyingPrice = prices[0]; 4 | 5 | for (int i = 1; i < pricesSize; i++){ 6 | if (prices[i] < buyingPrice) 7 | buyingPrice = prices[i]; 8 | else if (prices[i] - buyingPrice > answer) 9 | answer = prices[i] - buyingPrice; 10 | } 11 | 12 | return answer; 13 | } 14 | -------------------------------------------------------------------------------- /Algorithms/Easy/1295_FindNumbersWithEvenNumberOfDigits/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countDigit(int n) { 4 | return floor(log10(n) + 1); 5 | } 6 | 7 | int findNumbers(vector& nums) { 8 | int ans = 0, n = nums.size(); 9 | for (int i = 0; i < n; i++) { 10 | if (!(countDigit(nums[i]) & 1)) 11 | ans++; 12 | } 13 | return ans; 14 | } 15 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/1295_FindNumbersWithEvenNumberOfDigits/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int CountDigit(int n) { 3 | return (int)Math.Floor(Math.Log10(n) + 1); 4 | } 5 | 6 | public int FindNumbers(int[] nums) { 7 | int ans = 0, n = nums.Length; 8 | for (int i = 0; i < n; i++) { 9 | if (CountDigit(nums[i]) % 2 == 0) 10 | ans++; 11 | } 12 | return ans; 13 | } 14 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1295_FindNumbersWithEvenNumberOfDigits/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countDigit(int n) { 3 | return (int)Math.floor(Math.log10(n) + 1); 4 | } 5 | 6 | public int findNumbers(int[] nums) { 7 | int ans = 0, n = nums.length; 8 | for (int i = 0; i < n; i++) { 9 | if (countDigit(nums[i]) % 2 == 0) 10 | ans++; 11 | } 12 | return ans; 13 | } 14 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1299_ReplaceElementsWithGreatestElementOnRightSide/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector replaceElements(vector& arr) { 4 | int size = arr.size(), maxVal = -1; 5 | vector answer (size, 0); 6 | 7 | for (int i = size - 1; i >= 0; i--) { 8 | answer[i] = maxVal; 9 | maxVal = max(maxVal, arr[i]); 10 | } 11 | 12 | return answer; 13 | } 14 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/1299_ReplaceElementsWithGreatestElementOnRightSide/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] ReplaceElements(int[] arr) { 3 | int size = arr.Length, maxVal = -1; 4 | int[] answer = new int[size]; 5 | 6 | for (int i = size - 1; i >= 0; i--) { 7 | answer[i] = maxVal; 8 | maxVal = Math.Max(maxVal, arr[i]); 9 | } 10 | 11 | return answer; 12 | } 13 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1299_ReplaceElementsWithGreatestElementOnRightSide/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] replaceElements(int[] arr) { 3 | int size = arr.length, maxVal = -1; 4 | int[] answer = new int[size]; 5 | 6 | for (int i = size - 1; i >= 0; i--) { 7 | answer[i] = maxVal; 8 | maxVal = Math.max(maxVal, arr[i]); 9 | } 10 | 11 | return answer; 12 | } 13 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1304_FindNUniqueIntegersSumUpToZero/Resources.md: -------------------------------------------------------------------------------- 1 | # Resources 2 | 3 | - [Editorial Series - LeetCode 1304. Find N Unique Integers Sum up to Zero](https://tahanima.github.io/2021/05/31/editorial-series-leetcode-1304-find-n-unique-integers-sum-up-to-zero/) -------------------------------------------------------------------------------- /Algorithms/Easy/1304_FindNUniqueIntegersSumUpToZero/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sumZero(int n) { 4 | vector answer; 5 | 6 | if (n % 2 == 1) 7 | answer.push_back(0); 8 | 9 | n /= 2; 10 | 11 | for (int i = 1; i <= n; i++) { 12 | answer.push_back(i); 13 | answer.push_back(-i); 14 | } 15 | 16 | return answer; 17 | } 18 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/1304_FindNUniqueIntegersSumUpToZero/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] SumZero(int n) { 3 | int[] answer = new int[n]; 4 | int index = 0; 5 | 6 | if (n % 2 == 1) 7 | answer[index++] = 0; 8 | 9 | n /= 2; 10 | 11 | for (int i = 1; i <= n; i++) { 12 | answer[index++] = i; 13 | answer[index++] = -i; 14 | } 15 | 16 | return answer; 17 | } 18 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1304_FindNUniqueIntegersSumUpToZero/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] sumZero(int n) { 3 | int[] answer = new int[n]; 4 | int index = 0; 5 | 6 | if (n % 2 == 1) 7 | answer[index++] = 0; 8 | 9 | n /= 2; 10 | 11 | for (int i = 1; i <= n; i++) { 12 | answer[index++] = i; 13 | answer[index++] = -i; 14 | } 15 | 16 | return answer; 17 | } 18 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1304_FindNUniqueIntegersSumUpToZero/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sumZero(self, n): 3 | """ 4 | :type n: int 5 | :rtype: List[int] 6 | """ 7 | answer = [i for i in range(1, (n // 2) + 1)] 8 | answer += [-i for i in answer] 9 | 10 | return answer if (n % 2 == 0) else answer + [0] -------------------------------------------------------------------------------- /Algorithms/Easy/1304_FindNUniqueIntegersSumUpToZero/Solution.rb: -------------------------------------------------------------------------------- 1 | # @param {Integer} n 2 | # @return {Integer[]} 3 | def sum_zero(n) 4 | answer = [] 5 | answer << 0 if (n % 2 == 1) 6 | n /= 2 7 | n.times { |i| answer << (i + 1) << -(i + 1) } 8 | answer 9 | end -------------------------------------------------------------------------------- /Algorithms/Easy/14_LongestCommonPrefix/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static boolean isCommonForLength(int size, String[] strs) { 3 | String substr = ""; 4 | 5 | for (String s: strs) { 6 | if (s.length() < size) { 7 | return false; 8 | } 9 | 10 | if (substr.equals("")) { 11 | substr = s.substring(0, size); 12 | } else { 13 | if (!substr.equals(s.substring(0, size))) { 14 | return false; 15 | } 16 | } 17 | } 18 | 19 | return true; 20 | } 21 | 22 | public String longestCommonPrefix(String[] strs) { 23 | int lo = 0, hi = 201, mid = 0; 24 | 25 | for (int iter = 0; iter <= 8; iter++) { 26 | mid = (lo + hi) / 2; 27 | 28 | if (isCommonForLength(mid, strs)) { 29 | lo = mid; 30 | } else { 31 | hi = mid; 32 | } 33 | } 34 | 35 | return mid > 0 ? strs[0].substring(0, mid): ""; 36 | } 37 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1534_CountGoodTriplets/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countGoodTriplets(vector& arr, int a, int b, int c) { 4 | int size = arr.size(), count = 0; 5 | 6 | for (int i = 0; i < size; i++) { 7 | for (int j = i + 1; j < size; j++) { 8 | for (int k = j + 1; k < size; k++) { 9 | bool isGoodTriplet = abs(arr[i] - arr[j]) <= a 10 | && abs(arr[j] - arr[k]) <= b 11 | && abs(arr[i] - arr[k]) <= c; 12 | 13 | if (isGoodTriplet) 14 | count++; 15 | } 16 | } 17 | } 18 | 19 | return count; 20 | } 21 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/1534_CountGoodTriplets/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int CountGoodTriplets(int[] arr, int a, int b, int c) { 3 | int size = arr.Length, count = 0; 4 | 5 | for (int i = 0; i < size; i++) { 6 | for (int j = i + 1; j < size; j++) { 7 | for (int k = j + 1; k < size; k++) { 8 | bool isGoodTriplet = Math.Abs(arr[i] - arr[j]) <= a 9 | && Math.Abs(arr[j] - arr[k]) <= b 10 | && Math.Abs(arr[i] - arr[k]) <= c; 11 | 12 | if (isGoodTriplet) 13 | count++; 14 | } 15 | } 16 | } 17 | 18 | return count; 19 | } 20 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1534_CountGoodTriplets/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countGoodTriplets(int[] arr, int a, int b, int c) { 3 | int size = arr.length, count = 0; 4 | 5 | for (int i = 0; i < size; i++) { 6 | for (int j = i + 1; j < size; j++) { 7 | for (int k = j + 1; k < size; k++) { 8 | boolean isGoodTriplet = Math.abs(arr[i] - arr[j]) <= a 9 | && Math.abs(arr[j] - arr[k]) <= b 10 | && Math.abs(arr[i] - arr[k]) <= c; 11 | 12 | if (isGoodTriplet) 13 | count++; 14 | } 15 | } 16 | } 17 | 18 | return count; 19 | } 20 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1588_SumOfAllOddLengthSubarrays/Solution.c: -------------------------------------------------------------------------------- 1 | int sumOddLengthSubarrays(int* arr, int arrSize){ 2 | int ans = 0; 3 | 4 | for (int len = 1; len <= arrSize; len += 2) { 5 | int sum = 0; 6 | 7 | for (int i = 0; i < len; i++) { 8 | sum += arr[i]; 9 | } 10 | 11 | ans += sum; 12 | 13 | for (int i = len; i < arrSize; i++) { 14 | sum += (arr[i] - arr[i - len]); 15 | ans += sum; 16 | } 17 | } 18 | 19 | return ans; 20 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1588_SumOfAllOddLengthSubarrays/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int sumOddLengthSubarrays(vector& arr) { 4 | int ans = 0, n = arr.size(); 5 | 6 | for (int len = 1; len <= n; len += 2) { 7 | int sum = 0; 8 | for (int i = 0; i < len; i++) { 9 | sum += arr[i]; 10 | } 11 | ans += sum; 12 | for (int i = len; i < n; i++) { 13 | sum += (arr[i] - arr[i - len]); 14 | ans += sum; 15 | } 16 | } 17 | 18 | return ans; 19 | } 20 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/1588_SumOfAllOddLengthSubarrays/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int SumOddLengthSubarrays(int[] arr) { 3 | int ans = 0, n = arr.Length; 4 | 5 | for (int len = 1; len <= n; len += 2) { 6 | int sum = 0; 7 | for (int i = 0; i < len; i++) { 8 | sum += arr[i]; 9 | } 10 | ans += sum; 11 | for (int i = len; i < n; i++) { 12 | sum += (arr[i] - arr[i - len]); 13 | ans += sum; 14 | } 15 | } 16 | 17 | return ans; 18 | } 19 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1588_SumOfAllOddLengthSubarrays/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int sumOddLengthSubarrays(int[] arr) { 3 | int ans = 0, n = arr.length; 4 | 5 | for (int len = 1; len <= n; len += 2) { 6 | int sum = 0; 7 | for (int i = 0; i < len; i++) { 8 | sum += arr[i]; 9 | } 10 | ans += sum; 11 | for (int i = len; i < n; i++) { 12 | sum += (arr[i] - arr[i - len]); 13 | ans += sum; 14 | } 15 | } 16 | 17 | return ans; 18 | } 19 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1646_GetMaximumInGeneratedArray/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int getMaximumGenerated(int n) { 3 | int[] nums = new int[n + 1]; 4 | int max = 0; 5 | 6 | for (int i = 0; i <= n; i++) { 7 | if (i < 2) { 8 | nums[i] = i; 9 | } else if (i % 2 == 0) { 10 | nums[i] = nums[i / 2]; 11 | } else { 12 | nums[i] = nums[(i - 1) / 2] + nums[1 + (i - 1) / 2]; 13 | } 14 | 15 | max = Math.max(max, nums[i]); 16 | } 17 | 18 | return max; 19 | } 20 | } -------------------------------------------------------------------------------- /Algorithms/Easy/167_TwoSumII/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& numbers, int target) { 4 | int index1 = 0, index2 = numbers.size() - 1, sum; 5 | vector answer; 6 | 7 | while(index1 < index2) { 8 | sum = numbers[index1] + numbers[index2]; 9 | 10 | if(sum == target) 11 | break; 12 | else if(sum < target) 13 | index1++; 14 | else 15 | index2--; 16 | } 17 | 18 | answer.push_back(index1 + 1); 19 | answer.push_back(index2 + 1); 20 | 21 | return answer; 22 | } 23 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/1684_CountTheNumberOfConsistentStrings/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int markCharacters(string &word) { 4 | int marked = 0; 5 | 6 | for (char ch : word) { 7 | int position = ch - 'a'; 8 | marked |= 1 << position; 9 | } 10 | 11 | return marked; 12 | } 13 | 14 | int countConsistentStrings(string allowed, vector& words) { 15 | int markedAllowed = markCharacters(allowed); 16 | int answer = 0; 17 | 18 | for (string word : words) { 19 | int markedWord = markCharacters(word); 20 | 21 | if ((markedWord & markedAllowed) == markedWord) 22 | answer++; 23 | } 24 | 25 | return answer; 26 | } 27 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/1684_CountTheNumberOfConsistentStrings/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MarkCharacters(String word) { 3 | int marked = 0; 4 | 5 | foreach (char ch in word.ToCharArray()) { 6 | int position = ch - 'a'; 7 | marked |= 1 << position; 8 | } 9 | 10 | return marked; 11 | } 12 | 13 | public int CountConsistentStrings(string allowed, string[] words) { 14 | int markedAllowed = MarkCharacters(allowed); 15 | int answer = 0; 16 | 17 | foreach (String word in words) { 18 | int markedWord = MarkCharacters(word); 19 | 20 | if ((markedWord & markedAllowed) == markedWord) 21 | answer++; 22 | } 23 | 24 | return answer; 25 | } 26 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1684_CountTheNumberOfConsistentStrings/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int markCharacters(String word) { 3 | int marked = 0; 4 | 5 | for (char ch : word.toCharArray()) { 6 | int position = Character.getNumericValue(ch); 7 | marked |= 1 << position; 8 | } 9 | 10 | return marked; 11 | } 12 | 13 | public int countConsistentStrings(String allowed, String[] words) { 14 | int markedAllowed = markCharacters(allowed); 15 | int answer = 0; 16 | 17 | for (String word : words) { 18 | int markedWord = markCharacters(word); 19 | 20 | if ((markedWord & markedAllowed) == markedWord) 21 | answer++; 22 | } 23 | 24 | return answer; 25 | } 26 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1863_SumOfAllSubsetXorTotals/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subsetXORSum(vector& nums) { 4 | int n = nums.size(), sum = 0; 5 | int limit = (1 << n) - 1; 6 | 7 | for (int mask = 1; mask <= limit; mask++) { 8 | int _xor = 0; 9 | for (int pos = 0; pos < n; pos++) { 10 | if (mask & (1 << pos)) { 11 | _xor ^= nums[pos]; 12 | } 13 | } 14 | sum += _xor; 15 | } 16 | 17 | return sum; 18 | } 19 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/1863_SumOfAllSubsetXorTotals/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int SubsetXORSum(int[] nums) { 3 | int n = nums.Length, sum = 0; 4 | int limit = (1 << n) - 1; 5 | 6 | for (int mask = 1; mask <= limit; mask++) { 7 | int _xor = 0; 8 | for (int pos = 0; pos < n; pos++) { 9 | if ((mask & (1 << pos)) > 0) { 10 | _xor ^= nums[pos]; 11 | } 12 | } 13 | sum += _xor; 14 | } 15 | 16 | return sum; 17 | } 18 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1863_SumOfAllSubsetXorTotals/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subsetXORSum(int[] nums) { 3 | int n = nums.length, sum = 0; 4 | int limit = (1 << n) - 1; 5 | 6 | for (int mask = 1; mask <= limit; mask++) { 7 | int _xor = 0; 8 | for (int pos = 0; pos < n; pos++) { 9 | if ((mask & (1 << pos)) > 0) { 10 | _xor ^= nums[pos]; 11 | } 12 | } 13 | sum += _xor; 14 | } 15 | 16 | return sum; 17 | } 18 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1_TwoSum/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | int n = nums.size(); 5 | vector ans; 6 | 7 | for (int i = 0; i < n; i++) { 8 | for (int j = i + 1; j < n; j++) { 9 | if (nums[i] + nums[j] == target) { 10 | ans.push_back(i); 11 | ans.push_back(j); 12 | 13 | return ans; 14 | } 15 | } 16 | } 17 | 18 | return ans; 19 | } 20 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/1_TwoSum/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] TwoSum(int[] nums, int target) { 3 | int n = nums.Length; 4 | 5 | for (int i = 0; i < n; i++) { 6 | for (int j = i + 1; j < n; j++) { 7 | if (nums[i] + nums[j] == target) 8 | return new int []{i, j}; 9 | } 10 | } 11 | 12 | return new int []{-1, -1}; 13 | } 14 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1_TwoSum/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] nums, int target) { 3 | int n = nums.length; 4 | 5 | for (int i = 0; i < n; i++) { 6 | for (int j = i + 1; j < n; j++) { 7 | if (nums[i] + nums[j] == target) 8 | return new int []{i, j}; 9 | } 10 | } 11 | 12 | return new int []{-1, -1}; 13 | } 14 | } -------------------------------------------------------------------------------- /Algorithms/Easy/1_TwoSum/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | num_idx_map = {} 4 | 5 | for idx, num in enumerate(nums): 6 | difference = target - num 7 | if difference in num_idx_map: 8 | return [num_idx_map[difference], idx] 9 | else: 10 | num_idx_map[num] = idx 11 | -------------------------------------------------------------------------------- /Algorithms/Easy/1_TwoSum/SolutionOne.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | vector> valueIndexPair; 5 | vector answer; 6 | int index1, index2, sum; 7 | 8 | for(int k = 0; k < nums.size(); k++) { 9 | valueIndexPair.push_back(pair(nums[k], k)); 10 | } 11 | 12 | sort(valueIndexPair.begin(), valueIndexPair.end()); 13 | 14 | index1 = 0; 15 | index2 = valueIndexPair.size() - 1; 16 | 17 | while(index1 < index2) { 18 | sum = valueIndexPair[index1].first + valueIndexPair[index2].first; 19 | 20 | if(sum == target) 21 | break; 22 | else if(sum < target) 23 | index1++; 24 | else 25 | index2--; 26 | } 27 | 28 | answer.push_back(valueIndexPair[index1].second); 29 | answer.push_back(valueIndexPair[index2].second); 30 | 31 | return answer; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Algorithms/Easy/1_TwoSum/SolutionOne.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | # creating a list with their respective indices 4 | num_with_idx = [(num, idx) for idx, num in enumerate(nums)] 5 | # sorting list of tuple based on their first value 6 | num_with_idx = sorted(num_with_idx, key=lambda x: x[0]) 7 | 8 | # Two-Pointer approach 9 | left_idx = 0 10 | right_idx = len(nums) - 1 11 | 12 | while left_idx < right_idx: 13 | sum_result = num_with_idx[left_idx][0] + num_with_idx[right_idx][0] 14 | if sum_result > target: 15 | right_idx -= 1 16 | elif sum_result < target: 17 | left_idx += 1 18 | elif sum_result == target: 19 | return [num_with_idx[left_idx][1], num_with_idx[right_idx][1]] -------------------------------------------------------------------------------- /Algorithms/Easy/205_IsomorphicStrings/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isIsomorphic(string s, string t) { 4 | int len = s.size(); 5 | bool isIso = true; 6 | unordered_map mapping; 7 | unordered_map mappedTo; 8 | 9 | for (int i = 0; i < len; i++) { 10 | if (mapping.count(s[i])) { 11 | char ch = mapping[s[i]]; 12 | 13 | if (t[i] != ch) { 14 | isIso = false; 15 | break; 16 | } 17 | } else { 18 | if (mappedTo.count(t[i])) { 19 | isIso = false; 20 | break; 21 | } 22 | 23 | mapping[s[i]] = t[i]; 24 | mappedTo[t[i]] = s[i]; 25 | } 26 | } 27 | 28 | return isIso; 29 | } 30 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/205_IsomorphicStrings/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool IsIsomorphic(string s, string t) { 3 | int len = s.Length; 4 | bool isIso = true; 5 | int[] mapping = new int[130]; 6 | int[] mappedTo = new int[130]; 7 | 8 | for (int i = 0; i < len; i++) { 9 | if (mapping[s[i]] > 0) { 10 | int val = mapping[s[i]]; 11 | 12 | if ((int)t[i] != val) { 13 | isIso = false; 14 | break; 15 | } 16 | } else { 17 | if (mappedTo[t[i]] > 0) { 18 | isIso = false; 19 | break; 20 | } 21 | 22 | mapping[s[i]] = t[i]; 23 | mappedTo[t[i]] = s[i]; 24 | } 25 | } 26 | 27 | return isIso; 28 | } 29 | } -------------------------------------------------------------------------------- /Algorithms/Easy/205_IsomorphicStrings/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isIsomorphic(String s, String t) { 3 | int len = s.length(); 4 | boolean isIso = true; 5 | int[] mapping = new int[130]; 6 | int[] mappedTo = new int[130]; 7 | 8 | for (int i = 0; i < len; i++) { 9 | if (mapping[s.codePointAt(i)] > 0) { 10 | int val = mapping[s.codePointAt(i)]; 11 | 12 | if (t.codePointAt(i) != val) { 13 | isIso = false; 14 | break; 15 | } 16 | } else { 17 | if (mappedTo[t.codePointAt(i)] > 0) { 18 | isIso = false; 19 | break; 20 | } 21 | 22 | mapping[s.codePointAt(i)] = t.codePointAt(i); 23 | mappedTo[t.codePointAt(i)] = s.codePointAt(i); 24 | } 25 | } 26 | 27 | return isIso; 28 | } 29 | } -------------------------------------------------------------------------------- /Algorithms/Easy/206_ReverseLinkedList/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: 3 | prev = None 4 | 5 | while head != None: 6 | next = head.next 7 | head.next = prev 8 | prev = head 9 | head = next 10 | 11 | return prev 12 | -------------------------------------------------------------------------------- /Algorithms/Easy/20_ValidParentheses/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isValid(String s) { 3 | Stack st = new Stack(); 4 | 5 | for (int i = 0; i < s.length(); i++) { 6 | if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') { 7 | st.push(s.charAt(i)); 8 | } else { 9 | char c; 10 | 11 | if (st.size() > 0) 12 | c = st.pop(); 13 | else 14 | return false; 15 | 16 | if (s.charAt(i) == ']' && c != '[') 17 | return false; 18 | 19 | if (s.charAt(i) == '}' && c != '{') 20 | return false; 21 | 22 | if (s.charAt(i) == ')' && c != '(') 23 | return false; 24 | } 25 | } 26 | 27 | if (st.size() > 0) 28 | return false; 29 | 30 | return true; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/Easy/217_ContainsDuplicate/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean containsDuplicate(int[] nums) { 3 | Arrays.sort(nums); 4 | 5 | for (int i = 1; i < nums.length; i++) { 6 | if (nums[i] == nums[i - 1]) 7 | return true; 8 | } 9 | 10 | return false; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Algorithms/Easy/21_MergeTwoSortedLists/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode mergeTwoLists(ListNode list1, ListNode list2) { 13 | if (list1 == null) { 14 | return list2; 15 | } 16 | 17 | if (list2 == null) { 18 | return list1; 19 | } 20 | 21 | ListNode mergedHead = null; 22 | ListNode temporaryHead = null; 23 | 24 | while (list1 != null || list2 != null) { 25 | if (list1 == null && list2 != null) { 26 | ListNode node = new ListNode(list2.val); 27 | 28 | if (mergedHead == null) { 29 | mergedHead = node; 30 | } else { 31 | temporaryHead.next = node; 32 | } 33 | 34 | temporaryHead = node; 35 | list2 = list2.next; 36 | } else if (list1 != null && list2 == null) { 37 | ListNode node = new ListNode(list1.val); 38 | 39 | if (mergedHead == null) { 40 | mergedHead = node; 41 | } else { 42 | temporaryHead.next = node; 43 | } 44 | 45 | temporaryHead = node; 46 | list1 = list1.next; 47 | } else { 48 | if (list1.val < list2.val) { 49 | ListNode node = new ListNode(list1.val); 50 | 51 | if (mergedHead == null) { 52 | mergedHead = node; 53 | } else { 54 | temporaryHead.next = node; 55 | } 56 | 57 | temporaryHead = node; 58 | list1 = list1.next; 59 | } else { 60 | ListNode node = new ListNode(list2.val); 61 | 62 | if (mergedHead == null) { 63 | mergedHead = node; 64 | } else { 65 | temporaryHead.next = node; 66 | } 67 | 68 | temporaryHead = node; 69 | list2 = list2.next; 70 | } 71 | } 72 | } 73 | 74 | return mergedHead; 75 | } 76 | } -------------------------------------------------------------------------------- /Algorithms/Easy/234_PalindromeLinkedList/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, head: Optional[ListNode]) -> bool: 3 | fast, slow = head, head 4 | 5 | while fast != None and fast.next != None: 6 | fast = fast.next.next 7 | slow = slow.next 8 | 9 | slow = self.reverse(slow) 10 | fast = head 11 | 12 | while slow != None: 13 | if fast.val != slow.val: 14 | return False 15 | 16 | fast = fast.next 17 | slow = slow.next 18 | 19 | return True 20 | 21 | def reverse(self, head): 22 | prev = None 23 | 24 | while head != None: 25 | next = head.next 26 | head.next = prev 27 | prev = head 28 | head = next 29 | 30 | return prev -------------------------------------------------------------------------------- /Algorithms/Easy/242_ValidAnagram/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAnagram(self, s: str, t: str) -> bool: 3 | if len(s) != len(t): 4 | return False 5 | 6 | count_t = {} 7 | count_s = {} 8 | 9 | for i in range(len(t)): 10 | count_t[t[i]] = count_t.get(t[i], 0) + 1 11 | count_s[s[i]] = count_s.get(s[i], 0) + 1 12 | 13 | for key in count_s.keys(): 14 | if count_t.get(key) == None or count_t[key] != count_s[key]: 15 | return False 16 | 17 | return True 18 | -------------------------------------------------------------------------------- /Algorithms/Easy/268_MissingNumber/Resources.md: -------------------------------------------------------------------------------- 1 | # Resources 2 | 3 | - [Editorial Series - LeetCode 268. Missing Number](https://tahanima.github.io/2021/06/02/editorial-series-leetcode-268-missing-number/) -------------------------------------------------------------------------------- /Algorithms/Easy/268_MissingNumber/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | int n = nums.size(); 5 | int missing = n; 6 | 7 | for (int i = 0; i < n; i++) 8 | missing ^= i ^ nums[i]; 9 | 10 | return missing; 11 | } 12 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/268_MissingNumber/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MissingNumber(int[] nums) { 3 | int n = nums.Length; 4 | int missing = n; 5 | 6 | for (int i = 0; i < n; i++) 7 | missing ^= i ^ nums[i]; 8 | 9 | return missing; 10 | } 11 | } -------------------------------------------------------------------------------- /Algorithms/Easy/268_MissingNumber/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int missingNumber(int[] nums) { 3 | int n = nums.length; 4 | int missing = n; 5 | 6 | for (int i = 0; i < n; i++) 7 | missing ^= i ^ nums[i]; 8 | 9 | return missing; 10 | } 11 | } -------------------------------------------------------------------------------- /Algorithms/Easy/268_MissingNumber/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def missingNumber(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | n = len(nums) 8 | missing = n 9 | 10 | for i in range(0, n): 11 | missing ^= i ^ nums[i] 12 | 13 | return missing -------------------------------------------------------------------------------- /Algorithms/Easy/268_MissingNumber/Solution.rb: -------------------------------------------------------------------------------- 1 | # @param {Integer[]} nums 2 | # @return {Integer} 3 | def missing_number(nums) 4 | n = nums.length() 5 | missing = n 6 | n.times { |i| missing ^= i ^ nums[i] } 7 | missing 8 | end -------------------------------------------------------------------------------- /Algorithms/Easy/26_RemoveDuplicatesFromSortedArray/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums: List[int]) -> int: 3 | # go through the array, 4 | # if nth item and (n+1)th item match, pop nth item, but don't forward 5 | # otherwise go forward 6 | 7 | i = 1 8 | 9 | while i < len(nums): 10 | if nums[i - 1] == nums[i]: 11 | nums.pop(i - 1) 12 | else: 13 | i += 1 14 | 15 | return len(nums) 16 | -------------------------------------------------------------------------------- /Algorithms/Easy/278_FirstBadVersion/Solution.py: -------------------------------------------------------------------------------- 1 | # The isBadVersion API is already defined for you. 2 | # @param version, an integer 3 | # @return an integer 4 | # def isBadVersion(version): 5 | 6 | class Solution: 7 | def firstBadVersion(self, n): 8 | """ 9 | :type n: int 10 | :rtype: int 11 | """ 12 | left_version = 1 13 | right_version = n 14 | 15 | while left_version < right_version: 16 | mid_version = (left_version + right_version)//2 17 | 18 | if isBadVersion(mid_version): 19 | right_version = mid_version 20 | else: 21 | left_version = mid_version + 1 22 | 23 | return left_version 24 | -------------------------------------------------------------------------------- /Algorithms/Easy/414_ThirdMaximumNumber/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int thirdMax(int[] nums) { 3 | long max1 = -2147483649l; 4 | long max2 = -2147483649l; 5 | long max3 = -2147483649l; 6 | 7 | for (int i = 0; i < nums.length; i++) { 8 | if (nums[i] > max1) { 9 | max3 = max2; 10 | max2 = max1; 11 | max1 = nums[i]; 12 | } else if (nums[i] > max2 && nums[i] < max1) { 13 | max3 = max2; 14 | max2 = nums[i]; 15 | } else if (nums[i] > max3 && nums[i] < max2) { 16 | max3 = nums[i]; 17 | } 18 | } 19 | 20 | if (max3 == -2147483649l) { 21 | return (int)max1; 22 | } 23 | 24 | return (int)max3; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/Easy/561_ArrayPartitionI/Resources.md: -------------------------------------------------------------------------------- 1 | # Resources 2 | 3 | - [Editorial Series - LeetCode 561. Array Partition I](https://tahanima.github.io/2021/06/13/editorial-series-leetcode-561-array-partition-i/) -------------------------------------------------------------------------------- /Algorithms/Easy/561_ArrayPartitionI/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int arrayPairSum(vector& nums) { 4 | int n = nums.size(), answer = 0; 5 | sort(nums.begin(), nums.end()); 6 | 7 | for (int i = 0; i < n; i += 2) 8 | answer += nums[i]; 9 | 10 | return answer; 11 | } 12 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/561_ArrayPartitionI/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int ArrayPairSum(int[] nums) { 3 | int n = nums.Length, answer = 0; 4 | Array.Sort(nums); 5 | 6 | for (int i = 0; i < n; i += 2) 7 | answer += nums[i]; 8 | 9 | return answer; 10 | } 11 | } -------------------------------------------------------------------------------- /Algorithms/Easy/561_ArrayPartitionI/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int arrayPairSum(int[] nums) { 3 | int n = nums.length, answer = 0; 4 | Arrays.sort(nums); 5 | 6 | for (int i = 0; i < n; i += 2) 7 | answer += nums[i]; 8 | 9 | return answer; 10 | } 11 | } -------------------------------------------------------------------------------- /Algorithms/Easy/561_ArrayPartitionI/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def arrayPairSum(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | nums.sort() 8 | return sum([i for i in nums[::2]]) -------------------------------------------------------------------------------- /Algorithms/Easy/561_ArrayPartitionI/Solution.rb: -------------------------------------------------------------------------------- 1 | # @param {Integer[]} nums 2 | # @return {Integer} 3 | def array_pair_sum(nums) 4 | nums.sort! 5 | (nums.select!.with_index { |_,i| i.even? }).sum 6 | end -------------------------------------------------------------------------------- /Algorithms/Easy/58_LengthOfLastWord/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLastWord(String s) { 3 | int len = 0; 4 | boolean hasWordCountStarted = false; 5 | 6 | for (int i = s.length() - 1; i > -1; i--) { 7 | if (s.charAt(i) == ' ' && hasWordCountStarted) 8 | return len; 9 | 10 | if (s.charAt(i) != ' ') { 11 | hasWordCountStarted = true; 12 | len++; 13 | } 14 | } 15 | 16 | return len; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms/Easy/645_SetMismatch/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findErrorNums(vector& nums) { 4 | int n = nums.size(), sumXor = 0; 5 | int mark[n + 1]; 6 | memset(mark, 0, sizeof(mark)); 7 | vector ans; 8 | 9 | for (int i = 0; i < n; i++) { 10 | sumXor ^= nums[i] ^ (i + 1); 11 | 12 | if (mark[nums[i]] == 1) { 13 | ans.push_back(nums[i]); 14 | } 15 | 16 | mark[nums[i]]++; 17 | } 18 | 19 | ans.push_back(sumXor ^ ans[0]); 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/645_SetMismatch/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] findErrorNums(int[] nums) { 3 | int n = nums.length, sumXor = 0; 4 | int mark[] = new int[n + 1]; 5 | int ans[] = new int[2]; 6 | 7 | for (int i = 0; i < n; i++) { 8 | sumXor ^= nums[i] ^ (i + 1); 9 | 10 | if (mark[nums[i]] == 1) { 11 | ans[0] = nums[i]; 12 | } 13 | 14 | mark[nums[i]]++; 15 | } 16 | 17 | ans[1] = sumXor ^ ans[0]; 18 | return ans; 19 | } 20 | } -------------------------------------------------------------------------------- /Algorithms/Easy/70_ClimbingStairs/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int n; 3 | int[] memo = new int[50]; 4 | 5 | private int solve(int step) { 6 | if (step == n) { 7 | return 1; 8 | } else if (step > n) { 9 | return 0; 10 | } else if (memo[step] != -1) { 11 | return memo[step]; 12 | } else { 13 | memo[step] = solve(step + 1) + solve(step + 2); 14 | 15 | return memo[step]; 16 | } 17 | } 18 | 19 | 20 | public int climbStairs(int n) { 21 | this.n = n; 22 | 23 | for (int i = 0; i < 50; i++) { 24 | memo[i] = -1; 25 | } 26 | 27 | return solve(0); 28 | } 29 | } -------------------------------------------------------------------------------- /Algorithms/Easy/746_MinCostClimbingStairs/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int[] cost; 3 | int[] memo; 4 | int n; 5 | 6 | private int solve(int pos) { 7 | if (pos >= n) { 8 | return 0; 9 | } else if (memo[pos] != -1) { 10 | return memo[pos]; 11 | } else { 12 | memo[pos] = cost[pos] + Math.min(solve(pos + 1), solve(pos + 2)); 13 | 14 | return memo[pos]; 15 | } 16 | } 17 | 18 | public int minCostClimbingStairs(int[] cost) { 19 | this.cost = cost; 20 | n = cost.length; 21 | memo = new int[n + 1]; 22 | 23 | for (int i = 0; i <= n; i++) { 24 | memo[i] = -1; 25 | } 26 | 27 | return Math.min(solve(0), solve(1)); 28 | } 29 | } -------------------------------------------------------------------------------- /Algorithms/Easy/7_ReverseInteger/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | signed long long rev = 0, num = x; 5 | bool is_negative = false; 6 | 7 | if (num < 0) { 8 | is_negative = true; 9 | num *= -1; 10 | } 11 | 12 | for (; num > 0; rev = rev * 10 + (num % 10), num /= 10); 13 | 14 | if (rev > ((1LL << 31) - 1)) 15 | return 0; 16 | 17 | if (is_negative) 18 | rev *= -1LL; 19 | 20 | return (int)rev; 21 | } 22 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/7_ReverseInteger/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int Reverse(int x) { 3 | bool isNegative = false; 4 | 5 | if (x < 0) { 6 | isNegative = true; 7 | x *= -1; 8 | } 9 | 10 | long rev = 0; 11 | 12 | for (; x > 0; rev = rev * 10 + (x % 10), x /= 10); 13 | 14 | if (rev > ((1L << 31) - 1)) 15 | return 0; 16 | 17 | if (isNegative) 18 | rev *= -1; 19 | 20 | return (int)rev; 21 | } 22 | } -------------------------------------------------------------------------------- /Algorithms/Easy/7_ReverseInteger/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int reverse(int x) { 3 | boolean isNegative = false; 4 | 5 | if (x < 0) { 6 | isNegative = true; 7 | x *= -1; 8 | } 9 | 10 | long rev = 0; 11 | for (; x > 0; rev = rev * 10 + (x % 10), x /= 10); 12 | 13 | if (rev > ((1L << 31) - 1)) 14 | return 0; 15 | 16 | if (isNegative) 17 | rev *= -1; 18 | 19 | return (int)rev; 20 | } 21 | } -------------------------------------------------------------------------------- /Algorithms/Easy/905_SortArrayByParity/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortArrayByParity(vector& nums) { 4 | vector even, odd, ans; 5 | int n = nums.size(); 6 | 7 | for (int i = 0; i < n; i++) { 8 | if (nums[i] & 1) 9 | odd.push_back(nums[i]); 10 | else 11 | even.push_back(nums[i]); 12 | } 13 | 14 | for (int i = 0; i < even.size(); ans.push_back(even[i]), i++); 15 | for (int i = 0; i < odd.size(); ans.push_back(odd[i]), i++); 16 | 17 | return ans; 18 | } 19 | }; -------------------------------------------------------------------------------- /Algorithms/Easy/94_BinaryTreeInorderTraversal/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: 3 | stack = [] 4 | output_array = [] 5 | 6 | if root is None: 7 | return output_array 8 | 9 | current = root 10 | 11 | while current is not None or stack: 12 | while current is not None: 13 | stack.append(current) 14 | current = current.left 15 | 16 | current = stack.pop() 17 | output_array.append(current.val) 18 | current = current.right 19 | 20 | return output_array -------------------------------------------------------------------------------- /Algorithms/Easy/9_PalindromeNumber/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) { 4 | if(x < 0 || (x % 10 == 0 && x != 0)) { 5 | return false; 6 | } 7 | 8 | int reverseNumber = 0; 9 | 10 | while(x > reverseNumber) { 11 | reverseNumber = (reverseNumber * 10) + (x % 10); 12 | x = x / 10; 13 | } 14 | 15 | return x == reverseNumber || x == reverseNumber / 10; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Algorithms/Easy/9_PalindromeNumber/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPalindrome(int x) { 3 | if (x < 0) 4 | return false; 5 | 6 | int reversedInteger = 0, lastDigit, temp; 7 | temp = x; // storing the original number to a temporary variable 8 | // Reversing the number 9 | while (temp != 0) { 10 | lastDigit = temp % 10; 11 | reversedInteger = reversedInteger * 10 + lastDigit; 12 | temp = temp / 10; 13 | } 14 | // checking if palindrome or not using condition 15 | if (reversedInteger == x) 16 | return true; 17 | else 18 | return false; 19 | } 20 | } -------------------------------------------------------------------------------- /Algorithms/Easy/9_PalindromeNumber/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPalindrome(self, x: int) -> bool: 3 | if x < 0: 4 | return False 5 | 6 | b = int(str(x) [::-1]) 7 | 8 | if b == x: 9 | return True 10 | 11 | return False 12 | -------------------------------------------------------------------------------- /Algorithms/Easy/9_PalindromeNumber/SolutionOne.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, x: int) -> bool: 3 | x_str = str(x) 4 | left_idx = 0 5 | right_idx = len(x_str) - 1 6 | 7 | while left_idx < right_idx: 8 | if x_str[left_idx] != x_str[right_idx]: 9 | return False 10 | 11 | left_idx += 1 12 | right_idx -= 1 13 | 14 | return True -------------------------------------------------------------------------------- /Algorithms/Hard/4_MedianOfTwoSortedArrays/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double findMedianSortedArrays(int[] nums1, int[] nums2) { 3 | double median = 0.0; 4 | int m = nums1.length; 5 | int n = nums2.length; 6 | int combinedArr[] = new int[m + n]; 7 | int i = 0, j = 0, k = 0; 8 | 9 | while (i < m && j < n) { 10 | if (nums1[i] <= nums2[j]) { 11 | combinedArr[k] = nums1[i++]; 12 | } else { 13 | combinedArr[k] = nums2[j++]; 14 | } 15 | 16 | k++; 17 | } 18 | 19 | while (i < m) { 20 | combinedArr[k] = nums1[i]; 21 | i++; 22 | k++; 23 | } 24 | 25 | while (j < n) { 26 | combinedArr[k] = nums2[j]; 27 | j++; 28 | k++; 29 | } 30 | 31 | if (combinedArr.length % 2 == 0) { 32 | median = (combinedArr[(combinedArr.length / 2) - 1] + combinedArr[combinedArr.length / 2]) / 2.0; 33 | } else { 34 | median = (combinedArr[combinedArr.length / 2]) / 1.0; 35 | } 36 | 37 | return median; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/Hard/4_MedianOfTwoSortedArrays/Solution.py: -------------------------------------------------------------------------------- 1 | # This solution is for python3, may or may not work for other versions 2 | 3 | class Solution: 4 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 5 | nums3 = nums1 + nums2 6 | nums3.sort() 7 | 8 | if len(nums3) % 2 != 0: 9 | return nums3[(len(nums3) // 2)] 10 | else: 11 | return ( 12 | nums3[(len(nums3) // 2) - 1] + 13 | nums3[(len(nums3) // 2)] 14 | ) / 2 15 | -------------------------------------------------------------------------------- /Algorithms/Hard/827_MakingALargeIsland/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | ISLAND_MARK = 1 3 | 4 | def _is_in_boundary(self, row_index: int, column_index: int) -> bool: 5 | if (row_index < self._row_num and row_index >= 0) and \ 6 | (column_index < self._column_num and column_index >= 0): 7 | return True 8 | 9 | return False 10 | 11 | def _get_island_size(self, 12 | grid: List[List[int]], 13 | visited: List[List[int]], 14 | group_id: int, 15 | row_index: int, 16 | column_index: int) -> int: 17 | # [ up, down, left, right] 18 | four_directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] 19 | 20 | queue = [] 21 | island_size = 1 22 | 23 | queue.append((row_index, column_index)) 24 | 25 | while queue: 26 | row_index, column_index = queue.pop(0) 27 | visited[row_index][column_index] = group_id 28 | 29 | for direction in four_directions: 30 | next_row_index = row_index + direction[1] 31 | next_col_index = column_index + direction[0] 32 | 33 | if self._is_in_boundary(next_row_index, next_col_index): 34 | is_part_island = grid[next_row_index][next_col_index] == Solution.ISLAND_MARK 35 | is_visited = visited[next_row_index][next_col_index] != -1 36 | 37 | if is_part_island and not is_visited: 38 | island_size += 1 39 | visited[next_row_index][next_col_index] = group_id 40 | queue.append((next_row_index, next_col_index)) 41 | 42 | return island_size 43 | 44 | def _get_max_island_size(self, 45 | grid: List[List[int]], 46 | visited: List[List[int]], 47 | group_id_island_count_map: Dict[int, int], 48 | row_index: int, 49 | column_index: int) -> int: 50 | # [ up, down, left, right] 51 | four_directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] 52 | 53 | island_size = 1 54 | group_ids = [] 55 | for direction in four_directions: 56 | next_row_index = row_index + direction[1] 57 | next_col_index = column_index + direction[0] 58 | 59 | if self._is_in_boundary(next_row_index, next_col_index): 60 | is_part_island = grid[next_row_index][next_col_index] == Solution.ISLAND_MARK 61 | 62 | if is_part_island: 63 | group_id = visited[next_row_index][next_col_index] 64 | group_ids.append(group_id) 65 | 66 | # using set() to make sure, not to add same group id more than once 67 | for group_id in set(group_ids): 68 | island_size += group_id_island_count_map[group_id] 69 | 70 | return island_size 71 | 72 | 73 | 74 | def largestIsland(self, grid: List[List[int]]) -> int: 75 | self._row_num = len(grid) 76 | self._column_num = len(grid[0]) 77 | 78 | visited = [[-1]*self._column_num for _ in range(self._row_num)] 79 | 80 | group_id = 1 81 | group_id_island_count_map = {} 82 | # will be runnning BFS to explore islands. 83 | for row_index in range(self._row_num): 84 | for column_index in range(self._column_num): 85 | if grid[row_index][column_index] == 1 and visited[row_index][column_index] == -1: 86 | island_size = self._get_island_size(grid, visited, group_id, row_index, column_index) 87 | group_id_island_count_map[group_id] = island_size 88 | group_id += 1 89 | 90 | max_island_size = -1 91 | # now searching for max island size 92 | for row_index in range(self._row_num): 93 | for column_index in range(self._column_num): 94 | if grid[row_index][column_index] == 0: 95 | max_island_size = max(max_island_size, self._get_max_island_size(grid, visited, group_id_island_count_map, row_index, column_index)) 96 | 97 | if max_island_size == -1: 98 | # it means there is no zero in the grid, so the whole grid is the island 99 | max_island_size = self._row_num * self._column_num 100 | 101 | return max_island_size 102 | -------------------------------------------------------------------------------- /Algorithms/Medium/1143_LongestCommonSubsequence/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 3 | text1_length = len(text1) 4 | text2_length = len(text2) 5 | 6 | lcs_array = self._get_initialized_lcs_array(text1_length, text2_length) 7 | 8 | for idx_2, text2_char in enumerate(text2): 9 | row = idx_2 + 1 10 | for idx_1, text1_char in enumerate(text1): 11 | col = idx_1 + 1 12 | if text1_char == text2_char: 13 | lcs_array[row][col] = lcs_array[row-1][col-1] + 1 14 | else: 15 | lcs_array[row][col] = max(lcs_array[row][col-1], lcs_array[row-1][col]) 16 | 17 | return lcs_array[row][col] 18 | 19 | def _get_initialized_lcs_array(self, text1_length, text2_length): 20 | return [[0]*(text1_length+1) for _ in range(text2_length + 1)] 21 | -------------------------------------------------------------------------------- /Algorithms/Medium/11_ContainerWithMostWater/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxArea(int[] height) { 3 | int i = 0; 4 | int j = height.length - 1; 5 | int maxArea = Integer.MIN_VALUE; 6 | 7 | while (i < j) { 8 | int h = Math.min(height[i], height[j]); 9 | int width = j - i; 10 | maxArea = Math.max(maxArea, h*width); 11 | 12 | if (height[i] > height[j]) { 13 | j--; 14 | } else { 15 | i++; 16 | } 17 | } 18 | 19 | return maxArea; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms/Medium/11_ContainerWithMostWater/Soluton.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, height: List[int]) -> int: 3 | max_area = 0 4 | a_pointer, b_pointer = 0, len(height) - 1 5 | 6 | while a_pointer < b_pointer: 7 | if height[a_pointer] < height[b_pointer]: 8 | max_area = max(max_area, height[a_pointer] * (b_pointer - a_pointer)) 9 | a_pointer += 1 10 | else: 11 | max_area = max(max_area, height[b_pointer] * (b_pointer - a_pointer)) 12 | b_pointer -= 1 13 | 14 | return max_area -------------------------------------------------------------------------------- /Algorithms/Medium/128_LongestConsecutiveSequence/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestConsecutive(self, nums: List[int]) -> int: 3 | nums_set = set(nums) 4 | longest = 0 5 | 6 | for num in nums: 7 | length = 0 8 | 9 | if (num - 1) not in nums_set: 10 | while (num + length) in nums_set: 11 | length += 1 12 | 13 | longest = max(longest, length) 14 | 15 | return longest -------------------------------------------------------------------------------- /Algorithms/Medium/142_LinkedListCycleII/Resources.md: -------------------------------------------------------------------------------- 1 | # Resources 2 | 3 | - [Start of Loop in a Linked List](https://www.youtube.com/watch?v=-YiQZi3mLq0) -------------------------------------------------------------------------------- /Algorithms/Medium/142_LinkedListCycleII/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 | class Solution 10 | { 11 | public: 12 | ListNode *detectCycle(ListNode *head) 13 | { 14 | 15 | if (!head) 16 | { 17 | printf("no cycle\n"); 18 | return NULL; 19 | } 20 | 21 | ListNode *tortoise = head, *hare = head; 22 | 23 | while (1) 24 | { 25 | if (!hare->next || !(hare->next)->next) 26 | break; // no cycle 27 | 28 | // move hare pointer 2 times and tortoise pointer 1 times 29 | tortoise = tortoise->next; 30 | hare = (hare->next)->next; 31 | 32 | if (hare == tortoise) 33 | { 34 | ListNode *tortoise1 = head, *tortoise2 = tortoise; 35 | int position = 0; 36 | 37 | while (1) 38 | { 39 | 40 | if (tortoise1 == tortoise2) 41 | { 42 | printf("tail connects to node index %d\n", position); 43 | return tortoise1; 44 | } 45 | 46 | tortoise1 = tortoise1->next; 47 | tortoise2 = tortoise2->next; 48 | position++; 49 | } 50 | } 51 | } 52 | 53 | printf("no cycle\n"); 54 | return NULL; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /Algorithms/Medium/22_GenerateParentheses/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateParenthesis(self, n: int) -> List[str]: 3 | stack = [] 4 | res = [] 5 | 6 | def parenthesis_backtrack(open_paren, close_paren): 7 | if open_paren == close_paren == n: 8 | res.append("".join(stack)) 9 | return 10 | 11 | if open_paren < n: 12 | stack.append("(") 13 | parenthesis_backtrack(open_paren + 1, close_paren) 14 | stack.pop() 15 | 16 | if open_paren > close_paren: 17 | stack.append(")") 18 | parenthesis_backtrack(open_paren, close_paren + 1) 19 | stack.pop() 20 | 21 | parenthesis_backtrack(0, 0) 22 | return res -------------------------------------------------------------------------------- /Algorithms/Medium/238_ProductOfArrayExceptSelf/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] productExceptSelf(int[] nums) { 3 | int size = nums.length; 4 | int[] ans = new int[size]; 5 | int product = 1; 6 | 7 | for (int i = 0; i < size; i++) { 8 | ans[i] = product; 9 | product *= nums[i]; 10 | } 11 | 12 | product = 1; 13 | for (int i = size - 1; i >= 0; i--) { 14 | ans[i] *= product; 15 | product *= nums[i]; 16 | } 17 | 18 | 19 | return ans; 20 | } 21 | } -------------------------------------------------------------------------------- /Algorithms/Medium/238_ProductOfArrayExceptSelf/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def productExceptSelf(self, nums: List[int]) -> List[int]: 3 | prefix_prod = 1 4 | postfix_prod = 1 5 | res = [] 6 | 7 | for i in range(len(nums)): 8 | res.append(prefix_prod) 9 | prefix_prod *= nums[i] 10 | 11 | for i in range(len(nums) - 1, -1, -1): 12 | res[i] = res[i] * postfix_prod 13 | postfix_prod *= nums[i] 14 | 15 | return res -------------------------------------------------------------------------------- /Algorithms/Medium/287_FindTheDuplicateNumber/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | sort(nums.begin(), nums.end()); 5 | int n = nums.size(); 6 | 7 | for (int i = 0; i < n - 1; i++) 8 | { 9 | if(nums[i] == nums[i + 1]) 10 | return nums[i]; 11 | } 12 | 13 | return -1; 14 | } 15 | }; 16 | 17 | // Time Complexity: O(nlogn) 18 | // Space Complexity: O(n) 19 | -------------------------------------------------------------------------------- /Algorithms/Medium/287_FindTheDuplicateNumber/Solution.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def _get_count_of_equal_or_less(self, num_arr: List[int], value: int) -> int: 5 | return len([num for num in num_arr if num <= value]) 6 | 7 | def findDuplicate(self, nums: List[int]) -> int: 8 | left = 1 9 | right = len(nums) - 1 10 | 11 | duplicate_number = -1 12 | 13 | while left <= right: 14 | mid = (left + right)//2 15 | 16 | equal_or_less_count = self._get_count_of_equal_or_less(num_arr=nums, value=mid) 17 | 18 | if equal_or_less_count > mid: 19 | right = mid - 1 20 | duplicate_number = mid 21 | else: 22 | left = mid + 1 23 | 24 | return duplicate_number 25 | -------------------------------------------------------------------------------- /Algorithms/Medium/287_FindTheDuplicateNumber/SolutionOne.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | const int MX = 1e6 + 5; 5 | bitset mask; 6 | 7 | for (int i = 0; i < nums.size(); i++) { 8 | if (mask[nums[i]] == 1) 9 | return nums[i]; 10 | 11 | mask[nums[i]] = 1; 12 | } 13 | 14 | return 0; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Algorithms/Medium/36_ValidSudoku/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValidSudoku(self, board: List[List[str]]) -> bool: 3 | rows = collections.defaultdict(set) 4 | cols = collections.defaultdict(set) 5 | sqrs = collections.defaultdict(set) 6 | 7 | for i in range(9): 8 | for j in range(9): 9 | if board[i][j] == ".": 10 | continue 11 | 12 | if (board[i][j] in rows[i] or 13 | board[i][j] in cols[j] or 14 | board[i][j] in sqrs[(i // 3, j // 3)]): 15 | return False 16 | 17 | rows[i].add(board[i][j]) 18 | cols[j].add(board[i][j]) 19 | sqrs[(i // 3, j // 3)].add(board[i][j]) 20 | 21 | return True -------------------------------------------------------------------------------- /Algorithms/Medium/3_LongestSubstringWithoutRepeatingCharacters/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | int mark[500] = {0}, len = s.size(), en = 0, mx = 0, cnt = 0; 5 | 6 | for (int st = 0; st < len; st++) { 7 | if (mark[s[st]] > 0) { 8 | for (; en < st; en++) { 9 | if (s[en] == s[st]) { 10 | en++; 11 | break; 12 | } 13 | 14 | cnt--; 15 | mark[s[en]]--; 16 | } 17 | } else { 18 | cnt++; 19 | mark[s[st]]++; 20 | mx = max(mx, cnt); 21 | } 22 | } 23 | 24 | return mx; 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms/Medium/3_LongestSubstringWithoutRepeatingCharacters/Solution.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int LengthOfLongestSubstring(string s) { 3 | int[] mark = new int[500]; 4 | int len = s.Length, en = 0, mx = 0, cnt = 0; 5 | 6 | for (int st = 0; st < len; st++) { 7 | if (mark[s[st]] > 0) { 8 | for (; en < st; en++) { 9 | if (s[en] == s[st]) { 10 | en++; 11 | break; 12 | } 13 | 14 | cnt--; 15 | mark[s[en]]--; 16 | } 17 | } else { 18 | cnt++; 19 | mark[s[st]]++; 20 | mx = Math.Max(mx, cnt); 21 | } 22 | } 23 | 24 | return mx; 25 | } 26 | } -------------------------------------------------------------------------------- /Algorithms/Medium/3_LongestSubstringWithoutRepeatingCharacters/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLongestSubstring(String s) { 3 | int[] mark = new int[500]; 4 | int len = s.length(), en = 0, mx = 0, cnt = 0; 5 | 6 | for (int st = 0; st < len; st++) { 7 | if (mark[s.charAt(st)] > 0) { 8 | for (; en < st; en++) { 9 | if (s.charAt(en) == s.charAt(st)) { 10 | en++; 11 | break; 12 | } 13 | 14 | cnt--; 15 | mark[s.charAt(en)]--; 16 | } 17 | } else { 18 | cnt++; 19 | mark[s.charAt(st)]++; 20 | mx = Math.max(mx, cnt); 21 | } 22 | } 23 | 24 | return mx; 25 | } 26 | } -------------------------------------------------------------------------------- /Algorithms/Medium/494_TargetSum/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int[] nums; 3 | int n, target; 4 | HashMap, Integer> dp = new HashMap<>(); 5 | 6 | private int solve(int pos, int sum) { 7 | ArrayList aList = new ArrayList<>(); 8 | aList.add(pos); 9 | aList.add(sum); 10 | 11 | if (pos >= n) { 12 | if (sum == target) { 13 | return 1; 14 | } 15 | 16 | return 0; 17 | } else if (dp.containsKey(aList)) { 18 | return dp.get(aList); 19 | } else { 20 | int ans = solve(pos + 1, sum + nums[pos]); 21 | ans += solve(pos + 1, sum - nums[pos]); 22 | dp.put(aList, ans); 23 | 24 | return ans; 25 | } 26 | } 27 | 28 | public int findTargetSumWays(int[] nums, int target) { 29 | this.nums = nums; 30 | n = nums.length; 31 | this.target = target; 32 | 33 | return solve(1, nums[0]) + solve(1, -nums[0]); 34 | } 35 | } -------------------------------------------------------------------------------- /Algorithms/Medium/49_GroupAnagrams/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 3 | grp_anagrams = {} 4 | 5 | for string in strs: 6 | count = [0] * 26 7 | 8 | for char in string: 9 | count[ord(char) - ord("a")] += 1 10 | 11 | count = tuple(count) 12 | 13 | if grp_anagrams.get(count) == None: 14 | grp_anagrams[count] = [] 15 | 16 | grp_anagrams[count].append(string) 17 | 18 | return grp_anagrams.values() -------------------------------------------------------------------------------- /Algorithms/Medium/53_MaximumSubarray/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxSubArray(int[] nums) { 3 | int maxSum = Integer.MIN_VALUE; 4 | int sum = 0; 5 | 6 | for (int num : nums) { 7 | sum += num; 8 | maxSum = Math.max(sum, maxSum); 9 | 10 | if (sum < 0) { 11 | sum = 0; 12 | } 13 | } 14 | 15 | return maxSum; 16 | } 17 | } -------------------------------------------------------------------------------- /Algorithms/Medium/53_MaximumSubarray/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | current_sum, max_sub_sum = 0, nums[0] 4 | 5 | for num in nums: 6 | if current_sum < 0: 7 | current_sum = 0 8 | 9 | current_sum += num 10 | max_sub_sum = max(current_sum, max_sub_sum) 11 | 12 | return max_sub_sum -------------------------------------------------------------------------------- /Algorithms/Medium/57_InsertInterval/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isOverlapping(int s0, int e0, int s1, int e1) { 3 | if (s0 <= s1 && e0 >= e1) { 4 | return true; 5 | } else if (s0 >= s1 && e0 <= e1) { 6 | return true; 7 | } else if (e0 >= s1 && e0 <= e1) { 8 | return true; 9 | } else if (s0 >= s1 && s0 <= e1) { 10 | return true; 11 | } else { 12 | return false; 13 | } 14 | } 15 | 16 | public int[][] insert(int[][] intervals, int[] newInterval) { 17 | int[] tempInterval = new int[100005]; 18 | int minStart = newInterval[0]; 19 | int maxStart = newInterval[0]; 20 | int size = 0; 21 | 22 | for (int i = 0; i < 100005; tempInterval[i] = -1, i++); 23 | 24 | for (int[] interval: intervals) { 25 | minStart = Math.min(minStart, interval[0]); 26 | maxStart = Math.max(maxStart, interval[0]); 27 | 28 | if (isOverlapping(interval[0], interval[1], newInterval[0], newInterval[1])) { 29 | newInterval[0] = Math.min(interval[0], newInterval[0]); 30 | newInterval[1] = Math.max(interval[1], newInterval[1]); 31 | } else { 32 | tempInterval[interval[0]] = interval[1]; 33 | size++; 34 | } 35 | } 36 | 37 | tempInterval[newInterval[0]] = newInterval[1]; 38 | size++; 39 | 40 | int[][] answer = new int[size][2]; 41 | 42 | for (int i = minStart, j = 0; i <= maxStart; i++) { 43 | if (tempInterval[i] >= 0) { 44 | answer[j][0] = i; 45 | answer[j++][1] = tempInterval[i]; 46 | } 47 | } 48 | 49 | return answer; 50 | } 51 | } -------------------------------------------------------------------------------- /Algorithms/Medium/62_UniquePaths/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m: int, n: int) -> int: 3 | bottom_row = [1] * n 4 | 5 | for column in range(m - 1): 6 | new_row = [1] * n 7 | 8 | for i in range(n - 2, -1, -1): 9 | new_row[i] = new_row[i + 1] + bottom_row[i] 10 | 11 | bottom_row = new_row 12 | 13 | return bottom_row[0] 14 | -------------------------------------------------------------------------------- /Algorithms/Medium/983_MinimumCostForTickets/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int[] memo = new int[400]; 3 | 4 | public int solve(int i, int[] days, int[] costs) { 5 | if (i >= days.length) { 6 | return 0; 7 | } 8 | 9 | if (memo[i] > 0) { 10 | return memo[i]; 11 | } 12 | 13 | memo[i] = 1000000; 14 | for (int j = 0; j < 3; j++) { 15 | int next = days[i] + ((j == 0) ? 1 : ((j == 1) ? 7: 30)); 16 | int k = i; 17 | 18 | while (k < days.length && days[k] < next) { 19 | k++; 20 | } 21 | 22 | memo[i] = Math.min(memo[i], costs[j] + solve(k, days, costs)); 23 | } 24 | 25 | return memo[i]; 26 | } 27 | 28 | public int mincostTickets(int[] days, int[] costs) { 29 | return solve(0, days, costs); 30 | } 31 | } -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## Step 0 4 | If you are new to *how to contribute to GitHub projects*, don't forget to check our [HOWTO](./HOWTO.md) guide. 5 | 6 | ## Step 1 7 | Open an [issue](https://github.com/Tahanima/leetcode-solution-curation/issues) describing the contribution you want to make. [Here](https://github.com/Tahanima/leetcode-solution-curation/issues/7)'s an example issue for your reference. 8 | 9 | Examples of some contributions: 10 | * Adding a solution to a LeetCode problem in a particular programming language. 11 | * Adding a second solution with a different approach to a LeetCode problem in a particular programming language. 12 | * Adding relevant resources such as youtube videos, articles, tutorials that are going to help someone solve the LeetCode problem. 13 | 14 | and so on 15 | 16 | ## Step 2 17 | The project is structured as follows: 18 | 19 | ```bash 20 | . 21 | ├── [Category] 22 | │ └── [Problem Difficulty] 23 | │ └── [Problem] 24 | │ └── [Solution and Resources] 25 | ├── ... 26 | │ 27 | ... 28 | ``` 29 | 30 | Here, the values for 31 | * **Category** are: `Algorithms`, `Database`, `Shell` and `Concurrency` 32 | * **Problem Difficulty** are: `Easy`, `Medium` and `Hard` 33 | 34 | If you need to create a folder for any **Category** or any **Problem Difficulty**, make sure to name it accordingly. 35 | 36 | As for **Problem**, the naming convention we are following is 37 | ```markdown 38 | [Problem Number]_[Problem Name] 39 | Example: 1_TwoSum 40 | 41 | Note: Problem Name should be in Pascal case 42 | ``` 43 | 44 | Now, in case of **Solution and Resources** 45 | 46 | **Solution** 47 | * Solution in a particular programming language should be in a file named `Solution` with appropriate file extension. For example, `Solution.java` for Java. 48 | 49 | * You should utilize the solution template provided by LeetCode for a particular programming language and write your code in such a way that submitting your solution via pasting it in the LeetCode editor should provide an `Accepted` verdict. 50 | 51 | * Suppose you want to add a second solution to a problem in a particular programming language. In that case, name the file as `SolutionOne` with appropriate file extension. 52 | 53 | * You should be consistent regarding naming convention in your code. 54 | 55 | * You should use 4 spaces for indentation. 56 | 57 | * You should use meaningful variable names and function names where appropriate. 58 | 59 | * You should add comments where appropriate. 60 | 61 | * You should use appropriate spaces to make your code more readable. For example: 62 | ```java 63 | // Bad 64 | int i=0; 65 | 66 | // Good 67 | int i = 0; 68 | 69 | // Bad 70 | if(i<10){ 71 | ... 72 | }else{ 73 | ... 74 | } 75 | 76 | // Good 77 | if (i < 10) { 78 | ... 79 | } else { 80 | ... 81 | } 82 | ``` 83 | 84 | **Resources** 85 | 86 | Resources for each of the problems should be in a file `Resources.md`. If it is not already present, feel free to create one. 87 | 88 | If you want to add a resource, make sure to: 89 | * add it in a bulleted list 90 | * provide an appropriate title and link it 91 | 92 | Here's an example: 93 | 94 | * [Editorial Series - LeetCode 268. Missing Number](https://tahanima.github.io/2021/06/02/editorial-series-leetcode-268-missing-number/) 95 | 96 | 97 | Your help is greatly appreciated. Thank you so much! -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | ## Contributors ✨ 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |

Tahanima Chowdhury

📖

Nakhla Rafi

📖

Amisha Sahu

📖

Hasin Raihan Shovon

📖

Jaber Tuhin

📖

Md. Fahim Bin Amin

📖

KMA Badshah

📖

Nafi Asib

📖

Israt Jahan Khan

📖

MD. Maqsud ul Anwar

📖

Joy Krishan Das

📖

Sahariar Alam Khandoker

📖
21 | -------------------------------------------------------------------------------- /Database/Easy/175_CombineTwoTables.sql: -------------------------------------------------------------------------------- 1 | SELECT Person.FirstName, Person.LastName, Address.City, Address.State 2 | FROM Person 3 | LEFT JOIN Address ON Person.PersonId = Address.PersonId; -------------------------------------------------------------------------------- /Database/Easy/176_SecondHighestSalary.sql: -------------------------------------------------------------------------------- 1 | SELECT MAX(Salary) as 'SecondHighestSalary' 2 | FROM Employee 3 | WHERE Salary < (SELECT MAX(Salary) FROM Employee); 4 | -------------------------------------------------------------------------------- /Database/Easy/181_EmployeesEarningMoreThanTheirManagers.sql: -------------------------------------------------------------------------------- 1 | SELECT E1.Name as 'Employee' 2 | FROM Employee as E1, Employee as E2 3 | WHERE E1.ManagerId = E2.Id AND E1.Salary > E2.Salary; 4 | -------------------------------------------------------------------------------- /Database/Easy/182_DuplicateEmails.sql: -------------------------------------------------------------------------------- 1 | SELECT Email 2 | FROM Person 3 | GROUP BY Email 4 | HAVING COUNT(*) > 1; 5 | -------------------------------------------------------------------------------- /Database/Easy/183_CustomersWhoNeverOrder.sql: -------------------------------------------------------------------------------- 1 | SELECT Customers.Name AS Customers 2 | FROM Customers 3 | LEFT JOIN Orders ON Customers.Id = Orders.CustomerId 4 | WHERE Orders.CustomerId IS NULL; 5 | -------------------------------------------------------------------------------- /Database/Easy/196_DeleteDuplicateEmails.sql: -------------------------------------------------------------------------------- 1 | DELETE a 2 | FROM Person a, Person b 3 | WHERE a.Email = b.Email AND 4 | a.Id > b.Id; 5 | -------------------------------------------------------------------------------- /Database/Easy/595_BigCountries.sql: -------------------------------------------------------------------------------- 1 | SELECT name, population, area 2 | FROM World 3 | WHERE area > 3000000 OR population > 25000000; 4 | -------------------------------------------------------------------------------- /Database/Easy/596_ClassesMoreThan5Students.sql: -------------------------------------------------------------------------------- 1 | SELECT class 2 | FROM courses 3 | GROUP BY class 4 | HAVING COUNT(DISTINCT student) >= 5; 5 | -------------------------------------------------------------------------------- /Database/Easy/620_NotBoringMovies.sql: -------------------------------------------------------------------------------- 1 | SELECT id, movie, description, rating 2 | FROM cinema 3 | WHERE (id LIKE '%1' OR id LIKE '%3' OR id LIKE '%5' OR id LIKE '%7' OR id LIKE '%9') AND description NOT IN ('boring') 4 | ORDER BY rating DESC; 5 | -------------------------------------------------------------------------------- /Database/Easy/627_SwapSalary.sql: -------------------------------------------------------------------------------- 1 | UPDATE salary 2 | SET sex = (CASE WHEN sex = 'm' THEN 'f' 3 | WHEN sex = 'f' THEN 'm' ELSE 4 | 'a' 5 | END); 6 | -------------------------------------------------------------------------------- /HOWTO.md: -------------------------------------------------------------------------------- 1 | Welcome to the **LeetCode Solution Curation**! If you are new to open source contribution and/or if you need a refresher on Git and GitHub basics, here are some resources to help you out: 2 | 3 | * [Hello World](https://guides.github.com/activities/hello-world/) 4 | * [Step-by-step guide to contributing on GitHub](https://www.dataschool.io/how-to-contribute-on-github/) 5 | * [Git and GitHub for Beginners - Crash Course](https://youtu.be/RGOj5yH7evk) 6 | * [How to Fork and Clone a GitHub Repository](https://egghead.io/lessons/javascript-how-to-fork-and-clone-a-github-repository) 7 | * [How to Contribute to Someone's GitHub Repository (Fork/Pull Request)](https://youtu.be/yr6IzOGoMsQ) 8 | 9 | In case you don't want to go through the resources, here's a quick refresher: 10 | 11 | * Get a copy of [leetcode-solution-curation](https://github.com/Tahanima/leetcode-solution-curation) by clicking the Fork button. 12 | 13 | * Clone, i.e, download your copy of the repository to your local machine using 14 | ```bash 15 | # Creates a folder named `leetcode-solution-curation` in the current directory with appropriate resources 16 | $ git clone https://github.com/[your_username]/leetcode-solution-curation.git 17 | ``` 18 | * Move to the `leetcode-solution-curation` folder using 19 | ```bash 20 | # Changes current directory to a folder named `leetcode-solution-curation` 21 | $ cd leetcode-solution-curation 22 | ``` 23 | 24 | * Run the following command to see that your local copy has a reference to your forked remote repository in GitHub. 25 | ```bash 26 | $ git remote -v 27 | origin https://github.com/[your_username]/leetcode-solution-curation.git (fetch) 28 | origin https://github.com/[your_username]/leetcode-solution-curation.git (push) 29 | ``` 30 | * Add a reference to the original [leetcode-solution-curation](https://github.com/Tahanima/leetcode-solution-curation) repository using 31 | 32 | ```bash 33 | # Adds a new remote named `upstream` 34 | $ git remote add upstream https://github.com/Tahanima/leetcode-solution-curation.git 35 | ``` 36 | 37 | * Keep your copy of the repository updated with the original repository. Before making any changes and/or in an appropriate interval, run the following commands to update your local repository. 38 | 39 | ```bash 40 | # Switches to `main` branch 41 | $ git checkout main 42 | 43 | # Fetches the branches and their respective commits from the `upstream` repository 44 | $ git fetch upstream 45 | 46 | # Merges the changes from upstream/main into your local default branch 47 | $ git merge upstream/main 48 | 49 | # Pushes changes to your forked `leetcode-solution-curation` repo 50 | $ git push origin main 51 | ``` 52 | 53 | * Run the following commands as needed while working. 54 | 55 | ```bash 56 | # Creates a new branch named `branch_name` and switches to it 57 | $ git checkout -b branch_name 58 | 59 | # Switches to an existing branch named `branch_name` 60 | $ git checkout branch_name 61 | 62 | # Adds a file with the path `path_to_file` respective to the root directory 63 | $ git add path_to_file 64 | 65 | # Associates the message 'relevant message' to the file you have changed 66 | $ git commit -m 'relevant message' 67 | 68 | # Pushes your changes to your remote repository 69 | $ git push -u origin branch_name 70 | ``` 71 | 72 | To sumbit your pull request after pushing changes to a branch, go to the `leetcode-solution-curation` repository from your browser and click on `Compare & pull requests`. Add the necessary details and then, submit the pull request. 73 | 74 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Tahanima Chowdhury 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Welcome to the *LeetCode Solution Curation* repository! 👋 2 | --- 3 | 4 | [LeetCode](https://leetcode.com/) is one of the most well-known online judge platforms which provides hands-on training on real coding interview questions. This repository aims to curate solutions (in different programming languages) and resources for as many LeetCode problems as possible. 5 | 6 | *The contents of this repository will get published [here](https://tahanima.github.io/hello-leetcode/)*. So, don't forget to check it out. 7 | 8 | ## Contributing 9 | Want to contribute? Please read our [CONTRIBUTING](./CONTRIBUTING.md) guidelines. 10 | 11 | ## Contributors 12 | Thanks to all of our amazing [contributors](CONTRIBUTORS.md). 13 | 14 | ## License 15 | MIT License
This work is licensed under the MIT License. 16 | -------------------------------------------------------------------------------- /RESOURCES.md: -------------------------------------------------------------------------------- 1 | # Resources 2 | 3 | There has been a lot of initiatives taken revolving around LeetCode. Here is listed a few such initiatives - 4 | 5 | - [Curated List of Top 75 LeetCode Questions to Save Your Time](https://www.teamblind.com/post/New-Year-Gift---Curated-List-of-Top-75-LeetCode-Questions-to-Save-Your-Time-OaM1orEU) 6 | --------------------------------------------------------------------------------