├── .gitignore ├── Array & String ├── Best Time to Buy and Sell Stock II │ ├── BuySellStock2.cpp │ └── BuySellStock2.cs ├── Best Time to Buy and Sell Stock │ ├── BuySellStock1.cpp │ ├── BuySellStock1.cs │ └── BuySellStock1.java ├── Find the Index of the First Occurrence in a String │ ├── FirstOccurrence.cpp │ ├── FirstOccurrence.cs │ ├── FirstOccurrence.java │ └── FirstOccurrence.py ├── Length of Last Word │ ├── LastWordLength.cpp │ ├── LastWordLength.cs │ ├── LastWordLength.java │ └── LastWordLength.py ├── Majority Element │ ├── MajorityElement.cpp │ ├── MajorityElement.cs │ ├── MajorityElement.java │ └── MajorityElement.py ├── Merge Sorted Array │ ├── MergeSortedArray.cpp │ ├── MergeSortedArray.cs │ ├── MergeSortedArray.java │ └── MergeSortedArray.py ├── Remove Duplicates from Sorted Array II │ ├── RemoveDuplicates.cpp │ ├── RemoveDuplicates.cs │ ├── RemoveDuplicates.java │ └── RemoveDuplicates.py ├── Remove Duplicates from Sorted Array │ ├── RemoveDuplicates.cpp │ ├── RemoveDuplicates.cs │ ├── RemoveDuplicates.java │ └── RemoveDuplicates.py ├── Remove Element │ ├── RemoveElement.cpp │ ├── RemoveElement.cs │ ├── RemoveElement.java │ └── RemoveElement.py ├── Reverse Words in a String │ ├── ReverseWords.cpp │ ├── ReverseWords.cs │ ├── ReverseWords.java │ └── ReverseWords.py └── Rotate Array │ ├── RotateArray.cpp │ ├── RotateArray.cs │ ├── RotateArray.java │ └── RotateArray.py ├── Backtracking ├── Combinations │ ├── Combinations.cpp │ └── Combinations.cs ├── Letter Combinations of a Phone Number │ ├── LetterCombinations.cpp │ └── LetterCombinations.cs ├── N-Queens II │ ├── NQueensII.cpp │ └── NQueensII.cs └── Permutations │ ├── Permutations.cpp │ └── Permutations.cs ├── Bit Manipulation ├── Add Binary │ ├── AddBinary.cpp │ ├── AddBinary.cs │ └── AddBinary.py ├── Bitwise AND of Numbers Range │ ├── BitwiseAND.cpp │ └── BitwiseAND.cs ├── Number of 1 Bits │ ├── Number1Bits.cpp │ ├── Number1Bits.cs │ ├── Number1Bits.java │ └── Number1Bits.py ├── Reverse Bits │ ├── ReverseBits.cpp │ ├── ReverseBits.cs │ ├── ReverseBits.java │ └── ReverseBits.py ├── Single Number II │ ├── SingleNumber.cpp │ └── SingleNumber.cs └── Single Number │ ├── SingleNumber.cpp │ ├── SingleNumber.cs │ └── SingleNumber.py ├── Hashmap ├── Group Anagrams │ ├── GroupAnagrams.cpp │ ├── GroupAnagrams.cs │ ├── GroupAnagrams.java │ └── GroupAnagrams.py ├── Ransom Note │ ├── RansomNote.cpp │ ├── RansomNote.cs │ └── RansomNote.java ├── Two Sum │ ├── TwoSum.cpp │ ├── TwoSum.cs │ ├── TwoSum.java │ └── TwoSum.py ├── Valid Anagram │ ├── ValidAnagram.cpp │ ├── ValidAnagram.cs │ ├── ValidAnagram.java │ └── ValidAnagram.py └── Word Pattern │ ├── WordPattern.cpp │ ├── WordPattern.cs │ ├── WordPattern.java │ └── WordPattern.py ├── Linked List ├── Add Two Numbers │ ├── AddTwoNumbers.cpp │ └── AddTwoNumbers.cs ├── Linked List Cycle │ ├── LinkedListCycle.cpp │ ├── LinkedListCycle.cs │ ├── LinkedListCycle.java │ └── linked_list_cycle.py ├── Merge Two Sorted Lists │ ├── MergeSortedLists.cpp │ ├── MergeSortedLists.cs │ ├── MergeSortedLists.java │ └── merge_sorted_lists.py ├── Remove Nth Node From End of List │ ├── RemoveNthNodeFromEnd.cpp │ └── RemoveNthNodeFromEnd.cs └── Rotate List │ ├── RotateList.cpp │ └── RotateList.cs ├── Math ├── Factorial Trailing Zeroes │ ├── TrailingZeros.cpp │ ├── TrailingZeros.cs │ ├── TrailingZeros.java │ └── TrailingZeros.py ├── Max Points on a Line │ ├── MaxPoints.cpp │ ├── MaxPoints.cs │ ├── MaxPoints.java │ └── MaxPoints.py ├── Palindrome Number │ ├── PalindromeNumber.cpp │ ├── PalindromeNumber.cs │ ├── PalindromeNumber.java │ └── PalindromeNumber.py ├── Plus One │ ├── PlusOne.cpp │ ├── PlusOne.cs │ ├── PlusOne.java │ └── PlusOne.py ├── Pow(x,n) │ ├── Power.cpp │ ├── Power.cs │ ├── Power.java │ └── Power.py └── Sqrt(x) │ ├── sqrt.cpp │ ├── sqrt.cs │ ├── sqrt.java │ └── sqrt.py ├── Stack ├── Basic Calculator │ ├── BasicCalculator.cpp │ ├── BasicCalculator.cs │ ├── BasicCalculator.java │ └── BasicCalculator.py ├── Evaluate Reverse Polish Notation │ ├── Evaluate.cpp │ ├── Evaluate.cs │ ├── Evaluate.java │ └── Evaluate.py ├── Min Stack │ ├── MinStack.cpp │ ├── MinStack.cs │ ├── MinStack.java │ └── MinStack.py ├── Simplify Path │ ├── SimplifyPath.cpp │ ├── SimplifyPath.cs │ ├── SimplifyPath.java │ └── SimplifyPath.py └── Valid Parentheses │ ├── ValidParentheses.cpp │ ├── ValidParentheses.cs │ ├── ValidParentheses.java │ └── ValidParentheses.py ├── Two Pointers ├── Is Subsequence │ ├── isSubsequence.cpp │ ├── isSubsequence.cs │ ├── isSubsequence.java │ └── isSubsequence.py └── Valid Palindrome │ ├── validPalindrome.cpp │ ├── validPalindrome.cs │ ├── validPalindrome.java │ └── validPalindrome.py └── readme.md /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | bin/ 3 | obj/ 4 | *.exe 5 | *.class -------------------------------------------------------------------------------- /Array & String/Best Time to Buy and Sell Stock II/BuySellStock2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int profit = 0; 5 | for (int i = 1; i < prices.size(); i++) 6 | profit += prices[i] > prices[i-1] ? prices[i]-prices[i-1] : 0; 7 | return profit; 8 | } 9 | }; -------------------------------------------------------------------------------- /Array & String/Best Time to Buy and Sell Stock II/BuySellStock2.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MaxProfit(int[] prices) { 3 | int profit = 0; 4 | for (int i = 1; i < prices.Length; i++) 5 | profit += prices[i] > prices[i-1] ? prices[i]-prices[i-1] : 0; 6 | return profit; 7 | } 8 | } -------------------------------------------------------------------------------- /Array & String/Best Time to Buy and Sell Stock/BuySellStock1.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int profit = 0; 5 | int minPrice = INT_MAX; 6 | for (int i = 0; i < prices.size(); i++) { 7 | minPrice = min(minPrice, prices[i]); 8 | profit = max(profit, prices[i] - minPrice); 9 | } 10 | return profit; 11 | } 12 | }; -------------------------------------------------------------------------------- /Array & String/Best Time to Buy and Sell Stock/BuySellStock1.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MaxProfit(int[] prices) { 3 | int profit = 0; 4 | int minPrice = int.MaxValue; 5 | for (int i = 0; i < prices.Length; i++) { 6 | minPrice = Math.Min(minPrice, prices[i]); 7 | profit = Math.Max(profit, prices[i] - minPrice); 8 | } 9 | return profit; 10 | } 11 | } -------------------------------------------------------------------------------- /Array & String/Best Time to Buy and Sell Stock/BuySellStock1.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int maxProfit(int[] prices) { 4 | int minVal = Integer.MAX_VALUE; 5 | int maxProfit = 0; 6 | 7 | for (int i = 0; i < prices.length; i++) { 8 | if (prices[i] < minVal) { 9 | minVal = prices[i]; 10 | } else if (prices[i] - minVal > maxProfit) { 11 | maxProfit = prices[i] - minVal; 12 | } 13 | } 14 | return maxProfit; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Array & String/Find the Index of the First Occurrence in a String/FirstOccurrence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int strStr(string haystack, string needle) { 4 | return haystack.find(needle); 5 | } 6 | }; -------------------------------------------------------------------------------- /Array & String/Find the Index of the First Occurrence in a String/FirstOccurrence.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int StrStr(string haystack, string needle) { 3 | return haystack.IndexOf(needle); 4 | } 5 | } -------------------------------------------------------------------------------- /Array & String/Find the Index of the First Occurrence in a String/FirstOccurrence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int strStr(String haystack, String needle) { 3 | for (int i = 0; i < haystack.length(); i++) { 4 | if (haystack.charAt(i) == needle.charAt(0)) { 5 | int j = 0; 6 | int k = i; 7 | while (k < haystack.length() && j < needle.length() && haystack.charAt(k) == needle.charAt(j)) { 8 | k++; 9 | j++; 10 | if (j == needle.length()) 11 | return i; 12 | } 13 | } 14 | } 15 | return -1; 16 | } 17 | } -------------------------------------------------------------------------------- /Array & String/Find the Index of the First Occurrence in a String/FirstOccurrence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def strStr(self, haystack: str, needle: str) -> int: 3 | return haystack.find(needle) 4 | -------------------------------------------------------------------------------- /Array & String/Length of Last Word/LastWordLength.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLastWord(string s) { 4 | vector words; 5 | istringstream iss(s); 6 | string word; 7 | 8 | while (iss >> word) { 9 | words.push_back(word); 10 | } 11 | 12 | if (words.empty()) { 13 | return 0; 14 | } 15 | 16 | return words.back().length(); 17 | } 18 | }; -------------------------------------------------------------------------------- /Array & String/Length of Last Word/LastWordLength.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int LengthOfLastWord(string s) { 3 | return s.TrimEnd().Split(" ").Last().Length; 4 | } 5 | } -------------------------------------------------------------------------------- /Array & String/Length of Last Word/LastWordLength.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLastWord(String s) { 3 | String[] x = s.split(" +"); 4 | return x[x.length - 1].length(); 5 | } 6 | } -------------------------------------------------------------------------------- /Array & String/Length of Last Word/LastWordLength.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | return len(s.split()[-1]) -------------------------------------------------------------------------------- /Array & String/Majority Element/MajorityElement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | sort(nums.begin(), nums.end()); 5 | return nums[(int)nums.size() / 2]; 6 | } 7 | }; -------------------------------------------------------------------------------- /Array & String/Majority Element/MajorityElement.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MajorityElement(int[] nums) { 3 | Array.Sort(nums); 4 | return nums[(int)nums.Length / 2]; 5 | } 6 | } -------------------------------------------------------------------------------- /Array & String/Majority Element/MajorityElement.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int majorityElement(int[] nums) { 5 | Arrays.sort(nums); 6 | 7 | int n = nums.length; 8 | 9 | return nums[n / 2]; 10 | } 11 | } -------------------------------------------------------------------------------- /Array & String/Majority Element/MajorityElement.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def majorityElement(self, nums: List[int]) -> int: 6 | e = {} 7 | for n in nums: 8 | if n in e: 9 | e[n] += 1 10 | else: 11 | e[n] = 0 12 | 13 | return max(zip(e.values(), e.keys()))[1] 14 | -------------------------------------------------------------------------------- /Array & String/Merge Sorted Array/MergeSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void merge(vector& nums1, int m, vector& nums2, int n) { 4 | for(int i = 0; i < n; i++) 5 | nums1[i + m] = nums2[i]; 6 | sort(nums1.begin(),nums1.end()); 7 | } 8 | }; -------------------------------------------------------------------------------- /Array & String/Merge Sorted Array/MergeSortedArray.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void Merge(int[] nums1, int m, int[] nums2, int n) { 3 | var merged = nums1.Take(m).Concat(nums2.Take(n)).OrderBy(x => x).ToArray(); 4 | Array.Copy(merged, nums1, merged.Length); 5 | } 6 | } -------------------------------------------------------------------------------- /Array & String/Merge Sorted Array/MergeSortedArray.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public void merge(int[] nums1, int m, int[] nums2, int n) { 5 | for (int i = m, j = 0; j < n; j++) { 6 | nums1[i] = nums2[j]; 7 | i++; 8 | } 9 | Arrays.sort(nums1); 10 | } 11 | } -------------------------------------------------------------------------------- /Array & String/Merge Sorted Array/MergeSortedArray.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: 6 | i = m - 1 7 | j = n - 1 8 | k = (m + n) - 1 9 | 10 | while i >= 0 and j >= 0: 11 | if nums1[i] > nums2[j]: 12 | nums1[k] = nums1[i] 13 | i -= 1 14 | else: 15 | nums1[k] = nums2[j] 16 | j -= 1 17 | k -= 1 18 | 19 | while j >= 0: 20 | nums1[k] = nums2[j] 21 | j -= 1 22 | k -= 1 23 | -------------------------------------------------------------------------------- /Array & String/Remove Duplicates from Sorted Array II/RemoveDuplicates.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | if (nums.size() <= 2) { 5 | return nums.size(); 6 | } 7 | int uniqueCount = 2; 8 | for (int i = 2; i < nums.size(); i++) { 9 | if (nums[i] != nums[uniqueCount - 2]) { 10 | nums[uniqueCount] = nums[i]; 11 | uniqueCount++; 12 | } 13 | } 14 | return uniqueCount; 15 | } 16 | }; -------------------------------------------------------------------------------- /Array & String/Remove Duplicates from Sorted Array II/RemoveDuplicates.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int RemoveDuplicates(int[] nums) { 3 | var filteredArray = nums.GroupBy(num => num) 4 | .SelectMany(group => 5 | { 6 | int count = group.Count(); 7 | return count >= 2 ? group.Take(2) : group; 8 | }).ToArray(); 9 | 10 | Array.Copy(filteredArray, nums, filteredArray.Length); 11 | return filteredArray.Length; 12 | } 13 | } -------------------------------------------------------------------------------- /Array & String/Remove Duplicates from Sorted Array II/RemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | int j = 2; 4 | 5 | for (int i = 2; i < nums.length; i++) { 6 | if (nums[i] != nums[j - 2]) { 7 | nums[j++] = nums[i]; 8 | } 9 | 10 | } 11 | return j; 12 | } 13 | } -------------------------------------------------------------------------------- /Array & String/Remove Duplicates from Sorted Array II/RemoveDuplicates.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def remove_duplicates(nums: List[int]) -> int: 5 | if len(nums) <= 2: 6 | return len(nums) 7 | 8 | i = 2 9 | for j in range(i): 10 | if nums[j] != nums[i - 2]: 11 | nums[i] = nums[j] 12 | i += 1 13 | 14 | return i 15 | -------------------------------------------------------------------------------- /Array & String/Remove Duplicates from Sorted Array/RemoveDuplicates.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | set result(nums.begin(), nums.end()); 5 | nums.assign(result.begin(), result.end()); 6 | return nums.size(); 7 | } 8 | }; -------------------------------------------------------------------------------- /Array & String/Remove Duplicates from Sorted Array/RemoveDuplicates.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int RemoveDuplicates(int[] nums) { 3 | var uniqueArray = nums.Distinct().ToArray(); 4 | Array.Copy(uniqueArray, nums, uniqueArray.Length); 5 | return uniqueArray.Length; 6 | } 7 | } -------------------------------------------------------------------------------- /Array & String/Remove Duplicates from Sorted Array/RemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | int j = 0; 4 | 5 | for (int i = 0; i < nums.length; i++) { 6 | if (i < nums.length - 1 && nums[i] == nums[i + 1]) { 7 | continue; 8 | } else { 9 | nums[j++] = nums[i]; 10 | } 11 | } 12 | return j; 13 | } 14 | } -------------------------------------------------------------------------------- /Array & String/Remove Duplicates from Sorted Array/RemoveDuplicates.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def removeDuplicates(self, nums: List[int]) -> int: 6 | i, j = 1, 1 7 | 8 | while i < len(nums): 9 | if nums[i - 1] != nums[i]: 10 | nums[j] = nums[i] 11 | j += 1 12 | i += 1 13 | 14 | return j 15 | -------------------------------------------------------------------------------- /Array & String/Remove Element/RemoveElement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeElement(vector& nums, int val) { 4 | int index = 0; 5 | for (int num : nums) { 6 | if (num != val) { 7 | nums[index++] = num; 8 | } 9 | } 10 | return index; 11 | } 12 | }; -------------------------------------------------------------------------------- /Array & String/Remove Element/RemoveElement.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int RemoveElement(int[] nums, int val) { 3 | var filtered = nums.Where(num => num != val).ToArray(); 4 | Array.Copy(filtered, nums, filtered.Length); 5 | return filtered.Length; 6 | } 7 | } -------------------------------------------------------------------------------- /Array & String/Remove Element/RemoveElement.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeElement(int[] nums, int val) { 3 | int index = 0; 4 | for (int i = 0; i < nums.length; i++) { 5 | if (nums[i] != val) { 6 | nums[index++] = nums[i]; 7 | } 8 | } 9 | return index; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Array & String/Remove Element/RemoveElement.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def removeElement(self, nums: List[int], val: int) -> int: 6 | j = 0 7 | for num in nums: 8 | if num != val: 9 | nums[j] = num 10 | j += 1 11 | return j 12 | -------------------------------------------------------------------------------- /Array & String/Reverse Words in a String/ReverseWords.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseWords(string s) { 4 | vector words; 5 | istringstream iss(s); 6 | string word; 7 | 8 | while (iss >> word) { 9 | words.push_back(word); 10 | } 11 | 12 | ostringstream oss; 13 | for (int i = words.size() - 1; i >= 0; --i) { 14 | oss << words[i]; 15 | if (i > 0) { 16 | oss << " "; 17 | } 18 | } 19 | 20 | return oss.str(); 21 | } 22 | }; -------------------------------------------------------------------------------- /Array & String/Reverse Words in a String/ReverseWords.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public string ReverseWords(string s) { 3 | return String.Join(" ", s.Split(' ', StringSplitOptions.RemoveEmptyEntries).Reverse()); 4 | } 5 | } -------------------------------------------------------------------------------- /Array & String/Reverse Words in a String/ReverseWords.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reverseWords(String s) { 3 | String[] x = s.split(" +"); 4 | StringBuilder sb = new StringBuilder(); 5 | for (int i = x.length - 1; i >= 0; i--) { 6 | sb.append(x[i]); 7 | sb.append(" "); 8 | } 9 | return sb.toString().trim(); 10 | } 11 | } -------------------------------------------------------------------------------- /Array & String/Reverse Words in a String/ReverseWords.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | return " ".join(s.split()[::-1]) 4 | -------------------------------------------------------------------------------- /Array & String/Rotate Array/RotateArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector& nums, int k) { 4 | k = k % nums.size(); 5 | reverse(nums.begin(), nums.end()); 6 | reverse(nums.begin(), nums.begin() + k); 7 | reverse(nums.begin() + k, nums.end()); 8 | } 9 | }; -------------------------------------------------------------------------------- /Array & String/Rotate Array/RotateArray.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void Rotate(int[] nums, int k) { 3 | k = k % nums.Length; 4 | Array.Reverse(nums); 5 | Array.Reverse(nums, 0, k); 6 | Array.Reverse(nums, k, nums.Length - k); 7 | } 8 | } -------------------------------------------------------------------------------- /Array & String/Rotate Array/RotateArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[] nums, int k) { 3 | if (nums.length == k || nums.length == 1 || nums == null) 4 | return; 5 | 6 | k = k % nums.length; 7 | 8 | int left = 0; 9 | int right = nums.length - 1 - k; 10 | int nextLeft = right + 1; 11 | while (left < right) { 12 | int temp = nums[left]; 13 | nums[left] = nums[right]; 14 | nums[right] = temp; 15 | left++; 16 | right--; 17 | } 18 | right = nums.length - 1; 19 | while (nextLeft < right) { 20 | int temp = nums[nextLeft]; 21 | nums[nextLeft] = nums[right]; 22 | nums[right] = temp; 23 | nextLeft++; 24 | right--; 25 | } 26 | left = 0; 27 | right = nums.length - 1; 28 | while (left < right) { 29 | int temp = nums[left]; 30 | nums[left] = nums[right]; 31 | nums[right] = temp; 32 | left++; 33 | right--; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Array & String/Rotate Array/RotateArray.py: -------------------------------------------------------------------------------- 1 | import typing 2 | 3 | 4 | class Solution: 5 | def rotate(self, nums: typing.List[int], k: int) -> None: 6 | """ 7 | Do not return anything, modify nums in-place instead. 8 | """ 9 | k = k % len(nums) 10 | 11 | l, r = 0, len(nums) - 1 12 | while l < r: 13 | nums[l], nums[r] = nums[r], nums[l] 14 | l, r = l + 1, r - 1 15 | 16 | l, r = 0, k - 1 17 | while l < r: 18 | nums[l], nums[r] = nums[r], nums[l] 19 | l, r = l + 1, r - 1 20 | 21 | l, r = k, len(nums) - 1 22 | while l < r: 23 | nums[l], nums[r] = nums[r], nums[l] 24 | l, r = l + 1, r - 1 25 | -------------------------------------------------------------------------------- /Backtracking/Combinations/Combinations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> combine(int n, int k) { 4 | vector> result; 5 | vector current; 6 | combinations(result, current, n, k, 1); 7 | return result; 8 | } 9 | 10 | private: 11 | void combinations(vector>& result, vector& current, int n, int k, int start) { 12 | if (k == 0) { 13 | result.push_back(current); 14 | return; 15 | } 16 | for (int i = start; i <= n; ++i) { 17 | current.push_back(i); 18 | combinations(result, current, n, k - 1, i + 1); 19 | current.pop_back(); 20 | } 21 | } 22 | }; -------------------------------------------------------------------------------- /Backtracking/Combinations/Combinations.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public IList> Combine(int n, int k) { 3 | List> result = new List>(); 4 | List current = new List(); 5 | Combination(result, current, n, k, 1); 6 | return result; 7 | } 8 | 9 | private void Combination(List> result, List current, int n, int k, int start) { 10 | if (k == 0) { 11 | result.Add(new List(current)); 12 | return; 13 | } 14 | for (int i = start; i <= n; ++i) { 15 | current.Add(i); 16 | Combination(result, current, n, k - 1, i + 1); 17 | current.RemoveAt(current.Count - 1); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Backtracking/Letter Combinations of a Phone Number/LetterCombinations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector letterCombinations(const string& digits) { 4 | const unordered_map phoneMap = { 5 | {'2', "abc"}, 6 | {'3', "def"}, 7 | {'4', "ghi"}, 8 | {'5', "jkl"}, 9 | {'6', "mno"}, 10 | {'7', "pqrs"}, 11 | {'8', "tuv"}, 12 | {'9', "wxyz"} 13 | }; 14 | vector combinations; 15 | if (!digits.empty()) { 16 | generateCombinations(digits, 0, "", phoneMap, combinations); 17 | } 18 | return combinations; 19 | } 20 | 21 | private: 22 | void generateCombinations(const string& digits, size_t index, const string& current, 23 | const unordered_map& phoneMap, 24 | vector& combinations) { 25 | if (index == digits.length()) { 26 | combinations.push_back(current); 27 | return; 28 | } 29 | 30 | char digit = digits[index]; 31 | if (phoneMap.find(digit) != phoneMap.end()) { 32 | const string& letters = phoneMap.at(digit); 33 | for (char letter : letters) { 34 | generateCombinations(digits, index + 1, current + letter, phoneMap, combinations); 35 | } 36 | } 37 | } 38 | }; -------------------------------------------------------------------------------- /Backtracking/Letter Combinations of a Phone Number/LetterCombinations.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public IList LetterCombinations(string digits) { 3 | Dictionary phoneMap = new Dictionary { 4 | {'2', "abc"}, 5 | {'3', "def"}, 6 | {'4', "ghi"}, 7 | {'5', "jkl"}, 8 | {'6', "mno"}, 9 | {'7', "pqrs"}, 10 | {'8', "tuv"}, 11 | {'9', "wxyz"} 12 | }; 13 | List combinations = new List(); 14 | if (!string.IsNullOrEmpty(digits)) { 15 | GenerateCombinations(digits, 0, "", phoneMap, combinations); 16 | } 17 | return combinations; 18 | } 19 | 20 | private void GenerateCombinations(string digits, int index, string current, 21 | Dictionary phoneMap, 22 | List combinations) { 23 | if (index == digits.Length) { 24 | combinations.Add(current); 25 | return; 26 | } 27 | 28 | char digit = digits[index]; 29 | if (phoneMap.ContainsKey(digit)) { 30 | string letters = phoneMap[digit]; 31 | foreach (char letter in letters) { 32 | GenerateCombinations(digits, index + 1, current + letter, phoneMap, combinations); 33 | } 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Backtracking/N-Queens II/NQueensII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int totalNQueens(int n) { 4 | vector col(n), diag(2 * n - 1), anti_diag(2 * n - 1); 5 | return solveNQueens(col, diag, anti_diag, 0); 6 | } 7 | 8 | private: 9 | int solveNQueens(vector& col, vector& diag, vector& anti_diag, int row) { 10 | int n = col.size(), count = 0; 11 | if (row == n) { 12 | return 1; 13 | } 14 | for (int column = 0; column < n; column++) { 15 | if (canPlaceQueen(col, diag, anti_diag, row, column)) { 16 | placeQueen(col, diag, anti_diag, row, column); 17 | count += solveNQueens(col, diag, anti_diag, row + 1); 18 | removeQueen(col, diag, anti_diag, row, column); 19 | } 20 | } 21 | return count; 22 | } 23 | 24 | bool canPlaceQueen(const vector& col, const vector& diag, const vector& anti_diag, int row, int column) { 25 | return !col[column] && !diag[row + column] && !anti_diag[row - column + col.size() - 1]; 26 | } 27 | 28 | void placeQueen(vector& col, vector& diag, vector& anti_diag, int row, int column) { 29 | col[column] = diag[row + column] = anti_diag[row - column + col.size() - 1] = true; 30 | } 31 | 32 | void removeQueen(vector& col, vector& diag, vector& anti_diag, int row, int column) { 33 | col[column] = diag[row + column] = anti_diag[row - column + col.size() - 1] = false; 34 | } 35 | }; -------------------------------------------------------------------------------- /Backtracking/N-Queens II/NQueensII.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int TotalNQueens(int n) { 3 | bool[] col = new bool[n]; 4 | bool[] diag = new bool[2 * n - 1]; 5 | bool[] anti_diag = new bool[2 * n - 1]; 6 | return SolveNQueens(col, diag, anti_diag, 0); 7 | } 8 | 9 | private int SolveNQueens(bool[] col, bool[] diag, bool[] anti_diag, int row) { 10 | int n = col.Length; 11 | int count = 0; 12 | if (row == n) { 13 | return 1; 14 | } 15 | for (int column = 0; column < n; column++) { 16 | if (CanPlaceQueen(col, diag, anti_diag, row, column)) { 17 | PlaceQueen(col, diag, anti_diag, row, column); 18 | count += SolveNQueens(col, diag, anti_diag, row + 1); 19 | RemoveQueen(col, diag, anti_diag, row, column); 20 | } 21 | } 22 | return count; 23 | } 24 | 25 | private bool CanPlaceQueen(bool[] col, bool[] diag, bool[] anti_diag, int row, int column) { 26 | return !col[column] && !diag[row + column] && !anti_diag[row - column + col.Length - 1]; 27 | } 28 | 29 | private void PlaceQueen(bool[] col, bool[] diag, bool[] anti_diag, int row, int column) { 30 | col[column] = diag[row + column] = anti_diag[row - column + col.Length - 1] = true; 31 | } 32 | 33 | private void RemoveQueen(bool[] col, bool[] diag, bool[] anti_diag, int row, int column) { 34 | col[column] = diag[row + column] = anti_diag[row - column + col.Length - 1] = false; 35 | } 36 | } -------------------------------------------------------------------------------- /Backtracking/Permutations/Permutations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> permute(vector& nums) { 4 | vector> result; 5 | sort(nums.begin(), nums.end()); 6 | permutations(result, nums, 0); 7 | return result; 8 | } 9 | 10 | private: 11 | void permutations(vector>& result, vector& nums, int index) { 12 | if (index == nums.size()) { 13 | result.push_back(nums); 14 | return; 15 | } 16 | for (int i = index; i < nums.size(); ++i) { 17 | swap(nums[index], nums[i]); 18 | permutations(result, nums, index + 1); 19 | swap(nums[index], nums[i]); 20 | } 21 | } 22 | }; -------------------------------------------------------------------------------- /Backtracking/Permutations/Permutations.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public IList> Permute(int[] nums) { 3 | List> result = new List>(); 4 | Array.Sort(nums); 5 | Permutations(result, nums, 0); 6 | return result; 7 | } 8 | 9 | private void Permutations(List> result, int[] nums, int index) { 10 | if (index == nums.Length) { 11 | result.Add(new List(nums)); 12 | return; 13 | } 14 | for (int i = index; i < nums.Length; ++i) { 15 | Swap(nums, index, i); 16 | Permutations(result, nums, index + 1); 17 | Swap(nums, index, i); 18 | } 19 | } 20 | 21 | private void Swap(int[] nums, int i, int j) { 22 | int temp = nums[i]; 23 | nums[i] = nums[j]; 24 | nums[j] = temp; 25 | } 26 | } -------------------------------------------------------------------------------- /Bit Manipulation/Add Binary/AddBinary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string addBinary(string a, string b) { 4 | int carry = 0; 5 | string result = ""; 6 | int i = a.length() - 1; 7 | int j = b.length() - 1; 8 | 9 | while (i >= 0 || j >= 0 || carry > 0) { 10 | int bitA = (i >= 0) ? a[i] - '0' : 0; 11 | int bitB = (j >= 0) ? b[j] - '0' : 0; 12 | int sum = bitA + bitB + carry; 13 | result += to_string(sum % 2); 14 | carry = sum / 2; 15 | i--; 16 | j--; 17 | } 18 | 19 | reverse(result.begin(), result.end()); 20 | return result; 21 | } 22 | }; -------------------------------------------------------------------------------- /Bit Manipulation/Add Binary/AddBinary.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public string AddBinary(string a, string b) { 3 | int carry = 0; 4 | StringBuilder result = new StringBuilder(); 5 | int i = a.Length - 1; 6 | int j = b.Length - 1; 7 | while (i >= 0 || j >= 0 || carry > 0) 8 | { 9 | int bitA = (i >= 0) ? a[i] - '0' : 0; 10 | int bitB = (j >= 0) ? b[j] - '0' : 0; 11 | int sum = bitA + bitB + carry; 12 | result.Insert(0, sum % 2); 13 | carry = sum / 2; 14 | i--; 15 | j--; 16 | } 17 | return result.ToString(); 18 | } 19 | } -------------------------------------------------------------------------------- /Bit Manipulation/Add Binary/AddBinary.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addBinary(self, a: str, b: str) -> str: 3 | a, b = a[::-1], b[::-1] 4 | result = "" 5 | carry = 0 6 | 7 | for i in range(max(len(a), len(b))): 8 | x = int(a[i]) if i < len(a) else 0 9 | y = int(b[i]) if i < len(b) else 0 10 | 11 | total = x + y + carry 12 | result = str(total % 2) + result 13 | carry = total // 2 14 | 15 | if carry == 1: 16 | result = "1" + result 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /Bit Manipulation/Bitwise AND of Numbers Range/BitwiseAND.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rangeBitwiseAnd(int left, int right) { 4 | int count = 0; 5 | while (left != right) { 6 | left >>= 1; 7 | right >>= 1; 8 | count++; 9 | } 10 | return left << count; 11 | } 12 | }; -------------------------------------------------------------------------------- /Bit Manipulation/Bitwise AND of Numbers Range/BitwiseAND.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int RangeBitwiseAnd(int left, int right) { 3 | int count = 0; 4 | while (left != right) { 5 | left >>= 1; 6 | right >>= 1; 7 | count++; 8 | } 9 | return left << count; 10 | } 11 | } -------------------------------------------------------------------------------- /Bit Manipulation/Number of 1 Bits/Number1Bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingWeight(uint32_t n) { 4 | int count = 0; 5 | while (n > 0) { 6 | count += (n & 1); 7 | n >>= 1; 8 | } 9 | return count; 10 | } 11 | }; -------------------------------------------------------------------------------- /Bit Manipulation/Number of 1 Bits/Number1Bits.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int HammingWeight(uint n) { 3 | int count = 0; 4 | while (n > 0) { 5 | count += (int)(n & 1); 6 | n >>= 1; 7 | } 8 | return count; 9 | } 10 | } -------------------------------------------------------------------------------- /Bit Manipulation/Number of 1 Bits/Number1Bits.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public int hammingWeight(int n) { 4 | int count = 0, mask = 1; 5 | for (int i = 1; i <= 32; i++) { 6 | if ((n & mask) != 0) { 7 | count++; 8 | } 9 | mask = mask << 1; 10 | } 11 | return count; 12 | } 13 | } -------------------------------------------------------------------------------- /Bit Manipulation/Number of 1 Bits/Number1Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, n: int) -> int: 3 | result = 0 4 | 5 | for i in range(32): 6 | bit = (n >> i) & 1 7 | if bit == 1: 8 | result += 1 9 | 10 | return result 11 | -------------------------------------------------------------------------------- /Bit Manipulation/Reverse Bits/ReverseBits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | uint32_t reverseBits(uint32_t n) { 4 | uint32_t result = 0; 5 | for (int i = 0; i < 32; i++) { 6 | result = (result << 1) | (n & 1); 7 | n >>= 1; 8 | } 9 | return result; 10 | } 11 | }; -------------------------------------------------------------------------------- /Bit Manipulation/Reverse Bits/ReverseBits.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public uint reverseBits(uint n) { 3 | uint result = 0; 4 | for (int i = 0; i < 32; i++) 5 | { 6 | result = (result << 1) | (n & 1); 7 | n >>= 1; 8 | } 9 | return result; 10 | } 11 | } -------------------------------------------------------------------------------- /Bit Manipulation/Reverse Bits/ReverseBits.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | 3 | public int reverseBits(int n) { 4 | int result = 0; 5 | for (int i = 1; i <= 32; i++) { 6 | result += n & 1; 7 | n = n >> 1; 8 | if (i <= 31) { 9 | result = result << 1; 10 | } 11 | } 12 | return result; 13 | } 14 | } -------------------------------------------------------------------------------- /Bit Manipulation/Reverse Bits/ReverseBits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseBits(self, n: int) -> int: 3 | res = 0 4 | 5 | for i in range(32): 6 | bit = (n >> i) & 1 7 | res |= bit << (31 - i) 8 | 9 | return res 10 | -------------------------------------------------------------------------------- /Bit Manipulation/Single Number II/SingleNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int ones = 0, twos = 0; 5 | for (int num : nums) { 6 | ones = (ones ^ num) & ~twos; 7 | twos = (twos ^ num) & ~ones; 8 | } 9 | return ones; 10 | } 11 | }; -------------------------------------------------------------------------------- /Bit Manipulation/Single Number II/SingleNumber.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int SingleNumber(int[] nums) { 3 | int ones = 0, twos = 0; 4 | foreach (int num in nums) { 5 | ones = (ones ^ num) & ~twos; 6 | twos = (twos ^ num) & ~ones; 7 | } 8 | return ones; 9 | } 10 | } -------------------------------------------------------------------------------- /Bit Manipulation/Single Number/SingleNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int result = 0; 5 | for (int num : nums) { 6 | result ^= num; 7 | } 8 | return result; 9 | } 10 | }; -------------------------------------------------------------------------------- /Bit Manipulation/Single Number/SingleNumber.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int SingleNumber(int[] nums) { 3 | int result = 0; 4 | foreach (int num in nums) { 5 | result ^= num; 6 | } 7 | return result; 8 | } 9 | } -------------------------------------------------------------------------------- /Bit Manipulation/Single Number/SingleNumber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: List[int]) -> int: 3 | result = 0 4 | for n in nums: 5 | result ^= n 6 | return result 7 | -------------------------------------------------------------------------------- /Hashmap/Group Anagrams/GroupAnagrams.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> groupAnagrams(vector& strs) { 4 | unordered_map> group; 5 | 6 | for (const string& element : strs) { 7 | string sortedElement = element; 8 | sort(sortedElement.begin(), sortedElement.end()); 9 | if (group.find(sortedElement) == group.end()) { 10 | group[sortedElement] = {element}; 11 | } else { 12 | group[sortedElement].push_back(element); 13 | } 14 | } 15 | 16 | vector> result; 17 | for (const auto& kv : group) { 18 | result.push_back(kv.second); 19 | } 20 | 21 | return result; 22 | } 23 | }; -------------------------------------------------------------------------------- /Hashmap/Group Anagrams/GroupAnagrams.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public IList> GroupAnagrams(string[] strs) { 3 | Dictionary> group = new Dictionary>(); 4 | 5 | foreach (string element in strs) { 6 | string sortedElement = new string(element.ToCharArray().OrderBy(c => c).ToArray()); 7 | 8 | if (!group.ContainsKey(sortedElement)) { 9 | group[sortedElement] = new List { element }; 10 | } else { 11 | group[sortedElement].Add(element); 12 | } 13 | } 14 | 15 | IList> result = new List>(); 16 | foreach (var kv in group) { 17 | result.Add(kv.Value); 18 | } 19 | 20 | return result; 21 | } 22 | } -------------------------------------------------------------------------------- /Hashmap/Group Anagrams/GroupAnagrams.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public List> groupAnagrams(String[] strs) { 5 | if (strs == null || strs.length == 0) 6 | return null; 7 | 8 | ArrayList> list = new ArrayList<>(); 9 | 10 | HashMap> map = new HashMap<>(); 11 | 12 | for (String word : strs) { 13 | char[] sortedList = word.toCharArray(); 14 | Arrays.sort(sortedList); 15 | String sortedString = new String(sortedList); 16 | 17 | if (map.containsKey(sortedString)) { 18 | map.get(sortedString).add(word); 19 | } else { 20 | map.put(sortedString, new ArrayList()); 21 | map.get(sortedString).add(word); 22 | } 23 | } 24 | for (List x : map.values()) { 25 | list.add(x); 26 | } 27 | return list; 28 | } 29 | } -------------------------------------------------------------------------------- /Hashmap/Group Anagrams/GroupAnagrams.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 3 | anagrams = {} 4 | 5 | for i in strs: 6 | id = "".join(sorted(i)) 7 | items = anagrams.get(id, []) 8 | items.append(i) 9 | anagrams[id] = items 10 | return list(anagrams.values()) 11 | -------------------------------------------------------------------------------- /Hashmap/Ransom Note/RansomNote.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canConstruct(string ransomNote, string magazine) { 4 | unordered_map charCount; 5 | for (char word : magazine) 6 | charCount[word]++; 7 | 8 | for (char word : ransomNote) 9 | charCount[word]--; 10 | 11 | for (const auto& entry : charCount) { 12 | if (entry.second < 0) 13 | return false; 14 | } 15 | return true; 16 | } 17 | }; -------------------------------------------------------------------------------- /Hashmap/Ransom Note/RansomNote.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool CanConstruct(string ransomNote, string magazine) { 3 | Dictionary charCount = new Dictionary(); 4 | foreach (char word in magazine) { 5 | if (charCount.ContainsKey(word)) { 6 | charCount[word]++; 7 | } else { 8 | charCount[word] = 1; 9 | } 10 | } 11 | 12 | foreach (char word in ransomNote) { 13 | if (charCount.ContainsKey(word)) { 14 | charCount[word]--; 15 | } else { 16 | charCount[word] = -1; 17 | } 18 | } 19 | 20 | foreach (var entry in charCount) { 21 | if (entry.Value < 0) { 22 | return false; 23 | } 24 | } 25 | 26 | return true; 27 | } 28 | } -------------------------------------------------------------------------------- /Hashmap/Ransom Note/RansomNote.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canConstruct(String ransomNote, String magazine) { 3 | if (ransomNote.length() > magazine.length()) 4 | return false; 5 | 6 | int[] temp = new int[26]; 7 | 8 | for (char x : magazine.toCharArray()) { 9 | temp[x - 'a']++; 10 | } 11 | for (char x : ransomNote.toCharArray()) { 12 | if (--temp[x - 'a'] < 0) { 13 | return false; 14 | } 15 | } 16 | 17 | return true; 18 | } 19 | } -------------------------------------------------------------------------------- /Hashmap/Two Sum/TwoSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | unordered_map d; 5 | vector result; 6 | for (int index = 0; index < nums.size(); ++index) { 7 | if (d.find(target - nums[index]) != d.end()) { 8 | result.push_back(d[target - nums[index]]); 9 | result.push_back(index); 10 | break; 11 | } 12 | d[nums[index]] = index; 13 | } 14 | return result; 15 | } 16 | }; -------------------------------------------------------------------------------- /Hashmap/Two Sum/TwoSum.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] TwoSum(int[] nums, int target) { 3 | Dictionary d = new Dictionary(); 4 | int[] result = new int[2]; 5 | for (int index = 0; index < nums.Length; ++index) { 6 | if (d.ContainsKey(target - nums[index])) { 7 | result[0] = d[target - nums[index]]; 8 | result[1] = index; 9 | break; 10 | } 11 | d[nums[index]] = index; 12 | } 13 | return result; 14 | } 15 | } -------------------------------------------------------------------------------- /Hashmap/Two Sum/TwoSum.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | class Solution { 4 | public int[] twoSum(int[] nums, int target) { 5 | 6 | HashMap map = new HashMap<>(); 7 | 8 | for (int i = 0; i < nums.length; i++) { 9 | int complement = target - nums[i]; 10 | 11 | if (map.containsKey(complement)) { 12 | return new int[] { map.get(complement), i }; 13 | } 14 | 15 | map.put(nums[i], i); 16 | 17 | } 18 | return new int[] {}; 19 | } 20 | } -------------------------------------------------------------------------------- /Hashmap/Two Sum/TwoSum.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | class Solution: 5 | def twoSum(self, nums: List[int], target: int) -> List[int]: 6 | visited = {} 7 | for i in range(len(nums)): 8 | if target - nums[i] in visited: 9 | return [i, visited[target - nums[i]]] 10 | visited[nums[i]] = i 11 | 12 | # This should never happen as we will surely have an answer 13 | return [] 14 | -------------------------------------------------------------------------------- /Hashmap/Valid Anagram/ValidAnagram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isAnagram(string s, string t) { 4 | if (s.length() != t.length()) { 5 | return false; 6 | } 7 | map counter1, counter2; 8 | for(char c : s) { 9 | counter1[c]++; 10 | } 11 | for(char c : t) { 12 | counter2[c]++; 13 | } 14 | return counter1 == counter2; 15 | } 16 | }; -------------------------------------------------------------------------------- /Hashmap/Valid Anagram/ValidAnagram.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool IsAnagram(string s, string t) { 3 | if (s.Length != t.Length) { 4 | return false; 5 | } 6 | 7 | Dictionary counter1 = new Dictionary(); 8 | Dictionary counter2 = new Dictionary(); 9 | 10 | foreach (char c in s) { 11 | if (counter1.ContainsKey(c)) { 12 | counter1[c]++; 13 | } else { 14 | counter1[c] = 1; 15 | } 16 | } 17 | 18 | foreach (char c in t) { 19 | if (counter2.ContainsKey(c)) { 20 | counter2[c]++; 21 | } else { 22 | counter2[c] = 1; 23 | } 24 | } 25 | 26 | return counter1.OrderBy(kv => kv.Key) 27 | .SequenceEqual(counter2.OrderBy(kv => kv.Key)); 28 | } 29 | } -------------------------------------------------------------------------------- /Hashmap/Valid Anagram/ValidAnagram.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isAnagram(String s, String t) { 3 | if (s.length() != t.length()) 4 | return false; 5 | 6 | int[] charCount = new int[26]; 7 | 8 | for (int x : s.toCharArray()) { 9 | charCount[x - 'a']++; 10 | } 11 | for (int x : t.toCharArray()) { 12 | charCount[x - 'a']--; 13 | } 14 | for (int i : charCount) { 15 | if (i != 0) { 16 | return false; 17 | } 18 | } 19 | return true; 20 | } 21 | } -------------------------------------------------------------------------------- /Hashmap/Valid Anagram/ValidAnagram.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAnagram(self, s: str, t: str) -> bool: 3 | return Counter(s) == Counter(t) 4 | -------------------------------------------------------------------------------- /Hashmap/Word Pattern/WordPattern.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool wordPattern(string pattern, string s) { 4 | unordered_map patternMap; 5 | unordered_map wordMap; 6 | istringstream input(s); 7 | string word; 8 | int i = 0, n = pattern.size(); 9 | for (; input >> word; ++i) { 10 | if (i == n || patternMap[pattern[i]] != wordMap[word]) { 11 | return false; 12 | } 13 | patternMap[pattern[i]] = wordMap[word] = i + 1; 14 | } 15 | return i == n; 16 | } 17 | }; -------------------------------------------------------------------------------- /Hashmap/Word Pattern/WordPattern.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool WordPattern(string pattern, string s) { 3 | Dictionary patternMap = new Dictionary(); 4 | Dictionary wordMap = new Dictionary(); 5 | string[] words = s.Split(' '); 6 | int i = 0, n = pattern.Length; 7 | 8 | if (n != words.Length) { 9 | return false; 10 | } 11 | 12 | for (i = 0; i < n; i++) { 13 | char currPatternChar = pattern[i]; 14 | string currWord = words[i]; 15 | if (!patternMap.ContainsKey(currPatternChar)) { 16 | patternMap[currPatternChar] = i; 17 | } 18 | if (!wordMap.ContainsKey(currWord)) { 19 | wordMap[currWord] = i; 20 | } 21 | if (patternMap[currPatternChar] != wordMap[currWord]) { 22 | return false; 23 | } 24 | } 25 | return true; 26 | } 27 | } -------------------------------------------------------------------------------- /Hashmap/Word Pattern/WordPattern.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | class Solution { 4 | public boolean wordPattern(String pattern, String s) { 5 | String[] array = s.split(" "); 6 | 7 | if (pattern.length() != array.length) 8 | return false; 9 | 10 | HashMap map = new HashMap<>(); 11 | 12 | for (int i = 0; i < pattern.length(); i++) { 13 | char currentChar = pattern.charAt(i); 14 | if (map.containsKey(currentChar)) { 15 | if (!map.get(currentChar).equals(array[i])) { 16 | return false; 17 | } 18 | } else { 19 | if (map.containsValue(array[i])) { 20 | return false; 21 | } 22 | } 23 | map.put(currentChar, array[i]); 24 | } 25 | return true; 26 | } 27 | } -------------------------------------------------------------------------------- /Hashmap/Word Pattern/WordPattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordPattern(self, pattern: str, s: str) -> bool: 3 | if not str or not pattern: 4 | return False 5 | strings = s.split() 6 | if len(strings) != len(pattern): 7 | return False 8 | str2pat = {} 9 | pat2str = {} 10 | for i in range(len(pattern)): 11 | if strings[i] in str2pat: 12 | if str2pat[strings[i]] != pattern[i]: 13 | return False 14 | else: 15 | str2pat[strings[i]] = pattern[i] 16 | if pattern[i] in pat2str: 17 | if pat2str[pattern[i]] != strings[i]: 18 | return False 19 | else: 20 | pat2str[pattern[i]] = strings[i] 21 | return True 22 | -------------------------------------------------------------------------------- /Linked List/Add Two Numbers/AddTwoNumbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 4 | ListNode* dummyHead = new ListNode(0); 5 | ListNode* tail = dummyHead; 6 | int carry = 0; 7 | 8 | while (l1 != nullptr || l2 != nullptr || carry != 0) { 9 | int digit1 = (l1 != nullptr) ? l1->val : 0; 10 | int digit2 = (l2 != nullptr) ? l2->val : 0; 11 | 12 | int sum = digit1 + digit2 + carry; 13 | int digit = sum % 10; 14 | carry = sum / 10; 15 | 16 | ListNode* newNode = new ListNode(digit); 17 | tail->next = newNode; 18 | tail = tail->next; 19 | 20 | l1 = (l1 != nullptr) ? l1->next : nullptr; 21 | l2 = (l2 != nullptr) ? l2->next : nullptr; 22 | } 23 | 24 | ListNode* result = dummyHead->next; 25 | delete dummyHead; 26 | return result; 27 | } 28 | }; -------------------------------------------------------------------------------- /Linked List/Add Two Numbers/AddTwoNumbers.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { 3 | ListNode dummyHead = new ListNode(0); 4 | ListNode tail = dummyHead; 5 | int carry = 0; 6 | while (l1 != null || l2 != null || carry != 0) { 7 | int digit1 = (l1 != null) ? l1.val : 0; 8 | int digit2 = (l2 != null) ? l2.val : 0; 9 | 10 | int sum = digit1 + digit2 + carry; 11 | int digit = sum % 10; 12 | carry = sum / 10; 13 | 14 | ListNode newNode = new ListNode(digit); 15 | tail.next = newNode; 16 | tail = tail.next; 17 | 18 | l1 = (l1 != null) ? l1.next : null; 19 | l2 = (l2 != null) ? l2.next : null; 20 | } 21 | 22 | ListNode result = dummyHead.next; 23 | return result; 24 | } 25 | } -------------------------------------------------------------------------------- /Linked List/Linked List Cycle/LinkedListCycle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasCycle(ListNode *head) { 4 | ListNode *slow = head, *fast = head; 5 | while (fast && fast->next) { 6 | slow = slow->next; 7 | fast = fast->next->next; 8 | if (slow == fast) return true; 9 | } 10 | return false; 11 | } 12 | }; -------------------------------------------------------------------------------- /Linked List/Linked List Cycle/LinkedListCycle.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool HasCycle(ListNode head) { 3 | ListNode slow = head, fast = head; 4 | while (fast != null && fast.next != null) { 5 | slow = slow.next; 6 | fast = fast.next.next; 7 | if (slow == fast) return true; 8 | } 9 | return false; 10 | } 11 | } -------------------------------------------------------------------------------- /Linked List/Linked List Cycle/LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean hasCycle(ListNode head) { 3 | ListNode slow = head; 4 | ListNode fast = head; 5 | 6 | while(fast != null && fast.next != null ){ 7 | fast=fast.next.next; 8 | slow=slow.next; 9 | 10 | if(slow==fast){ 11 | return true; 12 | } 13 | } 14 | return false; 15 | } 16 | } -------------------------------------------------------------------------------- /Linked List/Linked List Cycle/linked_list_cycle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hasCycle(self, head: Optional[ListNode]) -> bool: 3 | if not head: 4 | return False 5 | 6 | slow, fast = head, head.next 7 | 8 | while fast and fast.next: 9 | if fast == slow: 10 | return True 11 | 12 | slow = slow.next 13 | fast = fast.next.next 14 | 15 | return False 16 | -------------------------------------------------------------------------------- /Linked List/Merge Two Sorted Lists/MergeSortedLists.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 4 | if(l1 == NULL) 5 | return l2; 6 | 7 | if(l2 == NULL) 8 | return l1; 9 | 10 | if(l1 -> val <= l2 -> val) 11 | { 12 | l1 -> next = mergeTwoLists(l1 -> next, l2); 13 | return l1; 14 | } 15 | 16 | else 17 | { 18 | l2 -> next = mergeTwoLists(l1, l2 -> next); 19 | return l2; 20 | } 21 | } 22 | }; -------------------------------------------------------------------------------- /Linked List/Merge Two Sorted Lists/MergeSortedLists.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ListNode MergeTwoLists(ListNode l1, ListNode l2) { 3 | if (l1 == null) 4 | return l2; 5 | 6 | if (l2 == null) 7 | return l1; 8 | 9 | if (l1.val <= l2.val) { 10 | l1.next = MergeTwoLists(l1.next, l2); 11 | return l1; 12 | } 13 | else { 14 | l2.next = MergeTwoLists(l1, l2.next); 15 | return l2; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Linked List/Merge Two Sorted Lists/MergeSortedLists.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 3 | ListNode preHead = new ListNode(0); 4 | ListNode last = preHead; 5 | 6 | while(l1 != null && l2 != null) { 7 | if(l1.val > l2.val) { 8 | last.next = l2; 9 | l2 = l2.next; 10 | } else { 11 | last.next = l1; 12 | l1 = l1.next; 13 | } 14 | last = last.next; 15 | } 16 | 17 | if(l1 == null) { 18 | last.next = l2; 19 | } else { 20 | last.next = l1; 21 | } 22 | 23 | return preHead.next; 24 | } 25 | } -------------------------------------------------------------------------------- /Linked List/Merge Two Sorted Lists/merge_sorted_lists.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mergeTwoLists( 3 | self, list1: Optional[ListNode], list2: Optional[ListNode] 4 | ) -> Optional[ListNode]: 5 | if not list1: 6 | return list2 7 | 8 | if not list2: 9 | return list1 10 | 11 | dummy = ListNode() 12 | tail = dummy 13 | 14 | while list1 and list2: 15 | if list2.val > list1.val: 16 | tail.next = list1 17 | list1 = list1.next 18 | else: 19 | tail.next = list2 20 | list2 = list2.next 21 | tail = tail.next 22 | 23 | if list1: 24 | tail.next = list1 25 | if list2: 26 | tail.next = list2 27 | 28 | return dummy.next 29 | -------------------------------------------------------------------------------- /Linked List/Remove Nth Node From End of List/RemoveNthNodeFromEnd.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* removeNthFromEnd(ListNode* head, int n) { 4 | int counter = 0; 5 | ListNode* current = head; 6 | while (current != nullptr) { 7 | current = current->next; 8 | counter++; 9 | } 10 | current = head; 11 | if (counter == n) { 12 | head = head->next; 13 | delete current; 14 | return head; 15 | } 16 | for (int i = 0; i < counter - n - 1; i++) { 17 | current = current->next; 18 | } 19 | ListNode* temp = current->next; 20 | current->next = current->next->next; 21 | delete temp; 22 | return head; 23 | } 24 | }; -------------------------------------------------------------------------------- /Linked List/Remove Nth Node From End of List/RemoveNthNodeFromEnd.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ListNode RemoveNthFromEnd(ListNode head, int n) { 3 | int counter = 0; 4 | ListNode current = head; 5 | while (current != null) { 6 | current = current.next; 7 | counter++; 8 | } 9 | current = head; 10 | if (counter == n) { 11 | head = head.next; 12 | return head; 13 | } 14 | for (int i = 0; i < counter - n - 1; i++) { 15 | current = current.next; 16 | } 17 | ListNode temp = current.next; 18 | current.next = current.next.next; 19 | return head; 20 | } 21 | } -------------------------------------------------------------------------------- /Linked List/Rotate List/RotateList.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* rotateRight(ListNode* head, int k) { 4 | if (head == nullptr || head->next == nullptr || k == 0) { 5 | return head; 6 | } 7 | int length = 1; 8 | ListNode* tail = head; 9 | while (tail->next != nullptr) { 10 | length++; 11 | tail = tail->next; 12 | } 13 | k = k % length; 14 | if(k == 0) 15 | return head; 16 | ListNode* newTail = head; 17 | for (int i = 0; i < length - k - 1; i++) { 18 | newTail = newTail->next; 19 | } 20 | ListNode* newHead = newTail->next; 21 | newTail->next = nullptr; 22 | tail->next = head; 23 | return newHead; 24 | } 25 | }; -------------------------------------------------------------------------------- /Linked List/Rotate List/RotateList.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ListNode RotateRight(ListNode head, int k) { 3 | if (head == null || head.next == null || k == 0) { 4 | return head; 5 | } 6 | int length = 1; 7 | ListNode tail = head; 8 | while (tail.next != null) { 9 | length++; 10 | tail = tail.next; 11 | } 12 | k = k % length; 13 | if(k == 0) 14 | return head; 15 | ListNode newTail = head; 16 | for (int i = 0; i < length - k - 1; i++) { 17 | newTail = newTail.next; 18 | } 19 | ListNode newHead = newTail.next; 20 | newTail.next = null; 21 | tail.next = head; 22 | return newHead; 23 | } 24 | }; -------------------------------------------------------------------------------- /Math/Factorial Trailing Zeroes/TrailingZeros.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trailingZeroes(int n) { 4 | int count = 0, i = 5; 5 | while (i <= n) 6 | { 7 | count += n / i; 8 | i *= 5; 9 | } 10 | return count; 11 | } 12 | }; -------------------------------------------------------------------------------- /Math/Factorial Trailing Zeroes/TrailingZeros.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int TrailingZeroes(int n) { 3 | int count = 0, i = 5; 4 | while (i <= n) 5 | { 6 | count += n / i; 7 | i *= 5; 8 | } 9 | return count; 10 | } 11 | } -------------------------------------------------------------------------------- /Math/Factorial Trailing Zeroes/TrailingZeros.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int trailingZeroes(int n) { 3 | int sum = 0; 4 | 5 | if (n < 5) { 6 | return 0; 7 | } 8 | while (n >= 5) { 9 | sum = sum + n / 5; 10 | n = n / 5; 11 | } 12 | return sum; 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /Math/Factorial Trailing Zeroes/TrailingZeros.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trailingZeroes(self, n: int) -> int: 3 | if n < 5: 4 | return 0 5 | 6 | count = 0 7 | for i in range(1, n + 1): 8 | j = i 9 | while j % 5 == 0: 10 | count += 1 11 | j //= 5 12 | return count 13 | -------------------------------------------------------------------------------- /Math/Max Points on a Line/MaxPoints.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxPoints(vector>& points) { 4 | int counter = 1; 5 | if (points.size() < 2) { 6 | return 1; 7 | } 8 | for (int i = 0; i < points.size(); ++i) { 9 | unordered_map slope; 10 | for (int j = i + 1; j < points.size(); ++j) { 11 | int y = points[j][1] - points[i][1]; 12 | int x = points[j][0] - points[i][0]; 13 | if (x != 0) { 14 | slope[static_cast(y) / x] = 1 + slope[static_cast(y) / x]; 15 | } else { 16 | slope[numeric_limits::infinity()] = 1 + slope[numeric_limits::infinity()]; 17 | } 18 | } 19 | for (const auto& kv : slope) { 20 | counter = max(counter, kv.second); 21 | } 22 | } 23 | return counter + 1; 24 | } 25 | }; -------------------------------------------------------------------------------- /Math/Max Points on a Line/MaxPoints.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MaxPoints(int[][] points) { 3 | int counter = 1; 4 | if (points.Length < 2) { 5 | return 1; 6 | } 7 | 8 | for (int i = 0; i < points.Length; i++) { 9 | Dictionary slope = new Dictionary(); 10 | for (int j = i + 1; j < points.Length; j++) { 11 | int y = points[j][1] - points[i][1]; 12 | int x = points[j][0] - points[i][0]; 13 | if (x != 0) { 14 | double currentSlope = (double)y / x; 15 | if (!slope.ContainsKey(currentSlope)) { 16 | slope[currentSlope] = 0; 17 | } 18 | slope[currentSlope]++; 19 | } else { 20 | if (!slope.ContainsKey(double.PositiveInfinity)) { 21 | slope[double.PositiveInfinity] = 0; 22 | } 23 | slope[double.PositiveInfinity]++; 24 | } 25 | } 26 | foreach (var kvp in slope) { 27 | counter = Math.Max(counter, kvp.Value); 28 | } 29 | } 30 | 31 | return counter + 1; 32 | } 33 | } -------------------------------------------------------------------------------- /Math/Max Points on a Line/MaxPoints.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | class Solution { 4 | public int maxPoints(int[][] points) { 5 | if (points.length <= 0) 6 | return 0; 7 | if (points.length <= 2) 8 | return points.length; 9 | 10 | int max = 0; 11 | 12 | for (int[] point1 : points) { 13 | HashMap map = new HashMap<>(); 14 | for (int[] point2 : points) { 15 | if (point1 == point2) 16 | continue; 17 | 18 | double slope = 0; 19 | 20 | if (point2[0] == point1[0]) { 21 | slope = Double.POSITIVE_INFINITY; 22 | } else { 23 | slope = (point2[1] - point1[1]) / (double) (point2[0] - point1[0]); 24 | } 25 | map.put(slope, map.getOrDefault(slope, 0) + 1); 26 | if (map.get(slope) > max) { 27 | max = map.get(slope); 28 | } 29 | } 30 | } 31 | return max + 1; 32 | } 33 | } -------------------------------------------------------------------------------- /Math/Max Points on a Line/MaxPoints.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxPoints(self, points: List[List[int]]) -> int: 3 | if len(points) <= 2: 4 | return len(points) 5 | 6 | result = 0 7 | for p1 in points: 8 | collinear_points = {} 9 | for p2 in points: 10 | if p1 == p2: 11 | continue 12 | 13 | slope = 0 14 | if p2[0] == p1[0]: 15 | slope = float("inf") 16 | else: 17 | slope = (p2[1] - p1[1]) / (p2[0] - p1[0]) 18 | 19 | collinear_points[slope] = collinear_points.get(slope, 0) + 1 20 | 21 | if collinear_points[slope] > result: 22 | result = collinear_points[slope] 23 | 24 | return result + 1 25 | -------------------------------------------------------------------------------- /Math/Palindrome Number/PalindromeNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) { 4 | if (x < 0) 5 | return false; 6 | return x == reverse(x); 7 | } 8 | 9 | int reverse(int num) { 10 | int reversed = 0; 11 | while (num != 0) { 12 | int digit = num % 10; 13 | if (reversed > INT_MAX / 10 || (reversed == INT_MAX / 10 && digit > 7)) { 14 | return 0; 15 | } 16 | reversed = reversed * 10 + digit; 17 | num /= 10; 18 | } 19 | return reversed; 20 | } 21 | }; -------------------------------------------------------------------------------- /Math/Palindrome Number/PalindromeNumber.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool IsPalindrome(int x) { 3 | if (x < 0) 4 | return false; 5 | return x == Reverse(x); 6 | } 7 | 8 | public static int Reverse(int num) { 9 | int reversed = 0; 10 | while (num != 0) { 11 | int digit = num % 10; 12 | reversed = reversed * 10 + digit; 13 | num /= 10; 14 | } 15 | return reversed; 16 | } 17 | } -------------------------------------------------------------------------------- /Math/Palindrome Number/PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPalindrome(int x) { 3 | int temp = x, sum = 0; 4 | while (temp > 0) { 5 | int digit = temp % 10; 6 | sum = (sum * 10) + digit; 7 | temp = temp / 10; 8 | } 9 | 10 | if (sum == x) 11 | return true; 12 | 13 | return false; 14 | } 15 | } -------------------------------------------------------------------------------- /Math/Palindrome Number/PalindromeNumber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, x: int) -> bool: 3 | if x < 0: 4 | return False 5 | 6 | rev = 0 7 | temp = x 8 | while temp > 0: 9 | rev = (rev * 10) + (temp % 10) 10 | temp = temp // 10 11 | return rev == x 12 | -------------------------------------------------------------------------------- /Math/Plus One/PlusOne.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector plusOne(vector& digits) { 4 | int carry = 1; 5 | for (int i = digits.size() - 1; i >= 0; i--) { 6 | int sum = digits[i] + carry; 7 | digits[i] = sum % 10; 8 | carry = sum / 10; 9 | } 10 | 11 | if (carry == 1) { 12 | digits.insert(digits.begin(), 1); 13 | } 14 | 15 | return digits; 16 | } 17 | }; -------------------------------------------------------------------------------- /Math/Plus One/PlusOne.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] PlusOne(int[] digits) { 3 | int carry = 1; 4 | for (int i = digits.Length - 1; i >= 0; i--) { 5 | int sum = digits[i] + carry; 6 | digits[i] = sum % 10; 7 | carry = sum / 10; 8 | } 9 | 10 | if (carry == 1) { 11 | List result = new List(digits); 12 | result.Insert(0, 1); 13 | return result.ToArray(); 14 | } 15 | 16 | return digits; 17 | } 18 | } -------------------------------------------------------------------------------- /Math/Plus One/PlusOne.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] plusOne(int[] digits) { 3 | for (int i = digits.length - 1; i >= 0; i--) { 4 | if (digits[i] < 9) { 5 | digits[i]++; 6 | return digits; 7 | } 8 | digits[i] = 0; 9 | } 10 | int[] newArray = new int[digits.length + 1]; 11 | newArray[0] = 1; 12 | return newArray; 13 | } 14 | } -------------------------------------------------------------------------------- /Math/Plus One/PlusOne.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def plusOne(self, digits: List[int]) -> List[int]: 3 | for i in range(len(digits) - 1, -1, -1): 4 | if digits[i] < 9: 5 | digits[i] += 1 6 | return digits 7 | 8 | digits[i] = 0 9 | 10 | digits = [0] * (len(digits) + 1) 11 | digits[0] = 1 12 | return digits 13 | -------------------------------------------------------------------------------- /Math/Pow(x,n)/Power.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double myPow(double x, int n) { 4 | if (n == INT_MIN) { 5 | n = -(n + 1); 6 | x = 1.0 / x; 7 | return x * x * myPow(x * x, n / 2); 8 | } 9 | 10 | if (n == 0) { 11 | return 1.0; 12 | } 13 | 14 | if (n < 0) { 15 | x = 1.0 / x; 16 | n = -n; 17 | } 18 | 19 | if (n % 2 == 0) { 20 | double y = myPow(x, n / 2); 21 | return y * y; 22 | } 23 | else { 24 | double y = myPow(x, (n - 1) / 2); 25 | return y * y * x; 26 | } 27 | } 28 | }; -------------------------------------------------------------------------------- /Math/Pow(x,n)/Power.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public double MyPow(double x, int n) { 3 | if (n == Int32.MinValue) { 4 | n = -(n + 1); 5 | x = 1.0 / x; 6 | return x * x * MyPow(x * x, n / 2); 7 | } 8 | 9 | if (n == 0) { 10 | return 1.0; 11 | } 12 | 13 | if (n < 0) { 14 | x = 1.0 / x; 15 | n = -n; 16 | } 17 | 18 | if (n % 2 == 0) { 19 | double y = MyPow(x, n / 2); 20 | return y * y; 21 | } 22 | else { 23 | double y = MyPow(x, (n - 1) / 2); 24 | return y * y * x; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /Math/Pow(x,n)/Power.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double myPow(double x, int n) { 3 | double ans = 1; 4 | long absN = Math.abs((long) n); 5 | while (absN > 0) { 6 | if ((absN & 1) == 1) 7 | ans *= x; 8 | absN >>= 1; 9 | x *= x; 10 | } 11 | return n < 0 ? 1 / ans : ans; 12 | } 13 | } -------------------------------------------------------------------------------- /Math/Pow(x,n)/Power.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x: float, n: int) -> float: 3 | if n == 0: 4 | return 1 5 | 6 | if n < 0: 7 | return 1 / self.myPow(x, -n) 8 | 9 | if n % 2 == 0: 10 | return self.myPow(x * x, n // 2) 11 | 12 | return x * self.myPow(x * x, (n - 1) // 2) 13 | -------------------------------------------------------------------------------- /Math/Sqrt(x)/sqrt.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int mySqrt(int x) { 4 | if (x == 0 || x == 1) 5 | return x; 6 | int first = 1, last = x; 7 | while (first <= last) { 8 | int mid = first + (last - first) / 2; 9 | if (mid == x / mid) 10 | return mid; 11 | else if (mid > x / mid) { 12 | last = mid - 1; 13 | } 14 | else { 15 | first = mid + 1; 16 | } 17 | } 18 | return last; 19 | } 20 | }; -------------------------------------------------------------------------------- /Math/Sqrt(x)/sqrt.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int MySqrt(int x) { 3 | if (x == 0 || x == 1) 4 | return x; 5 | int first = 1, last = x; 6 | while (first <= last) { 7 | int mid = first + (last - first) / 2; 8 | if (mid == x / mid) 9 | return mid; 10 | else if (mid > x / mid) { 11 | last = mid - 1; 12 | } 13 | else { 14 | first = mid + 1; 15 | } 16 | } 17 | return last; 18 | } 19 | } -------------------------------------------------------------------------------- /Math/Sqrt(x)/sqrt.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int mySqrt(int x) { 3 | if (x < 2) { 4 | return x; 5 | } 6 | long start = 1; 7 | long end = x; 8 | 9 | while (start <= end) { 10 | long mid = (start + end) / 2; 11 | 12 | if (mid * mid == x) { 13 | return (int) mid; 14 | } else if (mid * mid > x) { 15 | end = mid - 1; 16 | } else { 17 | start = mid + 1; 18 | } 19 | } 20 | return (int) end; 21 | } 22 | } -------------------------------------------------------------------------------- /Math/Sqrt(x)/sqrt.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mySqrt(self, x: int) -> int: 3 | if x == 0 or x == 1: 4 | return x 5 | 6 | guess = x 7 | while abs(x - guess * guess) > 1e-6: 8 | guess = (guess + (x / guess)) / 2 9 | return math.floor(guess) 10 | -------------------------------------------------------------------------------- /Stack/Basic Calculator/BasicCalculator.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int calculate(string s) { 4 | stack stack; 5 | 6 | long result = 0; 7 | auto sign = 1; 8 | long number = 0; 9 | 10 | for (auto i = 0; i < s.size(); i++) { 11 | switch (s[i]) { 12 | case ' ': 13 | continue; 14 | 15 | case '+': 16 | case '-': 17 | result += number * sign; 18 | sign = s[i] == '+' ? 1 : -1; 19 | number = 0; 20 | break; 21 | 22 | case '(': 23 | stack.push(result); 24 | stack.push(sign); 25 | result = 0; 26 | sign = 1; 27 | break; 28 | 29 | case ')': 30 | result += number * sign; 31 | result *= stack.top(); 32 | stack.pop(); 33 | result += stack.top(); 34 | stack.pop(); 35 | number = 0; 36 | break; 37 | 38 | default: 39 | while (i < s.size() && isdigit(s[i])) { 40 | number = number * 10 + s[i] - '0'; 41 | i++; 42 | } 43 | i--; 44 | } 45 | } 46 | 47 | return result + (number * sign); 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Stack/Basic Calculator/BasicCalculator.cs: -------------------------------------------------------------------------------- 1 | public class Solution 2 | { 3 | public int Calculate(string s) 4 | { 5 | int output = 0, curr = 0, sign = 1; 6 | Stack stack = new Stack(); 7 | for (int i = 0; i < s.Length; i++) 8 | { 9 | char c = s[i]; 10 | if (char.IsDigit(c)) 11 | { 12 | curr = (curr * 10) + (c - '0'); 13 | } 14 | else if (c == '+' || c == '-') 15 | { 16 | output += curr * sign; 17 | curr = 0; 18 | sign = (c == '+') ? 1 : -1; 19 | } 20 | else if (c == '(') 21 | { 22 | stack.Push(output); 23 | stack.Push(sign); 24 | output = 0; 25 | sign = 1; 26 | } 27 | else if (c == ')') 28 | { 29 | output += curr * sign; 30 | output *= stack.Pop(); 31 | output += stack.Pop(); 32 | curr = 0; 33 | } 34 | } 35 | return output + (curr * sign); 36 | } 37 | } -------------------------------------------------------------------------------- /Stack/Basic Calculator/BasicCalculator.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | class Solution { 4 | public int calculate(String s) { 5 | Stack stack = new Stack(); 6 | int result = 0; 7 | int number = 0; 8 | int sign = 1; 9 | for (int i = 0; i < s.length(); i++) { 10 | char c = s.charAt(i); 11 | if (Character.isDigit(c)) { 12 | number = 10 * number + (int) (c - '0'); 13 | } else if (c == '+') { 14 | result += sign * number; 15 | number = 0; 16 | sign = 1; 17 | } else if (c == '-') { 18 | result += sign * number; 19 | number = 0; 20 | sign = -1; 21 | } else if (c == '(') { 22 | 23 | stack.push(result); 24 | stack.push(sign); 25 | 26 | sign = 1; 27 | result = 0; 28 | } else if (c == ')') { 29 | result += sign * number; 30 | number = 0; 31 | result *= stack.pop(); 32 | result += stack.pop(); 33 | 34 | } 35 | } 36 | if (number != 0) 37 | result += sign * number; 38 | return result; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Stack/Basic Calculator/BasicCalculator.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def calculate(self, s: str) -> int: 3 | output, curr, sign, stack = 0, 0, 1, [] 4 | for i in range(len(s)): 5 | c = s[i] 6 | if c.isdigit(): 7 | curr = (curr * 10) + int(c) 8 | elif c in "+-": 9 | output += curr * sign 10 | curr = 0 11 | sign = 1 if c == "+" else -1 12 | elif c == "(": 13 | stack.append(output) 14 | stack.append(sign) 15 | output = 0 16 | sign = 1 17 | elif c == ")": 18 | output += curr * sign 19 | output *= stack.pop() 20 | output += stack.pop() 21 | curr = 0 22 | return output + (curr * sign) 23 | -------------------------------------------------------------------------------- /Stack/Evaluate Reverse Polish Notation/Evaluate.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int evalRPN(vector &tokens) { 4 | stack st; 5 | 6 | for (const string& token : tokens) { 7 | if (isOperator(token)) { 8 | int operand2 = st.top(); st.pop(); 9 | int operand1 = st.top(); st.pop(); 10 | st.push(performOperation(operand1, operand2, token)); 11 | } else { 12 | st.push(stoi(token)); 13 | } 14 | } 15 | 16 | return st.top(); 17 | } 18 | 19 | private: 20 | bool isOperator(const string& token) { 21 | return (token == "+" || token == "-" || token == "*" || token == "/"); 22 | } 23 | 24 | int performOperation(int operand1, int operand2, const string& op) { 25 | switch (op[0]) { 26 | case '+': 27 | return operand1 + operand2; 28 | case '-': 29 | return operand1 - operand2; 30 | case '*': 31 | return operand1 * operand2; 32 | case '/': 33 | return operand1 / operand2; 34 | default: 35 | return 0; 36 | } 37 | } 38 | }; -------------------------------------------------------------------------------- /Stack/Evaluate Reverse Polish Notation/Evaluate.cs: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int EvalRPN(string[] tokens) { 3 | Stack st = new Stack(); 4 | 5 | foreach (string token in tokens) { 6 | if (IsOperator(token)) { 7 | int operand2 = st.Pop(); 8 | int operand1 = st.Pop(); 9 | st.Push(PerformOperation(operand1, operand2, token)); 10 | } else { 11 | st.Push(int.Parse(token)); 12 | } 13 | } 14 | 15 | return st.Pop(); 16 | } 17 | 18 | private bool IsOperator(string token) { 19 | return (token == "+" || token == "-" || token == "*" || token == "/"); 20 | } 21 | 22 | private int PerformOperation(int operand1, int operand2, string op) { 23 | switch (op) { 24 | case "+": 25 | return operand1 + operand2; 26 | case "-": 27 | return operand1 - operand2; 28 | case "*": 29 | return operand1 * operand2; 30 | case "/": 31 | return operand1 / operand2; 32 | default: 33 | return 0; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Stack/Evaluate Reverse Polish Notation/Evaluate.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class Solution { 4 | public int evalRPN(String[] tokens) { 5 | int a,b; 6 | Stack S = new Stack(); 7 | for (String s : tokens) { 8 | if(s.equals("+")) { 9 | S.add(S.pop()+S.pop()); 10 | } 11 | else if(s.equals("/")) { 12 | b = S.pop(); 13 | a = S.pop(); 14 | S.add(a / b); 15 | } 16 | else if(s.equals("*")) { 17 | S.add(S.pop() * S.pop()); 18 | } 19 | else if(s.equals("-")) { 20 | b = S.pop(); 21 | a = S.pop(); 22 | S.add(a - b); 23 | } 24 | else { 25 | S.add(Integer.parseInt(s)); 26 | } 27 | } 28 | return S.pop(); 29 | } 30 | } -------------------------------------------------------------------------------- /Stack/Evaluate Reverse Polish Notation/Evaluate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def evalRPN(self, tokens: List[str]) -> int: 3 | operands = { 4 | '+': lambda x, y: x + y, 5 | '-': lambda x, y: x - y, 6 | '/': lambda x, y: int(x / y), 7 | '*': lambda x, y: x * y, 8 | } 9 | 10 | stack = [] 11 | for token in tokens: 12 | if token in operands: 13 | x = stack.pop() 14 | y = stack.pop() 15 | result = operands[token](y, x) 16 | stack.append(result) 17 | else: 18 | stack.append(int(token)) 19 | return stack.pop() -------------------------------------------------------------------------------- /Stack/Min Stack/MinStack.cpp: -------------------------------------------------------------------------------- 1 | class MinStack 2 | { 3 | private: 4 | struct StackElement 5 | { 6 | int value; 7 | int minValue; 8 | 9 | StackElement(int val, int minVal) : value(val), minValue(minVal) {} 10 | }; 11 | 12 | stack minStack; 13 | 14 | public: 15 | MinStack() {} 16 | 17 | void push(int val) 18 | { 19 | if (minStack.empty()) 20 | { 21 | minStack.push(StackElement(val, val)); 22 | } 23 | else 24 | { 25 | int newMin = std::min(val, minStack.top().minValue); 26 | minStack.push(StackElement(val, newMin)); 27 | } 28 | } 29 | 30 | void pop() 31 | { 32 | if (!minStack.empty()) 33 | { 34 | minStack.pop(); 35 | } 36 | } 37 | 38 | int top() 39 | { 40 | return minStack.top().value; 41 | } 42 | 43 | int getMin() 44 | { 45 | return minStack.top().minValue; 46 | } 47 | }; -------------------------------------------------------------------------------- /Stack/Min Stack/MinStack.cs: -------------------------------------------------------------------------------- 1 | public class MinStack 2 | { 3 | private class StackElement 4 | { 5 | public int Value { get; } 6 | public int MinValue { get; } 7 | 8 | public StackElement(int value, int minValue) 9 | { 10 | Value = value; 11 | MinValue = minValue; 12 | } 13 | } 14 | 15 | private Stack minStack; 16 | 17 | public MinStack() 18 | { 19 | minStack = new Stack(); 20 | } 21 | 22 | public void Push(int val) 23 | { 24 | if (minStack.Count == 0) 25 | { 26 | minStack.Push(new StackElement(val, val)); 27 | } 28 | else 29 | { 30 | int newMin = Math.Min(val, minStack.Peek().MinValue); 31 | minStack.Push(new StackElement(val, newMin)); 32 | } 33 | } 34 | 35 | public void Pop() 36 | { 37 | if (minStack.Count > 0) 38 | { 39 | minStack.Pop(); 40 | } 41 | } 42 | 43 | public int Top() 44 | { 45 | return minStack.Peek().Value; 46 | } 47 | 48 | public int GetMin() 49 | { 50 | return minStack.Peek().MinValue; 51 | } 52 | } -------------------------------------------------------------------------------- /Stack/Min Stack/MinStack.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | class MinStack { 4 | Stack stack; 5 | 6 | public MinStack() { 7 | stack = new Stack<>(); 8 | } 9 | 10 | public void push(int val) { 11 | if (stack.isEmpty()) { 12 | stack.push(new PairStack(val, val)); 13 | } else { 14 | int currentMinInStack = stack.peek().min; 15 | stack.push(new PairStack(val, Math.min(currentMinInStack, val))); 16 | } 17 | } 18 | 19 | public void pop() { 20 | if (!stack.isEmpty()) { 21 | stack.pop(); 22 | } 23 | } 24 | 25 | public int top() { 26 | return stack.peek().val; 27 | } 28 | 29 | public int getMin() { 30 | return stack.peek().min; 31 | } 32 | 33 | class PairStack { 34 | int val; 35 | int min; 36 | 37 | PairStack(int val, int min) { 38 | this.val = val; 39 | this.min = min; 40 | } 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Stack/Min Stack/MinStack.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | def __init__(self): 3 | self.stack = [] 4 | 5 | def push(self, val: int) -> None: 6 | self.stack.append(val) 7 | 8 | def pop(self) -> None: 9 | self.stack.pop() 10 | 11 | def top(self) -> int: 12 | return self.stack[-1] 13 | 14 | def getMin(self) -> int: 15 | return min(self.stack) 16 | -------------------------------------------------------------------------------- /Stack/Simplify Path/SimplifyPath.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string simplifyPath(string path) { 4 | deque queue; 5 | string current; 6 | for (const auto &p : path + "/") { 7 | if (p == '/') { 8 | if (current == ".." && !queue.empty()) 9 | queue.pop_back(); 10 | else if (current != "" && current != "." && current != "..") 11 | queue.push_back(current); 12 | current = ""; 13 | } else 14 | current += p; 15 | } 16 | 17 | string result = {}; 18 | 19 | if (queue.empty()) 20 | result = "/"; 21 | while (!queue.empty()) { 22 | result.append("/").append(queue.front()); 23 | queue.pop_front(); 24 | } 25 | 26 | return result; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Stack/Simplify Path/SimplifyPath.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public string SimplifyPath(string path) { 3 | Stack stack = new Stack(); 4 | string[] components = path.Split('/'); 5 | 6 | foreach (string component in components) { 7 | if (component == "..") { 8 | if (stack.Count > 0) { 9 | stack.Pop(); 10 | } 11 | } else if (!string.IsNullOrEmpty(component) && component != ".") { 12 | stack.Push(component); 13 | } 14 | } 15 | 16 | string[] simplifiedPathArray = stack.ToArray(); 17 | Array.Reverse(simplifiedPathArray); 18 | string simplifiedPath = "/" + string.Join("/", simplifiedPathArray); 19 | 20 | return string.IsNullOrEmpty(simplifiedPath) ? "/" : simplifiedPath; 21 | } 22 | } -------------------------------------------------------------------------------- /Stack/Simplify Path/SimplifyPath.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String simplifyPath(String path) { 3 | Deque stack = new LinkedList<>(); 4 | Set skip = new HashSet<>(Arrays.asList("..", ".", "")); 5 | for (String dir : path.split("/")) { 6 | if (dir.equals("..") && !stack.isEmpty()) 7 | stack.pop(); 8 | else if (!skip.contains(dir)) 9 | stack.push(dir); 10 | } 11 | String res = ""; 12 | for (String dir : stack) 13 | res = "/" + dir + res; 14 | return res.isEmpty() ? "/" : res; 15 | } 16 | } -------------------------------------------------------------------------------- /Stack/Simplify Path/SimplifyPath.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def simplifyPath(self, path: str) -> str: 3 | stack = deque() 4 | components = path.split("/") 5 | for component in components: 6 | if component == "..": 7 | if stack: 8 | stack.pop() 9 | elif component and component != ".": 10 | stack.append(component) 11 | simplified_path = "/" + "/".join(stack) 12 | return simplified_path if simplified_path else "/" 13 | -------------------------------------------------------------------------------- /Stack/Valid Parentheses/ValidParentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isValid(string s) 5 | { 6 | stack st; 7 | for (auto i : s) 8 | { 9 | if (st.empty() && (i == ')' || i == ']' || i == '}')) 10 | { 11 | return false; 12 | } 13 | else if (i == '(' || i == '[' || i == '{') 14 | { 15 | st.push(i); 16 | } 17 | else if (!st.empty() && st.top() == '[' && i == ']') 18 | { 19 | st.pop(); 20 | } 21 | else if (!st.empty() && st.top() == '(' && i == ')') 22 | { 23 | st.pop(); 24 | } 25 | else if (!st.empty() && st.top() == '{' && i == '}') 26 | { 27 | st.pop(); 28 | } 29 | else 30 | return false; 31 | } 32 | if (st.size() == 0) 33 | return true; 34 | return false; 35 | } 36 | }; -------------------------------------------------------------------------------- /Stack/Valid Parentheses/ValidParentheses.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool IsValid(string s) { 3 | Stack st = new Stack(); 4 | foreach (char i in s) 5 | { 6 | if (st.Count == 0 && (i == ')' || i == ']' || i == '}')) 7 | { 8 | return false; 9 | } 10 | else if (i == '(' || i == '[' || i == '{') 11 | { 12 | st.Push(i); 13 | } 14 | else if (st.Count > 0 && st.Peek() == '[' && i == ']') 15 | { 16 | st.Pop(); 17 | } 18 | else if (st.Count > 0 && st.Peek() == '(' && i == ')') 19 | { 20 | st.Pop(); 21 | } 22 | else if (st.Count > 0 && st.Peek() == '{' && i == '}') 23 | { 24 | st.Pop(); 25 | } 26 | else 27 | { 28 | return false; 29 | } 30 | } 31 | if (st.Count == 0) 32 | return true; 33 | return false; 34 | } 35 | } -------------------------------------------------------------------------------- /Stack/Valid Parentheses/ValidParentheses.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | class Solution { 4 | public boolean isValid(String s) { 5 | Stack stack = new Stack<>(); 6 | for (char x : s.toCharArray()) { 7 | if (x == '(') { 8 | stack.push(')'); 9 | } else if (x == '{') { 10 | stack.push('}'); 11 | } else if (x == '[') { 12 | stack.push(']'); 13 | } else if (stack.isEmpty() || stack.pop() != x) { 14 | return false; 15 | } 16 | } 17 | return stack.isEmpty(); 18 | } 19 | } -------------------------------------------------------------------------------- /Stack/Valid Parentheses/ValidParentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s: str) -> bool: 3 | if (len(s) % 2 != 0): 4 | return False 5 | 6 | pairs = { 7 | "}": "{", 8 | "]": "[", 9 | ")": "(" 10 | } 11 | stack = [] 12 | 13 | for i in s: 14 | if i in pairs: 15 | if len(stack) > 0 and pairs[i] == stack[-1]: 16 | stack.pop() 17 | else: 18 | return False 19 | else: 20 | stack.append(i) 21 | 22 | return len(stack) == 0 23 | -------------------------------------------------------------------------------- /Two Pointers/Is Subsequence/isSubsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSubsequence(string s, string t) { 4 | if (s.length() > t.length()) 5 | return false; 6 | if (s.length() == 0) 7 | return true; 8 | 9 | int l = 0; 10 | int r = 0; 11 | 12 | while (l < s.length() && r < t.length()) { 13 | if (s[l] == t[r]) 14 | l++; 15 | r++; 16 | } 17 | 18 | return l == s.length(); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Two Pointers/Is Subsequence/isSubsequence.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool IsSubsequence(string s, string t) { 3 | foreach (char c in s) { 4 | int i = t.IndexOf(c); 5 | if (i == -1) { 6 | return false; 7 | } 8 | t = t.Substring(i + 1); 9 | } 10 | return true; 11 | } 12 | } -------------------------------------------------------------------------------- /Two Pointers/Is Subsequence/isSubsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isSubsequence(String s, String t) { 3 | int j = 0; 4 | 5 | if (s.length() < 1) { 6 | return true; 7 | } 8 | 9 | for (int i = 0; i < t.length(); i++) { 10 | if (s.charAt(j) == t.charAt(i)) { 11 | j++; 12 | } 13 | if (j == s.length()) { 14 | return true; 15 | } 16 | } 17 | 18 | return false; 19 | } 20 | } -------------------------------------------------------------------------------- /Two Pointers/Is Subsequence/isSubsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSubsequence(self, s: str, t: str) -> bool: 3 | for c in s: 4 | i = t.find(c) 5 | if i == -1: 6 | return False 7 | t = t[i + 1 :] 8 | return True 9 | -------------------------------------------------------------------------------- /Two Pointers/Valid Palindrome/validPalindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(string s) { 4 | string cleaned = ""; 5 | for (auto i : s) { 6 | if (isalnum(i)) 7 | cleaned.push_back(tolower(i)); 8 | } 9 | 10 | int l = 0; 11 | int r = cleaned.length() - 1; 12 | 13 | while (l < r) { 14 | if (cleaned[l] != cleaned[r]) 15 | return false; 16 | l++; 17 | r--; 18 | } 19 | return true; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Two Pointers/Valid Palindrome/validPalindrome.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool IsPalindrome(string s) { 3 | string res = new string(s.Where(char.IsLetterOrDigit).ToArray()).ToLower(); 4 | return res == new string(res.Reverse().ToArray()); 5 | } 6 | } -------------------------------------------------------------------------------- /Two Pointers/Valid Palindrome/validPalindrome.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPalindrome(String s) { 3 | String fixed = ""; 4 | 5 | for (char x : s.toCharArray()) { 6 | if (Character.isLetterOrDigit(x)) { 7 | fixed += x; 8 | } 9 | } 10 | fixed = fixed.toLowerCase(); 11 | int i = 0; 12 | int j = fixed.length() - 1; 13 | 14 | while (i <= j) { 15 | if (fixed.charAt(i) != fixed.charAt(j)) { 16 | return false; 17 | } 18 | j--; 19 | i++; 20 | } 21 | return true; 22 | } 23 | } -------------------------------------------------------------------------------- /Two Pointers/Valid Palindrome/validPalindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, s: str) -> bool: 3 | res = "".join(x for x in s if x.isalnum()).lower() 4 | return res == res[::-1] 5 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 |

Leetcode Top Interview 150

2 |

3 | C++ 7 | C# 11 | Java 15 | Python 19 | Neovim 23 | Sublime Text 27 | vscode 31 |

32 |

33 | This repository contains leetcode Top 150 Interview Problems solutions source code in C++, C#, Java, and Python Programming languages. 34 |

35 |

Questions List Progress bar

39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 | 627 | 630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 | 658 | 659 | 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 671 | 672 | 673 | 674 | 675 | 676 | 677 | 678 | 679 | 680 | 681 | 682 | 683 | 684 | 685 | 686 | 687 | 688 | 689 | 690 | 691 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 | 702 | 703 | 704 | 705 | 706 | 707 | 708 | 709 | 710 | 711 | 712 | 713 | 714 | 717 | 718 | 719 | 720 | 721 | 722 | 723 | 724 | 725 | 726 | 727 | 728 | 729 | 730 | 731 | 732 | 733 | 734 | 735 | 736 | 737 | 738 | 739 | 740 | 741 | 742 | 743 | 744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 | 752 | 753 | 754 | 755 | 756 | 757 | 758 | 759 | 760 | 761 | 764 | 765 | 766 | 767 | 768 | 769 | 770 | 771 | 772 | 773 | 774 | 775 | 776 | 777 | 778 | 779 | 780 | 781 | 782 | 783 | 784 | 785 | 786 | 787 | 788 | 789 | 790 | 793 | 794 | 795 | 796 | 797 | 798 | 799 | 800 | 801 | 802 | 803 | 804 | 805 | 806 | 807 | 810 | 811 | 812 | 813 | 814 | 815 | 816 | 817 | 818 | 819 | 820 | 821 | 822 | 823 | 824 | 825 | 826 | 827 | 828 | 829 | 830 | 831 | 832 | 833 | 834 | 835 | 836 | 837 | 838 | 839 | 840 | 841 | 842 | 843 | 844 | 845 | 846 | 847 | 848 | 849 | 850 | 851 | 852 | 853 | 854 | 857 | 858 | 859 | 860 | 861 | 862 | 863 | 864 | 865 | 866 | 867 | 868 | 869 | 870 | 871 | 872 | 873 | 874 | 875 | 876 | 877 | 878 | 879 | 880 | 881 | 882 | 883 | 886 | 887 | 888 | 889 | 890 | 891 | 892 | 893 | 894 | 895 | 896 | 897 | 898 | 899 | 900 | 901 | 902 | 903 | 904 | 905 | 906 | 907 | 908 | 909 | 910 | 911 | 912 | 913 | 914 | 915 | 916 | 917 | 918 | 919 | 920 | 921 | 922 | 923 | 924 | 927 | 928 | 929 | 930 | 931 | 932 | 933 | 934 | 935 | 936 | 937 | 938 | 939 | 940 | 941 | 942 | 943 | 944 | 945 | 946 | 947 | 948 | 949 | 950 | 951 | 952 | 953 | 954 | 955 | 956 | 957 | 958 | 959 | 960 | 961 | 962 | 963 | 964 | 965 | 968 | 969 | 970 | 971 | 972 | 973 | 974 | 975 | 976 | 977 | 978 | 979 | 980 | 981 | 982 | 983 | 984 | 985 | 986 | 987 | 988 | 989 | 990 | 991 | 992 | 993 | 994 | 995 | 996 | 997 | 998 | 999 | 1000 | 1003 | 1004 | 1005 | 1006 | 1007 | 1008 | 1009 | 1010 | 1011 | 1012 | 1013 | 1014 | 1015 | 1016 | 1017 | 1018 | 1019 | 1020 | 1021 | 1022 | 1023 | 1024 | 1025 | 1026 | 1027 | 1028 | 1029 | 1030 | 1031 | 1032 | 1033 | 1034 | 1035 | 1036 | 1037 | 1038 | 1039 | 1040 | 1041 | 1042 | 1043 | 1044 | 1045 | 1046 | 1047 | 1048 | 1049 | 1050 | 1051 | 1052 | 1053 | 1054 | 1055 | 1056 | 1057 | 1058 | 1059 |
ProblemDifficultySignalStatus
51 | Array / String 52 |
Merge Sorted ArrayEasy🟢
Remove ElementEasy🟢
Remove Duplicates from Sorted ArrayEasy🟢
Remove Duplicates from Sorted Array IIMedium🟡
Majority ElementEasy🟢
Rotate ArrayMedium🟡
Best Time to Buy and Sell StockEasy🟢
Best Time to Buy and Sell Stock IIMedium🟡
Jump GameMedium🟡
Jump Game IIMedium🟡
H-IndexMedium🟡
Insert Delete GetRandom O(1)Medium🟡
Product of Array Except SelfMedium🟡
Gas StationMedium🟡
CandyHard🔴
Trapping Rain WaterHard🔴
Roman to IntegerEasy🟢
Integer to RomanMedium🟡
Length of Last WordEasy🟢
Longest Common PrefixEasy🟢
Reverse Words in a StringMedium🟡
Zigzag ConversionMedium🟡
Find the Index of the First Occurrence in a StringEasy🟢
Text JustificationHard🔴
200 | Two Pointers 201 |
Valid PalindromeEasy🟢
Is SubsequenceEasy🟢
Two Sum II - Input Array Is SortedMedium🟡
Container With Most WaterMedium🟡
3SumMedium🟡
235 | Sliding Window 236 |
Minimum Size Subarray SumMedium🟡
Longest Substring Without Repeating CharactersMedium🟡
Substring with Concatenation of All WordsHard🔴
Minimum Window SubstringHard🔴
264 | Matrix 265 |
Valid SudokuMedium🟡
Spiral MatrixMedium🟡
Rotate ImageMedium🟡
Set Matrix ZeroesMedium🟡
Game of LifeMedium🟡
299 | Hashmap 300 |
Ransom NoteEasy🟢
Isomorphic StringsEasy🟢
Word PatternEasy🟢
Valid AnagramEasy🟢
Group AnagramsMedium🟡
Two SumEasy🟢
Happy NumberEasy🟢
Contains Duplicate IIEasy🟢
Longest Consecutive SequenceMedium🟡
358 | Intervals 359 |
Summary RangesEasy🟢
Merge IntervalsMedium🟡
Insert IntervalMedium🟡
Minimum Number of Arrows to Burst BalloonsMedium🟡
387 | Stack 388 |
Valid ParenthesesEasy🟢
Simplify PathMedium🟡
Min StackMedium🟡
Evaluate Reverse Polish NotationMedium🟡
Basic CalculatorHard🔴
422 | Linked List 423 |
Linked List CycleEasy🟢
Add Two NumbersMedium🟡
Merge Two Sorted ListsEasy🟢
Copy List with Random PointerMedium🟡
Reverse Linked List IIMedium🟡
Reverse Nodes in k-GroupHard🔴
Remove Nth Node From End of ListMedium🟡
Remove Duplicates from Sorted List IIMedium🟡
Rotate ListMedium🟡
Partition ListMedium🟡
LRU CacheMedium🟡
493 | Binary Tree General 494 |
Maximum Depth of Binary TreeEasy🟢
Same TreeEasy🟢
Invert Binary TreeEasy🟢
Symmetric TreeEasy🟢
Construct Binary Tree from Preorder and Inorder TraversalMedium🟡
Construct Binary Tree from Inorder and Postorder TraversalMedium🟡
Populating Next Right Pointers in Each Node IIMedium🟡
Flatten Binary Tree to Linked ListMedium🟡
Path SumEasy🟢
Sum Root to Leaf NumbersMedium🟡
Binary Tree Maximum Path SumHard🔴
Binary Search Tree IteratorMedium🟡
Count Complete Tree NodesEasy🟢
576 | Binary Tree BFS 577 |
Binary Tree Right Side ViewMedium🟡
Average of Levels in Binary TreeEasy🟢
Binary Tree Level Order TraversalMedium🟡
Binary Tree Zigzag Level Order TraversalMedium🟡
605 | Binary Search Tree 606 |
Minimum Absolute Difference in BSTEasy🟢
Kth Smallest Element in a BSTMedium🟡
Validate Binary Search TreeMedium🟡
628 | Graph General 629 |
Number of IslandsMedium🟡
Surrounded RegionsMedium🟡
Clone GraphMedium🟡
Evaluate DivisionMedium🟡
Course ScheduleMedium🟡
Course Schedule IIMedium🟡
669 | Graph BFS 670 |
Snakes and LaddersMedium🟡
Minimum Genetic MutationMedium🟡
Word LadderHard🔴
692 | Trie 693 |
Implement Trie (Prefix Tree)Medium🟡
Design Add and Search Words Data StructureMedium🟡
Word Search IIHard🔴
715 | Backtracking 716 |
Letter Combinations of a Phone NumberMedium🟡
CombinationsMedium🟡
PermutationsMedium🟡
Combination SumMedium🟡
N-Queens IIHard🔴
Generate ParenthesesMedium🟡
Word SearchMedium🟡
762 | Divide & Conquer 763 |
Convert Sorted Array to Binary Search TreeEasy🟢
Sort ListMedium🟡
Construct Quad TreeMedium🟡
Merge k Sorted ListsHard🔴
791 | Kadane's Algorithm 792 |
Maximum SubarrayMedium🟡
Maximum Sum Circular SubarrayMedium🟡
808 | Binary Search 809 |
Search Insert PositionEasy🟢
Search a 2D MatrixMedium🟡
Find Peak ElementMedium🟡
Search in Rotated Sorted ArrayMedium🟡
Find First and Last Position of Element in Sorted ArrayMedium🟡
Find Minimum in Rotated Sorted ArrayMedium🟡
Median of Two Sorted ArraysHard🔴
855 | Heap 856 |
Kth Largest Element in an ArrayMedium🟡
IPOHard🔴
Find K Pairs with Smallest SumsMedium🟡
Find Median from Data StreamHard🔴
884 | Bit Manipulation 885 |
Add BinaryEasy🟢
Reverse BitsEasy🟢
Number of 1 BitsEasy🟢
Single NumberEasy🟢
Single Number IIMedium🟡
Bitwise AND of Numbers RangeMedium🟡
925 | Math 926 |
Palindrome NumberEasy🟢
Plus OneEasy🟢
Factorial Trailing ZeroesMedium🟡
Sqrt(x)Easy🟢
Pow(x, n)Medium🟡
Max Points on a LineHard🔴
966 | 1D DP 967 |
Climbing StairsEasy🟢
House RobberMedium🟡
Word BreakMedium🟡
Coin ChangeMedium🟡
Longest Increasing SubsequenceMedium🟡
1001 | Multidimensional DP 1002 |
TriangleMedium🟡
Minimum Path SumMedium🟡
Unique Paths IIMedium🟡
Longest Palindromic SubstringMedium🟡
Interleaving StringMedium🟡
Edit DistanceMedium🟡
Best Time to Buy and Sell Stock IIIHard🔴
Best Time to Buy and Sell Stock IVHard🔴
Maximal SquareMedium🟡
1060 | --------------------------------------------------------------------------------