├── CPP ├── 2d_matrix_search.cpp ├── 3sum.cpp ├── Add_Two_Numbers.cpp ├── Backspace_string_compare.cpp ├── Baseball-Game.cpp ├── BinaryLevelOrderTraversal-II.cpp ├── BinarySearch.cpp ├── Cherry-Pickup-II.cpp ├── CompareVersion.cpp ├── ComplexNumberMultiplication.cpp ├── Count-Primes.cpp ├── DailyTemperatures.cpp ├── Decode ways.cpp ├── DesignAddandSearchWordsDataStructure.cpp ├── Detect-Capital.cpp ├── Divide_Two_Integers.cpp ├── Factorial Trailing Zeroes.cpp ├── Find First and Last Position of Element in Sorted Array.cpp ├── Find Minimum in Rotated Sorted Array II.cpp ├── HouseRobber2.cpp ├── Implement_strstr.cpp ├── Integer-Break.cpp ├── Intersection_Of_Two_Arrays_II.cpp ├── InvertBinaryTree.cpp ├── Largest_Rectangle_in_Histogram.cpp ├── Longest_Common_Prefix.cpp ├── Longest_Substr_Without_RepeatingCharacters.cpp ├── MaximalSquare.cpp ├── Maximum_Subarray.cpp ├── Min_Cost_Climbing_Stairs.cpp ├── Minimum_Path_sum.cpp ├── Missing Number.cpp ├── Move-Zeroes.cpp ├── NextGreaterElement_I.cpp ├── Number_Of_Dice_Rolls_With_Target_Sum.cpp ├── Number_of_islands.cpp ├── Palindrome.cpp ├── PathSum.cpp ├── Permutation_Sequence.cpp ├── Permutations.cpp ├── PopulatingNextRightPointersInEachNode_II.cpp ├── Regular_Expression_Matching.cpp ├── ReverseInt.cpp ├── Reverse_Node_in_k-group.cpp ├── Roman_to_Integer.cpp ├── RotateImage.cpp ├── Search in Rotated Sorted Array.cpp ├── Search_Insert_Position.cpp ├── Search_an_element_in_a_sorted_and_rotated_Array.cpp ├── Single Number.cpp ├── Sort Colors.cpp ├── Spiral_Matrix.cpp ├── Sudoku Solver.cpp ├── SwapNode.cpp ├── Trapping Rain Water.cpp ├── TwoSum.cpp ├── UglyNumber.cpp ├── Valid_Parentheses.cpp ├── ValidateBinarySearchTree.cpp ├── VerticalOrderTraversal.cpp ├── WildCard_Matching.cpp ├── WordSearch.cpp ├── ZigZag_Level_Order_Traversal.cpp ├── addDigit.cpp ├── addString.cpp ├── asteroid-collision.cpp ├── binarySearch.cpp ├── brick-wall.cpp ├── construct-the-rectangle.cpp ├── container-with-most-water.cpp ├── countAndSay.cpp ├── decode-string.cpp ├── flatten-nested-list-iterator.cpp ├── house robber.cpp ├── insertion_sort.cpp ├── largest_word.cpp ├── letter-combinations-of-a-phone-number.cpp ├── letterCombinationsOfAPhoneNumber.cpp ├── median-of-two-sorted-arrays.cpp ├── multiplystrings.cpp ├── palindrome_check.cpp ├── power of 2.cpp ├── power.cpp ├── remove_nth_node_from_end_of_list.cpp ├── rotateArray.cpp ├── searchA2dMatrix.cpp ├── sqrt_number.cpp ├── sqrt_number_2.cpp ├── subsets.cpp └── zigzag.cpp ├── Golang ├── DistinctSubsequences.go ├── EditDistance.go ├── FirstMissingPositive.go ├── add-two-numbers.go ├── longest_substring_without_repeating_characters.go ├── min_ticket.go ├── palindrome_number.go ├── reverse_integer.go ├── two-sum.go └── valid_parenthesis.go ├── Java ├── 4sum.java ├── Add_Two_Numbers.java ├── BestTimeToBuyAndSellStock.java ├── BitwiseXOROfAllPairings.java ├── DecodeWays.java ├── Divide_Two_Integers.java ├── EvenNumberofDigits.java ├── Find-Right-Interval.java ├── FindLargestValueInEachTreeRow.java ├── FizzBuzz.java ├── HappyNumber.java ├── IntegerToRoman.java ├── IslandPerimeter.java ├── IsomorphicStrings.java ├── JumpGame.java ├── LongestCommonSubsequence.java ├── LongestUploadedPrefix.java ├── Longest_Common_Prefix.java ├── Longest_Substring_Without_Repeating_Characters.java ├── Maximum_Product.java ├── MinPathSum.java ├── NumberOfPairsSatisfyingInequality.java ├── PartitionToKEqualSumSubsets.java ├── Pascals.java ├── PopulatingNextRightPointersInEachNode.java ├── PrefixSuffixSearch.java ├── RectangleOverlap.java ├── RegularExpressionMatching.java ├── RemoveLetterToEqualizeFrequency.java ├── ReverseInteger ├── RomanToInteger.java ├── RotateImage.java ├── RunningSum1DArray.java ├── SortArrayByParityii.java ├── SplitLinkedListInParts.java ├── String_to_Integer_(atoi).java ├── Two Sum.java ├── Ugly-Number.java ├── UniqueEmailAddresses.java ├── ValidAnagram.java ├── WaterAndJugProblem.java ├── ZigzagConversion.java ├── findallduplicatesinanarray.java ├── median_sorted.java ├── mergingTwoTrees.java ├── peakIndexInAMountainArray.java ├── remove-element.java ├── reverseWords.java ├── reverse_integer.java └── word-ladder.java ├── JavaScript ├── 3Sum.js ├── FunctionComposite.js ├── MergeTwoSortedLists.js ├── RemoveElement.js ├── ValidParentheses.js ├── ValidSudoku.js ├── array-prototype-last.js ├── counter.js ├── divTwoInt.js ├── palindrome-number.js ├── reverse-integer.js ├── sleep.js ├── two-sum.js └── valid-parentheses.js ├── Kotlin ├── 10. Regular Expression Matching.kt ├── 22. Generate Parentheses.kt ├── 32. Longest Valid Parentheses.kt ├── 4. Median of Two Sorted Arrays.kt ├── reverse-integer.kt └── two-sum.kt ├── Mysql ├── Combine Two Tables ├── Customers Who Never Order ├── Employees Earning More Than Their Managers ├── Second Highest Salary ├── classes-more-than-5-students ├── consecutive-numbers ├── department-highest-salary ├── department-top-three-salaries ├── duplicate emails ├── duplicate-emails ├── human-traffic-of-stadium ├── nth-highest-salary ├── rank-scores ├── rising-temperature ├── swap-salary └── trips-and-users ├── Python ├── 3SumClosest.py ├── AddTwoNumbers.py ├── Binary_Search_Tree_Traversals.py ├── BreakAPalindrome.py ├── ContinuousSubarraySum.py ├── DecodeWays.py ├── EarliestPossibleDayOfBloom.py ├── GenParentheses.py ├── Group_Anagrams.py ├── ImageOverlap.py ├── IntegerReplacement.py ├── LongestSubstring.py ├── MaximumPopulationYear.py ├── MedianTwoSortedArrays.py ├── MergeTwoListed.py ├── RegularExpressionMatching.py ├── RemoveDupFromSortedArray.py ├── ReplaceAllDigitsWithCharacters.py ├── ReverseInteger.py ├── RomanToInteger.py ├── Rotate_Image.py ├── SetMismatch.py ├── ShortestPathInGridWithElim.py ├── SingleNumber.py ├── SortingTheSentence.py ├── String2Integer.py ├── SumofDigitsInBaseK.py ├── Trapping_Rain_Water.py ├── TwoSum.py ├── TwoSums.py ├── UniqueEmailAddress ├── ZigZagConversion.py ├── ZigzagConversion.py ├── add-binary.py ├── baseball-game.py ├── count-and-say.py ├── fibonacci-number.py ├── find-the-difference.py ├── firstMissingPositive.py ├── integer-to-english-words.py ├── integer-to-roman.py ├── intersectionofTwoLinkedLists.py ├── jump-game-II.py ├── length-of-last-word.py ├── linkedListCycle.py ├── loud-and-rich.py ├── min-cost-climbing-stairs.py ├── move_zeroes.py ├── multiply_strings.py ├── palindrome-number.py ├── powx-n.py ├── removeLinkedListElements.py ├── remove_duplicate.py ├── remove_element.py ├── reverseLinkedList.py ├── search_insert_position.py ├── strStr_Impl.py ├── valid-parentheses.py └── wildcard-matching.py ├── README.md ├── Rust ├── best-time-to-buy-and-sell-stock.rs ├── contains_duplicate.rs ├── decode_ways.rs ├── find_the_difference.rs ├── fizz_buzz.rs ├── group_anagrams.rs ├── int_to_roman.rs ├── letter_combinations_for_phone_number.rs ├── palindrome.rs ├── power_of_four.rs ├── reverse-integer.rs ├── three_sum.rs ├── three_sum_closest.rs ├── two-sum.rs └── zigzag-conversion.rs └── java └── valid-sudoku.java /CPP/2d_matrix_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | int main() 7 | { 8 | int n,m; 9 | cout<<"Enter the size of the matrix"<>n>>m; 11 | int array[n][m]; 12 | 13 | for (int i = 0; i < n; i++) 14 | { 15 | for (int j = 0; j >array[i][j]; 18 | } 19 | } 20 | int key; 21 | cout<<"Enter the element to be searched"<>key; 23 | 24 | for (int i = 0; i < n; i++) 25 | { 26 | for (int j = 0; j > threeSum(vector& nums) { 4 | 5 | vector> v; 6 | sort(nums.begin(),nums.end()); 7 | 8 | if(nums.size()==0 || nums.size()==1 || nums.size()==2) return v; 9 | 10 | int i=0; 11 | 12 | for(i;i0 && nums[i]==nums[i-1]) continue; 15 | 16 | int k=nums.size()-1,j=i+1; 17 | 18 | while(j0){ 28 | k--; 29 | }else{ 30 | j++; 31 | } 32 | } 33 | } 34 | return v; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /CPP/Add_Two_Numbers.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 14 | ListNode *head = new ListNode(0); 15 | ListNode *p = l1, *q = l2, *curr = head; 16 | int carry = 0; 17 | while (p != NULL || q != NULL) { 18 | int x = (p != NULL) ? p->val : 0; 19 | int y = (q != NULL) ? q->val : 0; 20 | int sum = carry + x + y; 21 | carry = sum / 10; 22 | curr->next = new ListNode(sum % 10); 23 | curr = curr->next; 24 | if (p != NULL) p = p->next; 25 | if (q != NULL) q = q->next; 26 | } 27 | if (carry > 0) { 28 | curr->next = new ListNode(carry); 29 | } 30 | return head->next; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /CPP/Backspace_string_compare.cpp: -------------------------------------------------------------------------------- 1 | //Leetcode 844 Solution in O(n) time and O(1) space 2 | 3 | bool backspaceCompare(string S, string T) { 4 | int i = S.length() - 1, j = T.length() - 1, back; 5 | while (true) { 6 | back = 0; 7 | while (i >= 0 && (back > 0 || S[i] == '#')) { 8 | back += S[i] == '#' ? 1 : -1; 9 | i--; 10 | } 11 | back = 0; 12 | while (j >= 0 && (back > 0 || T[j] == '#')) { 13 | back += T[j] == '#' ? 1 : -1; 14 | j--; 15 | } 16 | if (i >= 0 && j >= 0 && S[i] == T[j]) { 17 | i--; 18 | j--; 19 | } else { 20 | break; 21 | } 22 | } 23 | return i == -1 && j == -1; 24 | } -------------------------------------------------------------------------------- /CPP/Baseball-Game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int calPoints(vector& ops) { 4 | stack s; 5 | auto it=ops.begin(); 6 | while(it!=ops.end()){ 7 | if(*it=="+"){ //if char is + then new record is sum of last two records 8 | int val1=s.top(); 9 | s.pop(); 10 | int val2=s.top(); 11 | s.push(val1); 12 | s.push(val1+val2); 13 | } 14 | else if(*it=="D"){ //if char is D then new record is twice the last record 15 | s.push(2*s.top()); 16 | } 17 | else if(*it=="C"){ //if char is C then the last record is invalidated , hence popped 18 | s.pop(); 19 | } 20 | else{ // if none of these conditions occur then just push the new record to stack 21 | s.push(stoi(*it)); 22 | } 23 | it++; 24 | } 25 | int count=0; 26 | while(!s.empty()) //iteratively pop the top value of the stack and add it to the total 27 | { 28 | count+=s.top(); 29 | s.pop(); 30 | } 31 | return count; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /CPP/BinaryLevelOrderTraversal-II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> levelOrderBottom(TreeNode* root) { 4 | queue q; 5 | vector> v; 6 | if(root==NULL){ 7 | return v; 8 | } 9 | q.emplace(root); 10 | while(!q.empty()){ 11 | int n=q.size(); 12 | vector v1; 13 | for(int i=0;ival); 17 | if(cur->left) q.push(cur->left); 18 | if(cur->right) q.push(cur->right); 19 | q.pop(); 20 | } 21 | v.push_back(v1); 22 | } 23 | reverse(v.begin(),v.end()); 24 | return v; 25 | } 26 | }; -------------------------------------------------------------------------------- /CPP/BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | //Problem Statement: Binary Search 2 | 3 | // Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. 4 | 5 | 6 | //Solution: 7 | class Solution { 8 | public: 9 | int search(vector& nums, int target) { 10 | 11 | int si=0, ei=nums.size()-1; 12 | 13 | while(si <= ei) { 14 | // index of the middle element 15 | int mid = si + (ei-si)/2; 16 | 17 | // found target element 18 | if(nums[mid] == target) { 19 | return mid; 20 | } else if(nums[mid] < target) { // target on right side of middle element 21 | si += 1; 22 | } else { // target on left side of middle element 23 | ei -= 1; 24 | } 25 | } 26 | 27 | // target element not present in given array 28 | return -1; 29 | } 30 | }; 31 | 32 | // Time Complexity: O(log(n)) 33 | -------------------------------------------------------------------------------- /CPP/Cherry-Pickup-II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | // Let's run a simple dfs. If we come to the same cell with two robots, let's subtract that value. 4 | int dfs(int n, int m, int r, int c1, int c2, unordered_map>, int> &dp, vector> &grid) { 5 | if (c1 < 0 || c1 >= m || c2 < 0 || c2 >= m) { 6 | return 0; 7 | } else if (r == n) { 8 | return 0; 9 | } else if (dp.count({r, {c1, c2}}) > 0) { 10 | return dp[{r, {c1, c2}}]; 11 | } else { 12 | int current_ceil = grid[r][c1] + grid[r][c2]; 13 | 14 | // Here is that subtraction 15 | if (c1 == c2) { 16 | current_ceil -= grid[r][c2]; 17 | } 18 | 19 | // Running dfs from all possible cells 20 | int mx = 0; 21 | for (int i = -1; i <= 1; ++i) { 22 | for (int j = -1; j <= 1; ++j) { 23 | mx = max(mx, dfs(n, m, r + 1, c1 + i, c2 + j, dp, grid)); 24 | } 25 | } 26 | 27 | return dp[{r, {c1, c2}}] = current_ceil + mx; 28 | } 29 | } 30 | public: 31 | int cherryPickup(vector>& grid) { 32 | unordered_map>, int> dp; 33 | 34 | int n = grid.size(); 35 | int m = grid[0].size(); 36 | 37 | return dfs(n, m, 0, 0, m - 1, dp, grid); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /CPP/CompareVersion.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int compareVersion(string version1, string version2) { 4 | vector v1, v2; 5 | string s = ""; 6 | for(char x: version1) { 7 | if(x == '.') { 8 | v1.push_back(stol(s)); 9 | s = ""; 10 | } else { 11 | s += x; 12 | } 13 | } 14 | v1.push_back(stol(s)); 15 | s = ""; 16 | for(char x: version2) { 17 | if(x == '.') { 18 | v2.push_back(stol(s)); 19 | s = ""; 20 | } else { 21 | s += x; 22 | } 23 | } 24 | v2.push_back(stol(s)); 25 | int i=0; 26 | while(iv2[i]) { 28 | return 1; 29 | } else if(v1[i] < v2[i]) { 30 | return -1; 31 | } 32 | i++; 33 | } 34 | while(i < v1.size()) { 35 | if(v1[i] != 0) { 36 | return 1; 37 | } 38 | i++; 39 | } 40 | while(i < v2.size()) { 41 | if(v2[i] != 0) { 42 | return -1; 43 | } 44 | i++; 45 | } 46 | return 0; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /CPP/ComplexNumberMultiplication.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/complex-number-multiplication/ 2 | class Solution { 3 | public: 4 | int realpart(string str){ 5 | int i = 0 ; 6 | string realpart = "" ; 7 | 8 | while(str[i]!='+'){ 9 | realpart += str[i] ; 10 | i++ ; 11 | } 12 | return stoi(realpart) ; 13 | } 14 | 15 | int complex(string str){ 16 | int i = 0 ; 17 | string complex = "" ; 18 | 19 | while(str[i]!='+'){ 20 | i++ ; 21 | } 22 | 23 | i++ ; 24 | 25 | while(str[i]!='i'){ 26 | complex += str[i] ; 27 | i++ ; 28 | } 29 | 30 | return stoi(complex) ; 31 | } 32 | 33 | string complexNumberMultiply(string a, string b) { 34 | string result = "" ; 35 | int a1 = realpart(a) ; 36 | int a2 = realpart(b) ; 37 | int b1 = complex(a) ; 38 | int b2 = complex(b) ; 39 | 40 | result = result + to_string(a1*a2-b1*b2)+'+'+to_string(a1*b2+a2*b1)+'i' ; 41 | 42 | return result ; 43 | } 44 | }; -------------------------------------------------------------------------------- /CPP/Count-Primes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int countPrimes(int n) { 5 | 6 | vector arr(n+1,0); 7 | arr[0]=true; 8 | arr[1]=true; 9 | for(int i=2;i*i<=n;i++){ 10 | if(arr[i]==false){ 11 | for(int j = i*i;j<=n;j+=i){ 12 | arr[j]=true; 13 | } 14 | } 15 | } 16 | 17 | int count = 0; 18 | for(int i=2;i dailyTemperatures(vector& temperatures) { 28 | vector ans(temperatures.size()); 29 | stack s; 30 | 31 | for(int i=0; i temperatures[s.top()]){ 33 | const int k = s.top(); 34 | s.pop(); 35 | ans[k] = i - k; 36 | } 37 | s.push(i); 38 | } 39 | return ans; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /CPP/Decode ways.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numDecodings(string s) { 4 | int n=s.size(); 5 | int dp[n][2]; 6 | 7 | if(s[0]=='0') 8 | return 0; 9 | 10 | dp[0][0]=1;dp[0][1]=0; 11 | 12 | for(int i=1;i children; 5 | 6 | TrieNode() { 7 | isWord = false; 8 | } 9 | }; 10 | 11 | class WordDictionary { 12 | TrieNode *root; 13 | 14 | void addWordToTrie(string word) { 15 | auto cur = root; 16 | 17 | for (auto ch : word) { 18 | if (!cur->children.count(ch)) 19 | cur->children[ch] = new TrieNode(); 20 | 21 | cur = cur->children[ch]; 22 | } 23 | 24 | cur->isWord = true; 25 | } 26 | 27 | bool searchTrie(TrieNode* cur, int i, string word) { 28 | if (i == word.length()) 29 | return cur->isWord; 30 | 31 | if (word[i] != '.') { 32 | // normal letter 33 | if (!cur->children.count(word[i])) 34 | return false; 35 | 36 | return searchTrie(cur->children[word[i]], i + 1, word); 37 | } 38 | 39 | // '.' encountered. Perform DFS in all children branches 40 | for (auto it : cur->children) { 41 | if (searchTrie(it.second, i + 1, word)) 42 | return true; 43 | } 44 | 45 | return false; 46 | } 47 | 48 | public: 49 | /** Initialize your data structure here. */ 50 | WordDictionary() { 51 | root = new TrieNode(); 52 | } 53 | 54 | /** Adds a word into the data structure. */ 55 | void addWord(string word) { 56 | addWordToTrie(word); 57 | } 58 | 59 | /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ 60 | bool search(string word) { 61 | return searchTrie(root, 0, word); 62 | } 63 | }; -------------------------------------------------------------------------------- /CPP/Detect-Capital.cpp: -------------------------------------------------------------------------------- 1 | // Problem URL: https://leetcode.com/problems/single-number-iii/ 2 | /* 3 | * Runtime - 0ms 4 | * Memory - 5.9mb 5 | */ 6 | 7 | class Solution { 8 | public: 9 | bool detectCapitalUse(string word) { 10 | bool all_caps = 1; 11 | bool all_small = 1; 12 | bool first_letter_caps = isupper(word[0]); 13 | 14 | for(int i=1; i0) 10 | { 11 | i += n/5; 12 | n /=5; 13 | } 14 | return i; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /CPP/Find First and Last Position of Element in Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& a, int target) { 4 | int s = 0, e = a.size()-1; 5 | vector ans(2, -1); 6 | 7 | while(s <= e){ 8 | int m = s + (e-s)/2; 9 | if(a[m] < target) 10 | s = m+1; 11 | else if(a[m] > target) 12 | e = m-1; 13 | else{ 14 | if(m == s || a[m] != a[m-1]){ 15 | ans[0] = m; 16 | break; 17 | } 18 | else{ 19 | e = m-1; 20 | ans[0] = m-1; 21 | } 22 | } 23 | } 24 | 25 | s = 0, e = a.size()-1; 26 | while(s <= e){ 27 | int m = s + (e-s)/2; 28 | if(a[m] < target) 29 | s = m+1; 30 | else if(a[m] > target) 31 | e = m-1; 32 | else{ 33 | if(m == e || a[m] != a[m+1]){ 34 | ans[1] = m; 35 | break; 36 | } 37 | else{ 38 | s = m+1; 39 | ans[1] = m+1; 40 | } 41 | } 42 | } 43 | return ans; 44 | } 45 | }; -------------------------------------------------------------------------------- /CPP/Find Minimum in Rotated Sorted Array II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int low=0, high=nums.size()-1; 5 | if(nums[low] nums[high]) 10 | low=mid+1; 11 | else if(nums[mid] < nums[high]) 12 | high=mid; 13 | else 14 | high--; 15 | } 16 | return nums[low]; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /CPP/HouseRobber2.cpp: -------------------------------------------------------------------------------- 1 | // Leetcode Problem : 213 House Robber II 2 | // Link : (https://leetcode.com/problems/house-robber-ii/) 3 | 4 | #include 5 | using namespace std; 6 | class Solution 7 | { 8 | public: 9 | int rob(vector &nums) 10 | { 11 | // if there are no houses we can't rob any money 12 | if (nums.size() == 0) 13 | return 0; 14 | // if there is only one house we rob only that 15 | if (nums.size() == 1) 16 | return nums[0]; 17 | // if there are only 2 house we rob the one that has maximum cash 18 | if (nums.size() == 2) 19 | return max(nums[0], nums[1]); 20 | 21 | // else we use dp approach 22 | vector dp(nums.size()); 23 | vector dp2(nums.size()); 24 | dp[0] = nums[0]; 25 | dp[1] = nums[0]; 26 | 27 | dp2[0] = 0; 28 | dp2[1] = nums[1]; 29 | for (int i = 2; i < nums.size(); i++) 30 | { 31 | dp[i] = max(nums[i] + dp[i - 2], dp[i - 1]); 32 | dp2[i] = max(nums[i] + dp2[i - 2], dp2[i - 1]); 33 | } 34 | 35 | return max(dp[nums.size() - 2], dp2[nums.size() - 1]); 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /CPP/Implement_strstr.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int strStr(string haystack, string needle) { 4 | string subhaystack; 5 | char tmp; 6 | int result; 7 | if(needle.length()==0) 8 | return 0; 9 | for(int i=0;i=needle.length()) 13 | { 14 | if(memcmp(&haystack[i], &needle[0], needle.length()) == 0) 15 | return i; 16 | } 17 | } 18 | return -1; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /CPP/Integer-Break.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int integerBreak(int n) { 5 | 6 | // when n = 0,1 no possible cuts hence store 0 7 | int val[n + 1]; 8 | val[0] = val[1] = 0; 9 | 10 | // calculate for all possible cuts possible from 1 to n 11 | for (int i = 1; i <= n; i++) { 12 | int max_value = INT_MIN; 13 | 14 | /*for n = 6 calculate for all possible cuts like maximum of 15 | {(1,5),(5,1)}, {(4,2),(2,4)},{ (3,3) } 16 | */ 17 | for (int j = 1; j <= i / 2; j++) { 18 | max_value = max(max_value, max((i - j) * j, j * val[i - j])); 19 | } 20 | 21 | val[i] = max_value; 22 | } 23 | 24 | return val[n]; 25 | 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /CPP/Intersection_Of_Two_Arrays_II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector intersect(vector& nums1, vector& nums2) { 4 | int i=0; 5 | vector m; 6 | for(auto val : nums1){ 7 | auto it = find(nums2.begin(),nums2.end(),val); 8 | if(it!=nums2.end()) 9 | { 10 | m.push_back(*it); 11 | nums2.erase(it); 12 | } 13 | } 14 | return m; 15 | } 16 | 17 | }; 18 | -------------------------------------------------------------------------------- /CPP/InvertBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* invertTree(TreeNode* root) { 4 | if (root == NULL) return root; 5 | swap(root->left, root->right); 6 | invertTree(root->left); 7 | invertTree(root->right); 8 | return root; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /CPP/Largest_Rectangle_in_Histogram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestRectangleArea(vector& heights) { 4 | int n = heights.size(); 5 | int l[n]; 6 | stack s; 7 | for(int i=0;i= heights[i]) s.pop(); 9 | if(s.size()) l[i]=s.top(); 10 | else l[i]=-1; 11 | s.push(i); 12 | } 13 | int ans = 0; 14 | while(s.size()) s.pop(); 15 | for(int i=n-1;i>=0;i--) { 16 | while(s.size() and heights[s.top()] >= heights[i]) s.pop(); 17 | int r; 18 | if(s.size()) r = s.top(); 19 | else r = n; 20 | s.push(i); 21 | ans = max(ans, (r-l[i]-1)*heights[i]); 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /CPP/Longest_Common_Prefix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestCommonPrefix(vector& strs) { 4 | if(strs.size()==0) 5 | { 6 | return""; 7 | } 8 | string ans=""; 9 | for(int i=0; i map(256,-1); 5 | 6 | int left = 0 , right = 0; 7 | int n = s.size(); 8 | 9 | int len = 0; 10 | while(right>& matrix) { 4 | 5 | int m =matrix.size(); 6 | int n= matrix[0].size(); 7 | int dp[m][n]; 8 | 9 | int ans = -1 ; 10 | 11 | for(int j = n- 1 ; j >= 0 ; j--) 12 | { 13 | for(int i = m-1 ; i >= 0 ; i--) 14 | { 15 | 16 | 17 | if( i == m - 1) 18 | { 19 | dp[i][j] = matrix[i][j] - '0'; 20 | } 21 | 22 | else if(j == n -1 ) 23 | { 24 | 25 | dp[i][j] = matrix[i][j] - '0'; 26 | } 27 | 28 | else 29 | { 30 | 31 | if(matrix[i][j] == '0' ) 32 | dp[i][j] = 0; 33 | 34 | else 35 | { 36 | dp[i][j] = 1 + min(dp[i][j+1],min(dp[i+1][j],dp[i+1][j+1])); 37 | } 38 | 39 | 40 | } 41 | 42 | 43 | ans = max(ans ,dp[i][j]); 44 | } 45 | 46 | 47 | } 48 | 49 | 50 | return ans * ans ; 51 | 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /CPP/Maximum_Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubArray(vector& nums) { 4 | int currSum = 0, maxSubSum = nums[0]; 5 | for(int i=0;i& cost) { 4 | 5 | int dptable[cost.size()]; 6 | 7 | dptable[0] = cost[0]; 8 | dptable[1] = cost[1]; 9 | 10 | for(int i=2;i>& matrix) { 6 | int m=matrix.size(); 7 | int n = matrix[0].size(); 8 | vector> dp(m); 9 | for(int i=0; i(n); 11 | 12 | for(int i=m-1; i>=0; i--) 13 | { 14 | for(int j=n-1; j>=0; j--) 15 | { 16 | if(i==m-1 && j==n-1) 17 | dp[i][j] = matrix[i][j]; 18 | else if(i==m-1) 19 | dp[i][j] = dp[i][j+1] + matrix[i][j]; 20 | else if(j==n-1) 21 | dp[i][j] = dp[i+1][j] + matrix[i][j]; 22 | else 23 | { 24 | int minimum = min(dp[i+1][j], dp[i][j+1]); 25 | dp[i][j] = minimum + matrix[i][j]; 26 | } 27 | } 28 | } 29 | return dp[0][0]; 30 | } 31 | }; -------------------------------------------------------------------------------- /CPP/Missing Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | unordered_set s(nums.begin(), nums.end()); 5 | for(int i=0; i<=nums.size(); i++) { 6 | if(s.find(i) == s.end()) 7 | return i; 8 | } 9 | return -1; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /CPP/Move-Zeroes.cpp: -------------------------------------------------------------------------------- 1 | //Problem Statement: Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 2 | 3 | //Solution: 4 | class Solution { 5 | public: 6 | void moveZeroes(vector& nums) { 7 | int i = 0; 8 | for (int j = 0; j < nums.size(); j++) { 9 | // Bring all non zero numbers to the start of the array 10 | if (nums[j] != 0) { 11 | nums[i++] = nums[j]; 12 | } 13 | } 14 | 15 | while(i nextGreaterElement(vector& nums1, vector& nums2) { 4 | stack stax; 5 | unordered_map hax; 6 | int len = nums2.size() - 1; 7 | for (len; len >= 0; len--) { 8 | int cur = nums2[len]; 9 | while (!stax.empty() && stax.top() < cur) stax.pop(); 10 | hax[cur] = stax.empty() ? -1: stax.top(); 11 | stax.push(cur); 12 | } 13 | vector res; 14 | for (int i: nums1) { 15 | res.push_back(hax[i]); 16 | } 17 | return res; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /CPP/Number_Of_Dice_Rolls_With_Target_Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | const unsigned int M=1000000007; 4 | public: 5 | int numRollsToTarget(int d, int f, int target) { 6 | vector> dp(d+1,vector(target+1,0)); 7 | for(int j=1;j<=f&&j<=target;j++) 8 | dp[1][j]=1; 9 | for(int i=2;i<=d;i++) 10 | for(int j=1;j<=target;j++) 11 | for(int k=1;k<=f&&k=0&&a=0&&b>& grid, vector>& used,int a,int b,int n,int m){ 9 | 10 | used[a][b] = true; 11 | 12 | int d[4][2] = {{-1,0},{0,-1},{0,1},{1,0}}; 13 | 14 | for(int i=0;i<4;i++){ 15 | int newa = a+d[i][0]; 16 | int newb = b+d[i][1]; 17 | 18 | if(valid(newa,newb,n,m) && !used[newa][newb] && grid[newa][newb]=='1') 19 | dfs(grid,used,newa,newb,n,m); 20 | } 21 | 22 | return; 23 | } 24 | 25 | int numIslands(vector>& grid) { 26 | 27 | int n = grid.size(); 28 | int m = grid[0].size(); 29 | 30 | vector> used(n,vector(m,false)); 31 | 32 | int k=0; 33 | for(int i=0;i INT_MAX/10 || (rev == INT_MAX / 10 && tmp > 7)) return 0; 11 | if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && tmp < -8)) return 0; 12 | rev=(rev*10)+tmp; 13 | } 14 | return rev; 15 | } 16 | 17 | bool isPalindrome(int x) { 18 | if(x<0) 19 | return false; 20 | int rev = reverse(x); 21 | return x==rev?true:false; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /CPP/PathSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasPathSum(TreeNode* root, int sum) { 4 | if(root == NULL){ 5 | return false; 6 | } 7 | if(root->left == NULL && root->right == NULL){ 8 | if(sum == root->val){ 9 | return true; 10 | } 11 | return false; 12 | } 13 | 14 | return hasPathSum(root->left,sum-root->val) || 15 | hasPathSum(root->right,sum-root->val) ; 16 | } 17 | }; -------------------------------------------------------------------------------- /CPP/Permutation_Sequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Problem - Permutation Sequence 4 | Link - https://leetcode.com/problems/permutation-sequence/ 5 | Difficulty - Hard 6 | 7 | */ 8 | 9 | class Solution { 10 | public: 11 | string getPermutation(int n, int k) { 12 | // We need to move k-1 positions ahead since we are on 1st position 13 | k--; 14 | 15 | // 1st Sequence 16 | vector v; 17 | for(int i=1;i<=n;i++) { 18 | v.push_back(i); 19 | } 20 | 21 | // Factorials 22 | int fact[n+1]; 23 | fact[0]=1; 24 | for(int i=1;i<=n;i++) { 25 | fact[i] = fact[i-1]*i; 26 | } 27 | 28 | // Calculating Sequence 29 | for(int i=0;i> &result,vector &res,vector num,vector &used,int n){ 2 | 3 | if(n==0){ 4 | result.push_back(res); 5 | return; 6 | } 7 | for(int i=0;i> permute(vector& nums) { 21 | if(nums.size()<=0) return vector>(); 22 | sort(nums.begin(),nums.end()); 23 | vector> result; 24 | vectorres; 25 | vector used(nums.size(),false); 26 | dfs(result,res,nums,used,nums.size()); 27 | return result; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /CPP/PopulatingNextRightPointersInEachNode_II.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | Node* connect(Node* root) { 4 | queue q; 5 | if (root) { 6 | q.push(NULL); 7 | q.push(root); 8 | } 9 | while (q.size() > 1) { 10 | int len = q.size(); 11 | Node* it = NULL; 12 | while (len--) { 13 | Node* n = q.front(); 14 | if (n) { 15 | if (n->right) q.push(n->right); 16 | if (n->left) q.push(n->left); 17 | n->next = it; 18 | it = n; 19 | } else { 20 | q.push(n); 21 | } 22 | q.pop(); 23 | } 24 | } 25 | return root; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /CPP/Regular_Expression_Matching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMatch(string s, string p) { 4 | int n=s.size(), m=p.size(); 5 | vector> dp(n+1,vector(m+1,0)); 6 | dp[0][0]=true; 7 | for(int i=1;i<=n;i++) 8 | dp[i][0]=false; 9 | for(int j=1;j<=m;j++) 10 | { 11 | if(p[j-1]=='*') dp[0][j]=dp[0][j-2]; 12 | else dp[0][j]=0; 13 | } 14 | for(int i=1;i<=n;i++) 15 | { 16 | for(int j=1;j<=m;j++) 17 | { 18 | if(s[i-1]==p[j-1] || p[j-1]=='.') dp[i][j] = dp[i-1][j-1]; 19 | else if(p[j-1]=='*') 20 | { 21 | dp[i][j] = dp[i][j-2]; 22 | if(p[j-2]=='.' || p[j-2]==s[i-1]) 23 | dp[i][j] = dp[i][j]||dp[i-1][j]; 24 | } 25 | else dp[i][j]=0; 26 | } 27 | } 28 | return dp[n][m]; 29 | } 30 | }; -------------------------------------------------------------------------------- /CPP/ReverseInt.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | int rev=0,tmp=0; 5 | while(x!=0) 6 | { 7 | tmp=x%10; 8 | x=x/10; 9 | /*overflow check*/ 10 | if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && tmp > 7)) return 0; 11 | if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && tmp < -8)) return 0; 12 | rev=(rev*10)+tmp; 13 | } 14 | return rev; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /CPP/Reverse_Node_in_k-group.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseKGroup(ListNode* head, int k) { 14 | if(k==1) return head; 15 | ListNode dummy; 16 | ListNode *d_head = &dummy, *d_tail = &dummy; 17 | ListNode *head_copy = head; 18 | int n=0; 19 | while(head_copy) 20 | { 21 | head_copy = head_copy->next; 22 | n++; 23 | } 24 | int x = n/k; 25 | head_copy = head; 26 | int i=0,j=0; 27 | while(head_copy) 28 | { 29 | i++; 30 | if(i%k != 1) 31 | { 32 | ListNode* temp=head_copy->next; 33 | head_copy->next = d_head->next; 34 | d_head->next = head_copy; 35 | head_copy = temp; 36 | } 37 | else 38 | { 39 | ListNode* temp = head_copy->next; 40 | d_head = d_tail; 41 | d_head->next = head_copy; 42 | d_tail = head_copy; 43 | head_copy=temp; 44 | j++; 45 | } 46 | if(j==x+1) break; 47 | } 48 | d_tail->next = head_copy; 49 | return dummy.next; 50 | } 51 | }; -------------------------------------------------------------------------------- /CPP/Roman_to_Integer.cpp: -------------------------------------------------------------------------------- 1 | int value(char r) 2 | { 3 | if (r == 'I') 4 | return 1; 5 | if (r == 'V') 6 | return 5; 7 | if (r == 'X') 8 | return 10; 9 | if (r == 'L') 10 | return 50; 11 | if (r == 'C') 12 | return 100; 13 | if (r == 'D') 14 | return 500; 15 | if (r == 'M') 16 | return 1000; 17 | 18 | return -1; 19 | } 20 | class Solution { 21 | public: 22 | 23 | int romanToInt(string str) { 24 | int res = 0; 25 | 26 | for (int i = 0; i < str.length(); i++) { 27 | int s1 = value(str[i]); 28 | 29 | if (i + 1 < str.length()) { 30 | int s2 = value(str[i + 1]); 31 | if (s1 >= s2) { 32 | res = res + s1; 33 | } 34 | else { 35 | res = res + s2 - s1; 36 | i++; 37 | } 38 | } 39 | else { 40 | res = res + s1; 41 | } 42 | } 43 | return res; 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /CPP/RotateImage.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Rotate Image 3 | https://leetcode.com/problems/rotate-image/ 4 | */ 5 | 6 | class Solution { 7 | public: 8 | void transpose(vector>& matrix) { 9 | for(int i = 0; i < matrix.size(); i++) { 10 | for(int j = 0; j < i; j++) { 11 | int temp = matrix[i][j]; 12 | matrix[i][j] = matrix[j][i]; 13 | matrix[j][i] = temp; 14 | } 15 | } 16 | } 17 | void rotate(vector>& matrix) { 18 | transpose(matrix); 19 | for(int i = 0; i < matrix.size(); i++) 20 | reverse(matrix[i].begin(), matrix[i].end()); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /CPP/Search in Rotated Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int x) { 4 | int low=0, high=nums.size()-1; 5 | while(low<=high) { 6 | int mid=low+(high-low)/2; 7 | if(nums[mid]==x) 8 | return mid; 9 | if(nums[low]<=nums[mid]) { 10 | if(x>=nums[low] && x<=nums[mid]) 11 | high=mid-1; 12 | else 13 | low=mid+1; 14 | } 15 | else { 16 | if(x>nums[mid] && x<=nums[high]) 17 | low=mid+1; 18 | else 19 | high=mid-1; 20 | } 21 | } 22 | return -1; 23 | } 24 | }; -------------------------------------------------------------------------------- /CPP/Search_Insert_Position.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | int i=0; 5 | int j=nums.size()-1; 6 | 7 | while(i<=j){ 8 | int mid = (i+j)/2; 9 | 10 | if(target > nums[mid]){ 11 | i=mid+1; 12 | }else if(target < nums[mid]){ 13 | j=mid-1; 14 | }else{ 15 | return mid; 16 | } 17 | } 18 | 19 | return i; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /CPP/Search_an_element_in_a_sorted_and_rotated_Array.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program to search an element 2 | // in a sorted and pivoted array 3 | 4 | #include 5 | using namespace std; 6 | 7 | // Standard Binary Search function 8 | int binarySearch(int arr[], int low, int high, int key) 9 | { 10 | if (high < low) 11 | return -1; 12 | 13 | int mid = (low + high) / 2; 14 | if (key == arr[mid]) 15 | return mid; 16 | 17 | if (key > arr[mid]) 18 | return binarySearch(arr, (mid + 1), high, key); 19 | 20 | return binarySearch(arr, low, (mid - 1), key); 21 | } 22 | 23 | // Function to get pivot. For array 3, 4, 5, 6, 1, 2 24 | // it returns 3 (index of 6) 25 | int findPivot(int arr[], int low, int high) 26 | { 27 | // Base cases 28 | if (high < low) 29 | return -1; 30 | if (high == low) 31 | return low; 32 | 33 | // low + (high - low)/2; 34 | int mid = (low + high) / 2; 35 | if (mid < high && arr[mid] > arr[mid + 1]) 36 | return mid; 37 | 38 | if (mid > low && arr[mid] < arr[mid - 1]) 39 | return (mid - 1); 40 | 41 | if (arr[low] >= arr[mid]) 42 | return findPivot(arr, low, mid - 1); 43 | 44 | return findPivot(arr, mid + 1, high); 45 | } 46 | 47 | // Searches an element key in a pivoted 48 | // sorted array arr[] of size n 49 | int pivotedBinarySearch(int arr[], int n, int key) 50 | { 51 | int pivot = findPivot(arr, 0, n - 1); 52 | 53 | // If we didn't find a pivot, 54 | // then array is not rotated at all 55 | if (pivot == -1) 56 | return binarySearch(arr, 0, n - 1, key); 57 | 58 | // If we found a pivot, then first compare with pivot 59 | // and then search in two subarrays around pivot 60 | if (arr[pivot] == key) 61 | return pivot; 62 | 63 | if (arr[0] <= key) 64 | return binarySearch(arr, 0, pivot - 1, key); 65 | 66 | return binarySearch(arr, pivot + 1, n - 1, key); 67 | } 68 | 69 | // Driver program to check above functions 70 | int main() 71 | { 72 | // Let us search 3 in below array 73 | int arr1[] = { 5, 6, 7, 8, 9, 10, 1, 2, 3 }; 74 | int n = sizeof(arr1) / sizeof(arr1[0]); 75 | int key = 3; 76 | 77 | // Function calling 78 | cout << "Index of the element is : " 79 | << pivotedBinarySearch(arr1, n, key); 80 | 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /CPP/Single Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int singleNumber(vector &nums) 5 | { 6 | //initialised the xor of numbers in xorr variable 7 | int xorr = 0; 8 | //Linearly traversing the array 9 | for (auto x = 0; x < nums.size(); x++) 10 | { 11 | //Calculating Xor of two numbers . 12 | xorr = xorr ^ nums[x]; 13 | 14 | } 15 | 16 | // Atlast return the final xor . 17 | 18 | return xorr; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /CPP/Sort Colors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(vector& nums) { 4 | int l=0, mid=0, h=nums.size()-1; 5 | while(mid<=h) { 6 | if(nums[mid]==0) { 7 | swap(nums[mid], nums[l]); 8 | l++; 9 | mid++; 10 | } else if(nums[mid]==1) 11 | mid++; 12 | else { 13 | swap(nums[mid], nums[h]); 14 | h--; 15 | } 16 | } 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /CPP/Spiral_Matrix.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/spiral-matrix/ 2 | 3 | class Solution { 4 | public: 5 | vector spiralOrder(vector>& matrix) { 6 | int lu=0,ll=0,ld=matrix.size()-1; 7 | int lr=matrix.empty()?0:matrix[0].size()-1; 8 | int sz=matrix.empty()?0:matrix.size()*matrix[0].size(); 9 | vectorres; 10 | while(res.size()=ll;--i) 18 | res.push_back(matrix[ld][i]); 19 | --ld; 20 | for(int i=ld;i>=lu;--i) 21 | res.push_back(matrix[i][ll]); 22 | ++ll; 23 | } 24 | if(res.size()>sz) 25 | res.erase(res.begin()+sz, res.end()); 26 | return res; 27 | } 28 | }; -------------------------------------------------------------------------------- /CPP/Sudoku Solver.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void solveSudoku(vector > &board) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | solve(board); 7 | } 8 | bool solve(vector> &board){ 9 | // Start typing your C/C++ solution below 10 | // DO NOT write int main() function 11 | for(int i=0;i<9;i++) 12 | for(int j=0;j<9;j++){ 13 | if(board[i][j]=='.'){ 14 | for(int k=1;k<=9;k++){ 15 | board[i][j]='0'+k; 16 | if(checkSudoku(board,i,j)&&solve(board)) return true; 17 | board[i][j]='.'; 18 | } 19 | return false; 20 | } 21 | } 22 | return true; 23 | } 24 | bool checkSudoku(vector> &board,int row,int col){ 25 | for(int i=0;i<9;i++) 26 | if(i!=row&&board[i][col]==board[row][col]) 27 | return false; 28 | for(int j=0;j<9;j++) 29 | if(j!=col&&board[row][j]==board[row][col]) 30 | return false; 31 | for(int i=3*(row/3);i<3*(row/3+1);i++) 32 | for(int j=3*(col/3);j<3*(col/3+1);j++) 33 | if(i!=row&&j!=col&&board[i][j]==board[row][col]) 34 | return false; 35 | return true; 36 | } 37 | }; -------------------------------------------------------------------------------- /CPP/SwapNode.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* swapPairs(ListNode* head) { 4 | if(!head)return head; 5 | 6 | ListNode *slow=head, *fast=slow->next; 7 | 8 | while(fast && fast->next) 9 | { 10 | swap(slow->val,fast->val); 11 | 12 | slow=fast->next; 13 | fast=fast->next->next; 14 | } 15 | 16 | if(slow && fast) 17 | { 18 | swap(slow->val,fast->val); 19 | } 20 | 21 | return head; 22 | 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /CPP/Trapping Rain Water.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Trapping Rain Water 3 | https://leetcode.com/problems/trapping-rain-water/ 4 | */ 5 | 6 | class Solution { 7 | public: 8 | int trap(vector& height) { 9 | int left = 0, right = height.size() - 1, maxLeft = 0, maxRight = 0, ans = 0; 10 | while(left <= right) { 11 | if(height[left] <= height[right]) { 12 | if(height[left] >= maxLeft) 13 | maxLeft = height[left]; 14 | else 15 | ans += (maxLeft - height[left]); 16 | left++; 17 | } 18 | else { 19 | if(height[right] >= maxRight) 20 | maxRight = height[right]; 21 | else 22 | ans += (maxRight - height[right]); 23 | right--; 24 | } 25 | } 26 | return ans; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /CPP/TwoSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | vector result; 5 | for(int i=0;i s; 5 | char x; 6 | 7 | 8 | for (int i = 0; i < expr.length(); i++) { 9 | if (expr[i] == '(' || expr[i] == '[' || expr[i] == '{') { 10 | 11 | s.push(expr[i]); 12 | continue; 13 | } 14 | 15 | if (s.empty()) 16 | return false; 17 | 18 | switch (expr[i]) { 19 | case ')': 20 | 21 | x = s.top(); 22 | s.pop(); 23 | if (x == '{' || x == '[') 24 | return false; 25 | break; 26 | 27 | case '}': 28 | 29 | x = s.top(); 30 | s.pop(); 31 | if (x == '(' || x == '[') 32 | return false; 33 | break; 34 | 35 | case ']': 36 | 37 | x = s.top(); 38 | s.pop(); 39 | if (x == '(' || x == '{') 40 | return false; 41 | break; 42 | } 43 | } 44 | 45 | return (s.empty()); 46 | 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /CPP/ValidateBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector v; 4 | void inorder(TreeNode* root){ 5 | if(root!=NULL){ 6 | inorder(root->left); 7 | v.push_back(root->val); 8 | inorder(root->right); 9 | } 10 | } 11 | bool isValidBST(TreeNode* root) { 12 | if(root==NULL) return true; 13 | inorder(root); 14 | for(int i=0;i=v[i+1]) return false; 17 | } 18 | return true; 19 | } 20 | }; -------------------------------------------------------------------------------- /CPP/VerticalOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | map>> ans; 4 | void pre( TreeNode *root, int horizontal_Level, int vertical_Level ){ 5 | if(!root) 6 | return ; 7 | ans[horizontal_Level].insert({vertical_Level,root->val}); 8 | pre(root->left,horizontal_Level-1,vertical_Level+1); 9 | pre(root->right,horizontal_Level+1,vertical_Level+1); 10 | } 11 | vector> verticalTraversal(TreeNode* root) { 12 | pre(root,0 , 0 ); 13 | vector> v; 14 | for( auto e : ans ){ 15 | vector c; 16 | for( auto x : e.second ) 17 | c.push_back(x.second); 18 | v.push_back(c); 19 | } 20 | return v; 21 | } 22 | }; -------------------------------------------------------------------------------- /CPP/WildCard_Matching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMatch(string s, string p) { 4 | int n=s.size(), m=p.size(); 5 | vector> dp(n+1,vector(m+1,0)); 6 | dp[0][0]=true; 7 | for(int i=1;i<=n;i++) 8 | dp[i][0]=false; 9 | for(int j=1;j<=m;j++) 10 | { 11 | if(p[j-1]=='*') dp[0][j]=dp[0][j-1]; 12 | else dp[0][j]=0; 13 | } 14 | for(int i=1;i<=n;i++) 15 | { 16 | for(int j=1;j<=m;j++) 17 | { 18 | if(p[j-1]=='?' || s[i-1]==p[j-1]) 19 | dp[i][j] = dp[i-1][j-1]; 20 | else if(p[j-1]=='*') 21 | dp[i][j] = dp[i-1][j] || dp[i][j-1]; 22 | else 23 | dp[i][j]=0; 24 | } 25 | } 26 | return dp[n][m]; 27 | } 28 | }; -------------------------------------------------------------------------------- /CPP/WordSearch.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool backtrack(vector>&board,int i,int j,string word,int pos){ 5 | 6 | 7 | if(pos==word.length()){ 8 | return true; 9 | } 10 | 11 | if(i<0||j<0||i>=board.size()||j>=board[0].size()||board[i][j]!=word[pos]){ 12 | return false; 13 | } 14 | 15 | 16 | char temp=board[i][j]; 17 | board[i][j]='*'; 18 | 19 | bool curr=(backtrack(board,i+1,j,word,pos+1) || backtrack(board,i-1,j,word,pos+1) || backtrack(board,i,j+1,word,pos+1) || backtrack(board,i,j-1,word,pos+1)); 20 | 21 | 22 | 23 | board[i][j]=temp; 24 | 25 | return curr; 26 | 27 | } 28 | 29 | bool exist(vector>& board, string word) { 30 | 31 | int m=board.size(); 32 | int n=board[0].size(); 33 | 34 | for(int i=0;i> zigzagLevelOrder(TreeNode* root) { 15 | vector> result; 16 | 17 | if(root==NULL) 18 | return result; 19 | 20 | queue nodesQueue; 21 | 22 | nodesQueue.push(root); 23 | 24 | bool leftToRight = true; 25 | 26 | while(!nodesQueue.empty()){ 27 | int size = nodesQueue.size(); 28 | vector row(size); 29 | 30 | for(int i=0;ival; 38 | 39 | if(node->left) 40 | nodesQueue.push(node->left); 41 | if(node->right) 42 | nodesQueue.push(node->right); 43 | } 44 | 45 | leftToRight = !leftToRight; 46 | result.push_back(row); 47 | } 48 | return result; 49 | 50 | } 51 | }; -------------------------------------------------------------------------------- /CPP/addDigit.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int addDigits(int n) { 4 | int sum = 0; 5 | while(n > 0 || sum > 9) 6 | { 7 | if(n == 0) 8 | { 9 | n = sum; 10 | sum = 0; 11 | } 12 | sum += n % 10; 13 | n /= 10; 14 | } 15 | return sum; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /CPP/addString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string addStrings(string num1, string num2) { 4 | string result; 5 | 6 | for (int i = num1.size() - 1, j = num2.size() - 1, carry = 0; 7 | i >= 0 || j >= 0 || carry; 8 | carry /= 10) { 9 | 10 | if (i >= 0) { 11 | carry += num1[i--] - '0'; 12 | } 13 | if (j >= 0) { 14 | carry += num2[j--] - '0'; 15 | } 16 | result += to_string(carry % 10); 17 | } 18 | reverse(result.begin(), result.end()); 19 | 20 | return result; 21 | } 22 | }; -------------------------------------------------------------------------------- /CPP/asteroid-collision.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector asteroidCollision(vector& asteroids) { 4 | stack s; 5 | 6 | for(int i=0;i0) 9 | { 10 | s.push(asteroids[i]); 11 | } 12 | else 13 | { 14 | while(true) 15 | { 16 | int top = s.top(); 17 | 18 | if(top<0) 19 | { 20 | s.push(asteroids[i]); 21 | break; 22 | } 23 | else if(top==-asteroids[i]) 24 | { 25 | s.pop(); 26 | break; 27 | } 28 | else if(top>(-asteroids[i])) 29 | { 30 | break; 31 | } 32 | else 33 | { 34 | s.pop(); 35 | if(s.empty()) 36 | { 37 | s.push(asteroids[i]); 38 | break; 39 | } 40 | } 41 | } 42 | } 43 | } 44 | 45 | vector output(s.size(),0); 46 | 47 | for(int i=s.size()-1;i>=0;i--) 48 | { 49 | output[i]=s.top(); 50 | s.pop(); 51 | } 52 | 53 | return output; 54 | 55 | 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /CPP/binarySearch.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target){ 4 | int s = 0; 5 | int e = nums.size() - 1; 6 | return 7 | recursive(nums, s, e, target); 8 | } 9 | 10 | int recursive(vector& nums, int s, int e, int target){ 11 | if(s > e) 12 | return -1; 13 | 14 | int mid = s + (e - s) / 2; 15 | 16 | if(nums[mid] == target) 17 | return mid; 18 | 19 | if(target > nums[mid]) 20 | return recursive(nums, mid + 1, e, target); 21 | else 22 | return recursive(nums, s, mid - 1, target); 23 | } 24 | }; -------------------------------------------------------------------------------- /CPP/brick-wall.cpp: -------------------------------------------------------------------------------- 1 | //done using hash table 2 | class Solution { 3 | public: 4 | int leastBricks(vector>& wall) { 5 | int n=wall.size(),i,j,pos,maxcount=0; 6 | 7 | unordered_map m; 8 | unordered_map:: iterator it; 9 | 10 | for(i=0;isecond); 25 | } 26 | return (n-maxcount); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /CPP/construct-the-rectangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector constructRectangle(int area) { 4 | vectors; 5 | int r = sqrt(area); 6 | while (area % r != 0) 7 | --r; 8 | s.push_back(area/r); 9 | s.push_back(r); 10 | return s; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /CPP/container-with-most-water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxArea(vector& height) { 4 | int max_volume = min(height.front(), height.back()) * (height.size() - 1); 5 | int low = 0; 6 | int high = height.size() - 1; 7 | while (low < high) { 8 | // Greedy: keep the longer pole in the choices. 9 | if (height[low] < height[high]) { 10 | low++; 11 | } else { 12 | high--; 13 | } 14 | max_volume = max(max_volume, volume(height, low, high)); 15 | } 16 | return max_volume; 17 | } 18 | 19 | int volume(const vector& height, int low, int high) { 20 | return min(height[low], height[high]) * (high - low); 21 | } 22 | 23 | int maxArea_brutal(vector& height) { 24 | int max_volume = 0; 25 | for (int i = 0; i < height.size(); i++) { 26 | for (int j = i + 1; j < height.size(); j++) { 27 | auto volume = min(height[i], height[j]) * (j - i); 28 | max_volume = max(max_volume, volume); 29 | } 30 | } 31 | return max_volume; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /CPP/countAndSay.cpp: -------------------------------------------------------------------------------- 1 | // Time: O(n * 2^n) 2 | // Space: O(2^n) 3 | 4 | class Solution { 5 | public: 6 | string countAndSay(int n) { 7 | string seq{"1"}; 8 | for (int i = 0; i < n - 1; ++i) { 9 | seq = getNext(seq); 10 | } 11 | return seq; 12 | } 13 | 14 | private: 15 | string getNext(const string& seq) { 16 | string next_seq; 17 | for(auto i = seq.cbegin(); i != seq.cend();) { 18 | auto j = find_if(i, seq.cend(), bind1st(not_equal_to(), *i)); 19 | next_seq.append(to_string(distance(i, j))); 20 | next_seq.push_back(*i); 21 | i = j; 22 | } 23 | return next_seq; 24 | } 25 | }; -------------------------------------------------------------------------------- /CPP/decode-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string decodeString(string s) { 4 | stack chars; 5 | stack nums; 6 | string res; 7 | int num = 0; 8 | for(char c : s) { 9 | if(isdigit(c)) { 10 | num = num*10 + (c-'0'); 11 | } 12 | else if(isalpha(c)) { 13 | res.push_back(c); 14 | } 15 | else if(c == '[') { 16 | chars.push(res); 17 | nums.push(num); 18 | res = ""; 19 | num = 0; 20 | } 21 | else if(c == ']') { 22 | string tmp = res; 23 | for(int i = 0; i < nums.top()-1; ++i) { 24 | res += tmp; 25 | } 26 | res = chars.top() + res; 27 | chars.pop(); nums.pop(); 28 | } 29 | } 30 | return res; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /CPP/flatten-nested-list-iterator.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/flatten-nested-list-iterator/ 2 | 3 | class NestedIterator { 4 | public: 5 | vectorres; 6 | NestedIterator(vector &nestedList) { 7 | for(auto i:nestedList){ 8 | stackst; 9 | st.push(i); 10 | while(!st.empty()){ 11 | auto j =st.top(); 12 | st.pop(); 13 | if(j.isInteger()) 14 | res.push_back(j.getInteger()); 15 | else{ 16 | vectortmp = j.getList(); 17 | for(int i=tmp.size()-1;i>-1;--i) 18 | st.push(tmp[i]); 19 | } 20 | } 21 | } 22 | 23 | } 24 | 25 | int next() { 26 | int i=res[0]; 27 | res.erase(res.begin()); 28 | return i; 29 | } 30 | 31 | bool hasNext() { 32 | return !res.empty(); 33 | } 34 | }; -------------------------------------------------------------------------------- /CPP/house robber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | int i,money=0; 5 | for(i=0;i 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | int main() 7 | { 8 | int array_size; 9 | cout<<"Enter the array size"<>array_size; 11 | int array[array_size]; 12 | for (int i = 0; i >array[i]; 15 | } 16 | for (int i = 1; i < array_size; i++) 17 | { 18 | int key = array[i]; 19 | int j = i-1; 20 | 21 | while (key0) 22 | { 23 | array[j+1]= array[j]; 24 | j = j-1; 25 | } 26 | j = key; 27 | cout< 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | int main() 7 | { 8 | int n; 9 | cin>>n; 10 | cin.ignore(); 11 | char arr[n+1]; 12 | cin.getline(arr,n); 13 | cin.ignore(); 14 | int curr_length=0,max_length; 15 | max_length=0; 16 | int i=0; 17 | while(1) 18 | { 19 | if (arr[i]==' '|| arr[i]=='\0') 20 | { 21 | if (curr_length>max_length) 22 | { 23 | max_length=curr_length; 24 | } 25 | curr_length=0; 26 | } 27 | else 28 | curr_length++; 29 | if (arr[i]=='\0') 30 | { 31 | break; 32 | } 33 | 34 | 35 | i++ ; 36 | } 37 | cout< helper(int temp,string map1[]){ 4 | if(temp==0 || temp ==1){ 5 | vector base; 6 | base.push_back(""); 7 | return base; 8 | } 9 | int smallNo = temp%10; 10 | string s = map1[smallNo]; 11 | vectorsmallOutput; 12 | int temp1 = temp/10; 13 | smallOutput = helper(temp1,map1); 14 | 15 | vectoroutput; 16 | for(int i=0;i letterCombinations(string digits) { 24 | int temp = 0; 25 | if(digits==""){ 26 | vectorans; 27 | return ans; 28 | } 29 | for (int i = 0; i < digits.length(); i++) { 30 | temp = temp * 10 + (digits[i] - '0'); 31 | } 32 | string map1[] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 33 | return helper(temp,map1); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /CPP/letterCombinationsOfAPhoneNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void solve(string digit, string output, int index, vector &ans, string mapping[]){ 4 | if(index >= digit.length()){ 5 | ans.push_back(output); 6 | return; 7 | } 8 | 9 | int number = digit[index] - '0'; 10 | string value = mapping[number]; 11 | 12 | for(int i = 0; i < value.length(); i++){ 13 | output.push_back(value[i]); 14 | solve(digit, output, index + 1, ans, mapping); 15 | output.pop_back(); 16 | } 17 | } 18 | 19 | public: 20 | vector letterCombinations(string digits){ 21 | vector ans; 22 | if(digits.length() == 0) 23 | return ans; 24 | string output; 25 | int index = 0; 26 | string mapping[10] = {"", "", "abc", "def", "ghi", "jkl","mno","pqrs","tuv","wxyz"}; 27 | solve(digits, output, index, ans, mapping); 28 | return ans; 29 | } 30 | }; -------------------------------------------------------------------------------- /CPP/median-of-two-sorted-arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector& v1, vector& v2) { 4 | v1.insert(v1.end(),v2.begin(),v2.end()); 5 | sort(v1.begin(),v1.end()); 6 | int n = v1.size()-1; 7 | if(n%2!=0) { 8 | return (v1[n/2]+v1[(n/2)+1])/2.0; 9 | } 10 | else{ 11 | return v1[n/2]; 12 | } 13 | return 0; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /CPP/multiplystrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string multiply(string num1, string num2) 4 | { 5 | int p; 6 | int first = std::stoi(num1); 7 | int second = std::stoi(num2); 8 | p=first*second; 9 | std::string str = to_string(p); 10 | 11 | return str; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /CPP/palindrome_check.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | int main() 7 | { 8 | int n; 9 | cin >>n; 10 | char arr[n+1]; 11 | cin>>arr; 12 | bool pal_check=1; 13 | for (int i = 0; i next; 21 | } 22 | if(length==1) { 23 | return NULL; 24 | } 25 | int node=length-n+1; 26 | int count=1; 27 | temp=head; 28 | if(node==1 || node==0) { 29 | return head->next; 30 | } 31 | while(count!=(node-1)) { 32 | temp=temp->next; 33 | count++; 34 | } 35 | // cout<val; 36 | if(temp->next->next==NULL) 37 | temp->next=NULL; 38 | else 39 | temp->next=temp->next->next; 40 | return head; 41 | } 42 | }; -------------------------------------------------------------------------------- /CPP/rotateArray.cpp: -------------------------------------------------------------------------------- 1 | /* 189. Rotate Array */ 2 | /* https://leetcode.com/problems/rotate-array/ */ 3 | 4 | 5 | class Solution { 6 | public: 7 | void rotate(vector& nums, int k) { 8 | int n=nums.size(); 9 | k%=n; 10 | int d=n-k; 11 | for(int i=0;i>& matrix, int target) { 4 | int i = matrix.size(); 5 | int j = matrix[0].size(); 6 | 7 | int s = 0; 8 | int e = i * j - 1; 9 | 10 | int mid = s + (e - s) / 2; 11 | 12 | while (s <= e){ 13 | int element = matrix[mid / j][mid % j]; 14 | if (element == target){ 15 | return 1; 16 | } 17 | else if (element < target){ 18 | s = mid + 1; 19 | } 20 | else { 21 | e = mid - 1; 22 | } 23 | mid = s + (e - s) / 2; 24 | } 25 | return 0; 26 | } 27 | }; -------------------------------------------------------------------------------- /CPP/sqrt_number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int mySqrt(int x) 4 | { 5 | int prev,k = 0; 6 | int kmax = 1000; 7 | double s = 1; 8 | for(k=0;k 2 | #include 3 | #include 4 | 5 | class Solution { 6 | public: 7 | int mySqrt(int x) { 8 | long long l(1), h(x), mid(0), res(0); 9 | while (l <= h) { 10 | mid = (l + h) / 2; 11 | long long msq = mid * mid; 12 | if (msq == x) { 13 | return mid; 14 | } else if (msq > x) { 15 | h = mid - 1; 16 | } else { 17 | l = mid + 1; 18 | res = mid; 19 | } 20 | } 21 | return res; 22 | } 23 | }; 24 | 25 | int main(int argc, char** argv) { 26 | int val(atoi(argv[1])); 27 | std::unique_ptr ptr(new Solution()); 28 | std::cout << ptr->mySqrt(val) << std::endl; 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /CPP/subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void solve(vector nums, vector output, int index, vector> &ans){ 4 | if(index >= nums.size()){ 5 | ans.push_back(output); 6 | return ; 7 | } 8 | 9 | solve(nums, output, index+1, ans); 10 | 11 | int element = nums[index]; 12 | output.push_back(element); 13 | solve(nums, output, index+1, ans); 14 | 15 | } 16 | 17 | public: 18 | vector> subsets(vector& nums){ 19 | vector > ans; 20 | vector output; 21 | int index = 0; 22 | solve(nums, output, index, ans); 23 | return ans; 24 | } 25 | }; -------------------------------------------------------------------------------- /CPP/zigzag.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string convert(string s, int numRows) { 4 | if(numRows == 1) 5 | return s; 6 | string arr[numRows]; 7 | int row = 0; 8 | bool down = true; 9 | for(int i = 0; i < s.size(); i++) 10 | { 11 | arr[row].push_back(s[i]); 12 | if(row == numRows - 1) down = false; 13 | else if(row == 0)down = true; 14 | if(down) row++; 15 | else row--; 16 | } 17 | string ans = ""; 18 | for(int i = 0; i < numRows; i++) 19 | { 20 | ans += arr[i]; 21 | } 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Golang/DistinctSubsequences.go: -------------------------------------------------------------------------------- 1 | func numDistinct(s string, t string) int { 2 | mem := make([][]int, len(t)+1) 3 | for i := range mem { 4 | mem[i] = make([]int, len(s)+1) 5 | } 6 | 7 | for i := 0; i <= len(s); i++ { 8 | mem[0][i] = 1 9 | } 10 | 11 | for i := 0; i < len(t); i++ { 12 | for j := 0; j < len(s); j++ { 13 | if t[i] == s[j] { 14 | mem[i+1][j+1] = mem[i][j] + mem[i+1][j] 15 | } else { 16 | mem[i+1][j+1] = mem[i+1][j] 17 | } 18 | } 19 | } 20 | return mem[len(t)][len(s)] 21 | } 22 | -------------------------------------------------------------------------------- /Golang/EditDistance.go: -------------------------------------------------------------------------------- 1 | func minDistance(word1 string, word2 string) int { 2 | len1, len2 := len(word1), len(word2) 3 | 4 | costs := make([][]int, len1 + 1) 5 | for idx := range costs{ 6 | costs[idx] = make([]int, len2 + 1) 7 | } 8 | 9 | for idx := 0; idx <= len1; idx++ { 10 | costs[idx][0] = idx 11 | } 12 | 13 | for idx := 0; idx <= len2; idx++{ 14 | costs[0][idx] = idx 15 | } 16 | 17 | for idx1 := 0; idx1 < len1; idx1++{ 18 | for idx2 := 0; idx2 < len2; idx2++ { 19 | if word1[idx1] == word2[idx2] { 20 | costs[idx1 + 1][idx2 + 1] = costs[idx1][idx2] 21 | }else{ 22 | replacement := costs[idx1][idx2] 23 | insersion := costs[idx1 + 1][idx2] 24 | deletion := costs[idx1][idx2 + 1] 25 | 26 | costs[idx1 + 1][idx2 + 1] = 1 + minOf(replacement, insersion, deletion) 27 | } 28 | } 29 | } 30 | 31 | return costs[len1][len2] 32 | } 33 | 34 | func minOf(vars ...int) int{ 35 | min := vars[0] 36 | 37 | for _, val := range vars{ 38 | if val < min{ 39 | min = val 40 | } 41 | } 42 | 43 | return min 44 | } 45 | -------------------------------------------------------------------------------- /Golang/FirstMissingPositive.go: -------------------------------------------------------------------------------- 1 | func firstMissingPositive(nums []int) int { 2 | //we can map negative, 0 and number that is larger than n to 1 3 | //first check if one exist 4 | n := len(nums) 5 | oneExist := false 6 | for i := 0; i < n; i++ { 7 | if nums[i] == 1 { 8 | oneExist = true 9 | break 10 | } 11 | } 12 | if !oneExist { 13 | return 1 14 | } 15 | for i := 0; i < n; i++ { 16 | if nums[i] <= 0 || nums[i] > n { 17 | nums[i] = 1 18 | } 19 | } 20 | for i := 0; i < n; i++ { 21 | nums[abs(nums[i])-1] = -abs(nums[abs(nums[i])-1]) 22 | } 23 | for i := 0; i < n; i++ { 24 | if nums[i] > 0 { 25 | return i+1 26 | } 27 | } 28 | return n+1 29 | } 30 | 31 | func abs(x int) int { 32 | if x < 0 { 33 | return -x 34 | } else { 35 | return x 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Golang/add-two-numbers.go: -------------------------------------------------------------------------------- 1 | // Time: O(n) 2 | // Space: O(1) 3 | 4 | /** 5 | * Definition for singly-linked list. 6 | * type ListNode struct { 7 | * Val int 8 | * Next *ListNode 9 | * } 10 | */ 11 | 12 | func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { 13 | dummy := &ListNode{} 14 | current, carry := dummy, 0 15 | 16 | for l1 != nil || l2 != nil { 17 | val := carry 18 | if l1 != nil { 19 | val += l1.Val 20 | l1 = l1.Next 21 | } 22 | if l2 != nil { 23 | val += l2.Val 24 | l2 = l2.Next 25 | } 26 | carry, val = val/10, val%10 27 | current.Next = &ListNode{Val: val} 28 | current = current.Next 29 | } 30 | 31 | if carry == 1 { 32 | current.Next = &ListNode{Val: 1} 33 | } 34 | 35 | return dummy.Next 36 | } 37 | -------------------------------------------------------------------------------- /Golang/longest_substring_without_repeating_characters.go: -------------------------------------------------------------------------------- 1 | // Time: O(n) 2 | 3 | func lengthOfLongestSubstring(s string) int { 4 | m := make(map[byte]int) 5 | res := 0 6 | left := 0 7 | right := 0 8 | 9 | for right < len(s) { 10 | if index, ok := m[s[right]]; ok { 11 | if left > index { 12 | left = left 13 | } else { 14 | left = index 15 | } 16 | } 17 | 18 | if res > right-left+1 { 19 | res = res 20 | } else { 21 | res = right - left + 1 22 | } 23 | 24 | m[s[right]] = right + 1 25 | right++ 26 | } 27 | return res 28 | } -------------------------------------------------------------------------------- /Golang/min_ticket.go: -------------------------------------------------------------------------------- 1 | func mincostTickets(days []int, costs []int) int { 2 | const MAXINT = int(^uint(0) >> 1) 3 | 4 | durations := [3]int{1, 7, 30} 5 | W := durations[len(durations)-1] 6 | dp := make([]int, W) 7 | for i, _ := range dp { 8 | dp[i] = MAXINT 9 | } 10 | dp[0] = 0 11 | 12 | last_buy_days := [3]int{0, 0, 0} 13 | for i := 1; i < len(days)+1; i++ { 14 | dp[i%W] = MAXINT 15 | for j := 0; j < len(durations); j++ { 16 | for (i-1 < len(days)) && 17 | (days[i-1] > days[last_buy_days[j]]+durations[j]-1) { 18 | last_buy_days[j]++ 19 | } 20 | dp[i%W] = min(dp[i%W], dp[last_buy_days[j]%W]+costs[j]) 21 | } 22 | } 23 | return dp[len(days)%W] 24 | } 25 | 26 | func min(X int, Y int) int { 27 | if X < Y { 28 | return X 29 | } 30 | return Y 31 | } -------------------------------------------------------------------------------- /Golang/palindrome_number.go: -------------------------------------------------------------------------------- 1 | // Time: O(n) 2 | 3 | func isPalindrome(x int) bool { 4 | 5 | if x < 0 { 6 | return false 7 | } 8 | 9 | var reversed int 10 | temp := x 11 | for x != 0 { 12 | last_digit := x % 10 13 | reversed = reversed*10 + last_digit 14 | x = x / 10 15 | } 16 | 17 | if reversed == temp { 18 | return true 19 | } 20 | 21 | return false 22 | } -------------------------------------------------------------------------------- /Golang/reverse_integer.go: -------------------------------------------------------------------------------- 1 | // Time: O(n) 2 | 3 | func reverse(x int) int { 4 | var reversed int 5 | for x != 0 { 6 | last_digit := x % 10 7 | reversed = reversed*10 + last_digit 8 | x = x / 10 9 | } 10 | if reversed < -1<<31 || reversed > 1<<31 { 11 | return 0 12 | } 13 | return reversed 14 | } -------------------------------------------------------------------------------- /Golang/two-sum.go: -------------------------------------------------------------------------------- 1 | // Time: O(n) 2 | // Space: O(n) 3 | 4 | func twoSum(nums []int, target int) []int { 5 | lookup := make(map[int]int) 6 | for i, num := range nums { 7 | if j, ok := lookup[target-num]; ok { 8 | return []int{j, i} 9 | } 10 | lookup[nums[i]] = i 11 | } 12 | return nil 13 | } 14 | -------------------------------------------------------------------------------- /Golang/valid_parenthesis.go: -------------------------------------------------------------------------------- 1 | // Time: O(n) 2 | 3 | func isValid(s string) bool { 4 | stack := []rune{} 5 | Maps := map[rune]rune{ 6 | ')': '(', 7 | '}': '{', 8 | ']': '[', 9 | } 10 | 11 | if s != "" { 12 | for _, b := range s { 13 | if len(stack) == 0 { 14 | stack = append(stack, b) 15 | continue 16 | } 17 | if Maps[b] == stack[len(stack)-1] { 18 | stack = stack[:len(stack)-1] 19 | } else { 20 | stack = append(stack, b) 21 | } 22 | } 23 | } else { 24 | return false 25 | } 26 | if len(stack) == 0 { 27 | return true 28 | } 29 | return false 30 | } 31 | -------------------------------------------------------------------------------- /Java/4sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> fourSum(int[] nums, int target) { 3 | Arrays.sort(nums); 4 | return kSum(nums, target, 0, 4); 5 | } 6 | 7 | public List> kSum(int[] nums, long target, int start, int k) { 8 | List> res = new ArrayList<>(); 9 | 10 | if (start == nums.length) { 11 | return res; 12 | } 13 | 14 | 15 | long average_value = target / k; 16 | 17 | 18 | if (nums[start] > average_value || average_value > nums[nums.length - 1]) { 19 | return res; 20 | } 21 | 22 | if (k == 2) { 23 | return twoSum(nums, target, start); 24 | } 25 | 26 | for (int i = start; i < nums.length; ++i) { 27 | if (i == start || nums[i - 1] != nums[i]) { 28 | for (List subset : kSum(nums, target - nums[i], i + 1, k - 1)) { 29 | res.add(new ArrayList<>(Arrays.asList(nums[i]))); 30 | res.get(res.size() - 1).addAll(subset); 31 | } 32 | } 33 | } 34 | 35 | return res; 36 | } 37 | 38 | public List> twoSum(int[] nums, long target, int start) { 39 | List> res = new ArrayList<>(); 40 | int lo = start, hi = nums.length - 1; 41 | 42 | while (lo < hi) { 43 | int currSum = nums[lo] + nums[hi]; 44 | if (currSum < target || (lo > start && nums[lo] == nums[lo - 1])) { 45 | ++lo; 46 | } else if (currSum > target || (hi < nums.length - 1 && nums[hi] == nums[hi + 1])) { 47 | --hi; 48 | } else { 49 | res.add(Arrays.asList(nums[lo++], nums[hi--])); 50 | } 51 | } 52 | 53 | return res; 54 | } 55 | } -------------------------------------------------------------------------------- /Java/Add_Two_Numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | 13 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 14 | ListNode ans = new ListNode(); 15 | ListNode tail = ans; 16 | int carry = 0; 17 | while (true) { 18 | int v1 = l1 == null ? 0 : l1.val; 19 | int v2 = l2 == null ? 0 : l2.val; 20 | if (l1 != null) l1 = l1.next; 21 | if(l2 != null) l2 = l2.next; 22 | int sum = carry + v1 + v2; 23 | tail.val = sum % 10; 24 | carry = sum / 10; 25 | if (l1 == null && l2 == null && carry == 0) break; 26 | tail.next = new ListNode(); 27 | tail = tail.next; 28 | } 29 | return ans; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Java/BestTimeToBuyAndSellStock.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices) { 3 | int maxProf = 0, j = 0; 4 | for (int i = 1; i < prices.length; i ++){ 5 | int compare = prices[i] - prices[j]; 6 | if(compare > maxProf){ 7 | maxProf = compare; 8 | } 9 | if(prices[i] < prices[j]) 10 | j = i; 11 | } 12 | return maxProf; 13 | } 14 | } -------------------------------------------------------------------------------- /Java/BitwiseXOROfAllPairings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int xorAllNums(int[] nums1, int[] nums2) { 3 | int n1 = nums1.length, n2 = nums2.length; 4 | int v = 0; 5 | if (!isEven(n1)) { 6 | for (int x: nums2) v ^= x; 7 | } 8 | if (!isEven(n2)) { 9 | for (int x: nums1) v ^= x; 10 | } 11 | return v; 12 | } 13 | private boolean isEven(int x) { 14 | return (x&1) == 0; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Java/DecodeWays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numDecodings(String s) { 3 | int dp[] = new int[s.length()]; 4 | if(s.charAt(0)!='0') 5 | dp[0] = 1; 6 | 7 | for(int i=1;i=2 ? dp[i-2]:1); 21 | } 22 | } 23 | else if(a!='0'&&b=='0') 24 | { 25 | dp[i] = dp[i-1]; 26 | } 27 | else 28 | { 29 | int x = Integer.parseInt(s.substring(i-1,i+1)); 30 | if(x<=26) 31 | { 32 | dp[i] = dp[i-1] + (i>=2?dp[i-2]:1); 33 | } 34 | else 35 | { 36 | dp[i] = dp[i-1]; 37 | } 38 | } 39 | } 40 | return dp[s.length()-1]; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Java/Divide_Two_Integers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int divide(int dividend, int divisor) { 3 | if(dividend == 1 << 31 && divisor == -1) return (1 << 31) - 1; 4 | int a = dividend > 0 ? dividend : -dividend, b = divisor > 0 ? divisor : -divisor; 5 | int res = 0, x = 0; 6 | while (a - b >= 0) { // a >= b is not same as this, same below 7 | x = 0; 8 | while(a - (b << x << 1) >= 0) x++; 9 | res += 1 << x; 10 | a -= b << x; 11 | } 12 | return dividend > 0 == divisor > 0 ? res : -res; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Java/EvenNumberofDigits.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findNumbers(int[] nums) { 3 | int count = 0; 4 | for(int i=0; i index = new HashMap<>(); 6 | for(int i=0;i(){ 10 | public int compare(int[] i1,int[] i2){ 11 | return i1[0]-i2[0]; 12 | } 13 | }); 14 | for(int i=0;i>1; 19 | if(intervals[mid][0]>=target)high=mid-1; 20 | else low=mid+1; 21 | } 22 | right[index.get(intervals[i][0])]=low==n?-1:index.get(intervals[low][0]); 23 | } 24 | return right; 25 | } 26 | } -------------------------------------------------------------------------------- /Java/FindLargestValueInEachTreeRow.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List largestValues(TreeNode root) { 3 | Queue q = new LinkedList<>(); 4 | List res = new ArrayList(); 5 | if (root != null) q.add(root); 6 | while (q.size() > 0) { 7 | int len = q.size(), maxx = Integer.MIN_VALUE; 8 | while (len-- > 0) { 9 | TreeNode n = q.peek(); 10 | if (n.val > maxx) maxx = n.val; 11 | if (n.left != null) q.add(n.left); 12 | if (n.right != null) q.add(n.right); 13 | q.remove(); 14 | } 15 | res.add(maxx); 16 | } 17 | return res; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Java/FizzBuzz.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List fizzBuzz(int n) { 3 | List list = new ArrayList<>(); 4 | int i3 = 0, i5 = 0; 5 | String f = "Fizz", b = "Buzz", fb = "FizzBuzz"; 6 | for (int i = 1; i <= n; i++) { 7 | i3 += 1; i5 += 1; 8 | if (i3 == 3 && i5 == 5) { 9 | list.add(fb); 10 | i3 = 0; i5 = 0; 11 | } else if (i3 == 3) { 12 | list.add(f); 13 | i3 = 0; 14 | } else if (i5 == 5) { 15 | list.add(b); 16 | i5 = 0; 17 | } else { 18 | list.add(String.valueOf(i)); 19 | } 20 | } 21 | return list; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/HappyNumber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int getNext(int n) { 4 | int totalSum = 0; 5 | while (n > 0) { 6 | int d = n % 10; 7 | n = n / 10; 8 | totalSum += d * d; 9 | } 10 | return totalSum; 11 | } 12 | 13 | public boolean isHappy(int n) { 14 | int slowRunner = n; 15 | int fastRunner = getNext(n); 16 | while (fastRunner != 1 && slowRunner != fastRunner) { 17 | slowRunner = getNext(slowRunner); 18 | fastRunner = getNext(getNext(fastRunner)); 19 | } 20 | return fastRunner == 1; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Java/IntegerToRoman.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String intToRoman(int num) { 3 | int[] value = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 4 | String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 5 | 6 | StringBuilder romanNumeral = new StringBuilder(); 7 | 8 | for (int i = 0; i < value.length && num > 0; i++) { 9 | while (num >= value[i]) { 10 | romanNumeral.append(roman[i]); 11 | num -= value[i]; 12 | } 13 | } 14 | return romanNumeral.toString(); 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /Java/IslandPerimeter.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int islandPerimeter(int[][] grid) { 3 | int rows = grid.length; 4 | int cols = grid[0].length; 5 | int perimeter = 0; 6 | for (int i = 0; i < rows; i++) { 7 | for (int j = 0; j < cols; j++) { 8 | if (grid[i][j] == 1) { 9 | perimeter += 4; 10 | if (i > 0 && grid[i-1][j] == 1) { 11 | perimeter -= 1; 12 | } 13 | if (i < rows - 1 && grid[i+1][j] == 1) { 14 | perimeter -= 1; 15 | } 16 | if (j > 0 && grid[i][j-1] == 1) { 17 | perimeter -= 1; 18 | } 19 | if (j < cols - 1 && grid[i][j+1] == 1) { 20 | perimeter -= 1; 21 | } 22 | } 23 | } 24 | } 25 | return perimeter; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/IsomorphicStrings.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isIsomorphic(String s, String t) { 3 | Map cMap = new HashMap<>(); 4 | for (int i = 0; i < s.length(); i++) { 5 | char sc = s.charAt(i), tc = t.charAt(i); 6 | boolean contains = cMap.containsKey(sc); 7 | if ((contains && cMap.get(sc) != tc) 8 | || (!contains && cMap.containsValue(tc))) return false; 9 | if (!contains) cMap.put(sc, tc); 10 | } 11 | return true; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Java/JumpGame.java: -------------------------------------------------------------------------------- 1 | public boolean canJump(int[] nums) { 2 | int indexToJump = nums.length - 1; 3 | for (int i = nums.length - 1; i >= 0; i--) { 4 | if (i + nums[i] >= indexToJump) { 5 | indexToJump = i; 6 | } 7 | } 8 | return indexToJump == 0; 9 | } 10 | -------------------------------------------------------------------------------- /Java/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestCommonSubsequence(String text1, String text2) { 3 | if (text2.length() > text1.length()) { 4 | String t = text1; 5 | text1 = text2; 6 | text2 = t; 7 | } 8 | int m = text1.length(), n = text2.length(); 9 | int[] dp = new int[n+1]; 10 | for (int i = 1; i <= m; ++i) { 11 | for (int j = 1, p = 0, np; j <= n; ++j) { 12 | np = dp[j]; 13 | if (text1.charAt(i-1) == text2.charAt(j-1)) dp[j] = 1+p; 14 | else if (dp[j] < dp[j-1]) dp[j] = dp[j-1]; 15 | p = np; 16 | } 17 | //System.out.println(Arrays.toString(dp)); 18 | } 19 | return dp[n]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Java/LongestUploadedPrefix.java: -------------------------------------------------------------------------------- 1 | class LUPrefix { 2 | // probably an overkill 3 | UF uf; 4 | boolean[] v; 5 | 6 | public LUPrefix(int n) { 7 | uf = new UF(n+1); 8 | v = new boolean[n+2]; 9 | } 10 | 11 | public void upload(int video) { 12 | v[video] = true; 13 | if (v[video-1]) uf.union(video-1, video); 14 | if (v[video+1]) uf.union(video, video+1); 15 | } 16 | 17 | public int longest() { 18 | return v[1] ? uf.find(1): 0; 19 | } 20 | } 21 | class UF { 22 | int[] p; 23 | public UF(int n) { 24 | p = new int[n]; 25 | Arrays.setAll(p, i -> i); 26 | } 27 | public int find(int i) { 28 | return i == p[i] ? i : (p[i] = find(p[p[i]])); 29 | } 30 | public void union(int i, int j) { 31 | int pi = find(i), pj = find(j); 32 | if (pi == pj) return; 33 | if (pj > pi) p[pi] = pj; 34 | else p[pj] = pi; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Java/Longest_Common_Prefix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | private boolean charNotEqual(String[] strs, int i, int j) { 4 | if(j >= strs[i].length() || j >= strs[i+1].length()) return true; 5 | return strs[i].charAt(j) != strs[i+1].charAt(j); 6 | } 7 | public String longestCommonPrefix(String[] strs) { 8 | if(strs.length == 0) return ""; 9 | for (int j = 0; j < strs[0].length(); j++) { 10 | for (int i = 0; i < strs.length - 1; i++) { 11 | if(charNotEqual(strs, i, j)) return strs[0].substring(0, j); 12 | } 13 | } 14 | return strs[0]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Java/Longest_Substring_Without_Repeating_Characters.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLongestSubstring(String s) { 3 | int res = -1; 4 | int count = 0; 5 | int[] present = new int[256]; 6 | for (char i = 0; i < 256; i++) present[i] = -1; 7 | char[] str = s.toCharArray(); 8 | int i = 0; 9 | while(i < str.length) { 10 | char ch = str[i]; 11 | if(present[ch] != -1) { 12 | i = present[ch]; 13 | for (char j = 0; j < 256; j++) present[j] = -1; 14 | if(res < count) res = count; 15 | count = 0; 16 | } 17 | else { 18 | present[ch] = i; 19 | count++; 20 | } 21 | i++; 22 | } 23 | return res < count ? count : res; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Java/Maximum_Product.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProduct(int[] nums) { 3 | int max = 0; 4 | for(int i=0; i= 0) { 6 | for (int j = grid[0].length - 1; j >= 0; j--) { 7 | if (i == grid.length - 1 && j == grid[0].length - 1) { 8 | grid[i][j] = grid[i][j]; 9 | } else if (i == grid.length - 1) { 10 | grid[i][j] += grid[i][j + 1]; 11 | } else if (j == grid[0].length - 1) { 12 | grid[i][j] += grid[i + 1][j]; 13 | } else { 14 | grid[i][j] += Math.min(grid[i][j + 1], grid[i + 1][j]); 15 | } 16 | } 17 | i--; 18 | } 19 | 20 | return grid[0][0]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Java/NumberOfPairsSatisfyingInequality.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long numberOfPairs(int[] nums1, int[] nums2, int diff) { 3 | // nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff 4 | // nums2[j] - nums1[j] <= nums2[i] - nums1[i] + diff 5 | int n = nums1.length; 6 | int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; 7 | for (int i = n-1; i >= 0; --i) { 8 | int k = nums2[i] - nums1[i]; 9 | if (min > k) min = k; 10 | if (max < k) max = k; 11 | } 12 | min = Math.min(min, min+diff); 13 | max = Math.max(max, max+diff); 14 | BIT bit = new BIT(max-min+1); 15 | long ans = 0; 16 | int shift = -min; 17 | for (int i = n-1; i >= 0; --i) { 18 | int k = nums2[i] - nums1[i]; 19 | ans += bit.sum(k + diff + shift); 20 | bit.add(k + shift, 1); 21 | } 22 | return ans; 23 | } 24 | } 25 | class BIT { 26 | int[] bit; 27 | int n; 28 | public BIT(int n) { 29 | bit = new int[n+1]; 30 | this.n = n; 31 | } 32 | int sum(int idx) { 33 | int ret = 0; 34 | for (++idx; idx > 0; idx -= idx & -idx) 35 | ret += bit[idx]; 36 | return ret; 37 | } 38 | 39 | int sum(int l, int r) { 40 | return sum(r) - sum(l - 1); 41 | } 42 | 43 | void add(int idx, int delta) { 44 | for (++idx; idx < n; idx += idx & -idx) 45 | bit[idx] += delta; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Java/PartitionToKEqualSumSubsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canPartitionKSubsets(int[] nums, int k) { 3 | int n = nums.length, sum = Arrays.stream(nums).reduce(0, Integer::sum); 4 | int subsetSum = sum/k; 5 | if (subsetSum*k != sum) return false; 6 | int[] subsets = new int[k]; 7 | Arrays.fill(subsets, subsetSum); 8 | Arrays.sort(nums); 9 | return dfs(nums, n-1, subsets); 10 | } 11 | private boolean dfs(int[] a, int p, int[] s) { 12 | if (Arrays.stream(s).reduce(Integer::sum).getAsInt() == 0) return true; 13 | if (p < 0) return false; 14 | for (int i = 0; i < s.length; ++i) { 15 | if (s[i] >= a[p]){ 16 | s[i] -= a[p]; 17 | if (dfs(a, p-1, s)) return true; 18 | s[i] += a[p]; 19 | } 20 | } 21 | return false; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/Pascals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List < List < Integer >> generate(int numRows) { 3 | List < List < Integer >> ans = new ArrayList < > (); 4 | ans.add(List.of(1)); 5 | if (numRows == 1) { 6 | return ans; 7 | } 8 | for (int row = 2; row <= numRows; row++) { 9 | List < Integer > newRow = new ArrayList < > (); 10 | List < Integer > prevRow = ans.get(row - 2); 11 | for (int i = 0; i < row; i++) { 12 | if (i == 0 || i == row - 1) { 13 | newRow.add(1); 14 | } else { 15 | newRow.add(prevRow.get(i - 1) + prevRow.get(i)); 16 | } 17 | } 18 | ans.add(newRow); 19 | } 20 | return ans; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Java/PopulatingNextRightPointersInEachNode.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public Node connect(Node root) { 3 | Queue q = new LinkedList<>(); 4 | if (root != null) { 5 | q.add(null); 6 | q.add(root); 7 | } 8 | while (q.size() > 1) { 9 | int len = q.size(); 10 | Node it = null; 11 | while (len-- > 0) { 12 | Node n = q.peek(); 13 | if (n != null) { 14 | if (n.right != null) q.add(n.right); 15 | if (n.left != null) q.add(n.left); 16 | n.next = it; 17 | it = n; 18 | } else { 19 | q.add(n); 20 | } 21 | q.remove(); 22 | } 23 | } 24 | return root; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Java/PrefixSuffixSearch.java: -------------------------------------------------------------------------------- 1 | class TrieNode { 2 | public Map children; 3 | public Set words; 4 | public TrieNode() { 5 | children = new HashMap<>(); 6 | words = new HashSet<>(); 7 | } 8 | } 9 | class WordFilter { 10 | private TrieNode rootP, rootS; 11 | private Map indexes; 12 | 13 | public WordFilter(String[] words) { 14 | rootP = new TrieNode(); 15 | rootS = new TrieNode(); 16 | indexes = new HashMap<>(); 17 | for (int i=0; i prefixes = ptrP.words; 52 | 53 | // get all words with suffix 54 | for (int i=0; i suffixes = ptrS.words; 60 | 61 | int index = -1; 62 | for (String word: prefixes) 63 | if (suffixes.contains(word)) 64 | index = Math.max(index, indexes.get(word)); 65 | 66 | return index; 67 | } 68 | } 69 | /** 70 | * Your WordFilter object will be instantiated and called as such: 71 | * WordFilter obj = new WordFilter(words); 72 | * int param_1 = obj.f(prefix,suffix); 73 | */ 74 | -------------------------------------------------------------------------------- /Java/RectangleOverlap.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isRectangleOverlap(int[] rec1, int[] rec2) { 3 | return ( 4 | overlap(rec1[0], rec1[2], rec2[0], rec2[2]) && 5 | overlap(rec1[1], rec1[3], rec2[1], rec2[3]) 6 | ); 7 | } 8 | 9 | public boolean overlap(int ax1, int ax2, int bx1, int bx2) { 10 | if (ax2 <= bx1 || bx2 <= ax1) return false; 11 | return true; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Java/RegularExpressionMatching.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isMatch(String s, String p) { 3 | if(s.matches(p)){ 4 | return true; 5 | } 6 | return false; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Java/RemoveLetterToEqualizeFrequency.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean equalFrequency(String word) { 3 | int[] map = new int[26]; 4 | for (char ch: word.toCharArray()) map[ch-'a']++; 5 | // brute force too many edge cases for optimised solution 6 | for (int i = 0; i < map.length; ++i) { 7 | if (map[i] == 0) continue; 8 | map[i]--; 9 | int p = 0; 10 | boolean f = true; 11 | for (int v: map) { 12 | if (v == 0) continue; 13 | if (p == 0) p = v; 14 | else if (p != v) { 15 | f = false; 16 | break; 17 | } 18 | } 19 | map[i]++; 20 | if (f) return true; 21 | } 22 | return false; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Java/ReverseInteger: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int reverse(int x) { 3 | int ans=0; 4 | int q=1; 5 | while(x!=0){ 6 | int r=x%10; 7 | if(ans > Integer.MAX_VALUE/10 || ans< Integer.MIN_VALUE/10) return 0; 8 | ans=(ans*10) +r; 9 | 10 | x/=10; 11 | } 12 | return ans; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Java/RomanToInteger.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | private final Map map = Map.of( 4 | 'I', 1, 5 | 'V', 5, 6 | 'X', 10, 7 | 'L', 50, 8 | 'C', 100, 9 | 'D', 500, 10 | 'M', 1000 11 | ); 12 | 13 | public int romanToInt(String s) { 14 | int result = map.get(s.charAt(s.length() - 1)); 15 | int last = result; 16 | for (int i = s.length() - 2; i >= 0; i--) { 17 | int curInt = map.get(s.charAt(i)); 18 | if (curInt < last) 19 | result -= curInt; 20 | else 21 | result += curInt; 22 | last = curInt; 23 | } 24 | 25 | return result; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/RotateImage.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[][] matrix) { 3 | int n = matrix.length; 4 | for (int i = 0; i < (n + 1) / 2; i ++) { 5 | for (int j = 0; j < n / 2; j++) { 6 | int temp = matrix[n - 1 - j][i]; 7 | matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1]; 8 | matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 -i]; 9 | matrix[j][n - 1 - i] = matrix[i][j]; 10 | matrix[i][j] = temp; 11 | } 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Java/RunningSum1DArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] runningSum(int[] nums) { 3 | int ans[]=new int[nums.length]; 4 | ans[0]=nums[0]; 5 | for(int i=1;i 1) { 11 | a = a.next; 12 | } 13 | mv = a.next; 14 | a.next = null; 15 | i++; 16 | } 17 | return ans; 18 | } 19 | private int len(ListNode h) { 20 | int n = 0; 21 | while (h != null) { 22 | n++; 23 | h = h.next; 24 | } 25 | return n; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/String_to_Integer_(atoi).java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int myAtoi(String str) { 3 | boolean isNeg = false; 4 | int i = 0; 5 | while(i < str.length() && str.charAt(i) == ' ') i++; 6 | if(i >= str.length()) return 0; 7 | if(str.charAt(i) == '-') {isNeg = true; i++;} 8 | else if(str.charAt(i) == '+') i++; 9 | while(i < str.length() && str.charAt(i) == '0') i++; 10 | int j = i; 11 | while (j < str.length() && Character.isDigit(str.charAt(j))) j++; 12 | if (j == i) return 0; 13 | int maxlen = (int)(Math.log10(Integer.MAX_VALUE)) + 1; 14 | int value = 0; 15 | if(j-i > maxlen){ 16 | if(isNeg) return Integer.MIN_VALUE; 17 | return Integer.MAX_VALUE; 18 | } 19 | else if(j - i < maxlen){ 20 | value = Integer.parseInt(str.substring(i,j)); 21 | if(isNeg) value*=-1; 22 | } 23 | else { 24 | long val = Long.parseLong(str.substring(i,j)); 25 | if(isNeg) val*=-1; 26 | if(val < Integer.MIN_VALUE) return Integer.MIN_VALUE; 27 | if(val > Integer.MAX_VALUE) return Integer.MAX_VALUE; 28 | value = (int) val; 29 | } 30 | return value; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Java/Two Sum.java: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/two-sum/ 2 | 3 | class Solution { 4 | public int[] twoSum(int[] nums, int target) { 5 | if(2 > nums.length ||nums.length> 10000 || -1000000000> target || target> 1000000000 ){return null;} 6 | int[] ans=new int[2]; 7 | for (int i = 0; i < nums.length; i++) { 8 | for (int j = i+1; j < nums.length; j++) { 9 | if((target-nums[i])==nums[j]){ 10 | ans[0]=i; 11 | ans[1]=j; 12 | } 13 | } 14 | } 15 | return ans; 16 | } 17 | } -------------------------------------------------------------------------------- /Java/Ugly-Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isUgly(int num) { 3 | if(num == 0) return false; 4 | if(num == 1) return true; 5 | 6 | if(num % 2 == 0){ 7 | num = num / 2; 8 | return isUgly(num); 9 | } 10 | 11 | if(num % 3 == 0){ 12 | num=num / 3; 13 | return isUgly(num); 14 | } 15 | 16 | if(num % 5 == 0){ 17 | num = num / 5; 18 | return isUgly(num); 19 | } 20 | 21 | return false; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java/UniqueEmailAddresses.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numUniqueEmails(String[] emails) { 3 | Set s = new HashSet<>(); 4 | StringBuilder sb = new StringBuilder(); 5 | for (String em : emails) { 6 | int i = 0; 7 | while(em.charAt(i) != '@' && em.charAt(i) != '+') { 8 | if (em.charAt(i) != '.') sb.append(em.charAt(i)); 9 | i++; 10 | } 11 | while(em.charAt(i) != '@') i++; 12 | sb.append(em.substring(i)); 13 | s.add(sb.toString()); 14 | sb.delete(0,sb.length()); 15 | } 16 | return s.size(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Java/ValidAnagram.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | private static String sortString(String s) { 5 | char[] c = s.toCharArray(); 6 | Arrays.sort(c); 7 | return new String(c); 8 | } 9 | 10 | public boolean isAnagram(String s, String t) { 11 | return sortString(s).equals(sortString(t)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Java/WaterAndJugProblem.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private int jug1Capacity; 3 | private int jug2Capacity; 4 | public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) { 5 | if(jug1Capacity == targetCapacity || jug2Capacity == targetCapacity) { 6 | return true; 7 | } 8 | if(jug1Capacity + jug2Capacity < targetCapacity) { 9 | return false; 10 | } 11 | this.jug1Capacity = jug1Capacity; 12 | this.jug2Capacity = jug2Capacity; 13 | 14 | final Queue q = new ArrayDeque<>(); 15 | final Set visited = new HashSet<>(); 16 | q.offer(new Jugs(0, 0)); 17 | 18 | while(!q.isEmpty()) { 19 | // remove mark* work add* 20 | final Jugs curr = q.poll(); 21 | if(visited.contains(curr)) { 22 | continue; 23 | } 24 | visited.add(curr); 25 | if(curr.jug1 + curr.jug2 == targetCapacity 26 | || curr.jug1 == targetCapacity 27 | || curr.jug2 == targetCapacity) { 28 | return true; 29 | } 30 | final List possibleNextStates = getPossibleNextStates(curr); 31 | for(final Jugs nextState : possibleNextStates) { 32 | if(visited.contains(nextState)) { 33 | continue; 34 | } 35 | q.offer(nextState); 36 | } 37 | } 38 | return false; 39 | } 40 | 41 | private List getPossibleNextStates(final Jugs curr) { 42 | final List states = new ArrayList<>(); 43 | states.add(new Jugs(0, curr.jug2)); // empty first jug 44 | states.add(new Jugs(curr.jug1, 0)); // empty second jug 45 | states.add(new Jugs(jug1Capacity, curr.jug2)); // fill first jug 46 | states.add(new Jugs(curr.jug1, jug2Capacity)); // fill second jug 47 | // transer current jug1 into jug2 48 | { 49 | final int jug1 = Math.max(0, curr.jug1 - (jug2Capacity - curr.jug2)); 50 | final int jug2 = Math.min(curr.jug1 + curr.jug2, jug2Capacity); 51 | states.add(new Jugs(jug1, jug2)); 52 | } 53 | // transer current jug2 into jug1 54 | { 55 | final int jug1 = Math.min(curr.jug1 + curr.jug2, jug1Capacity); 56 | final int jug2 = Math.max(0, curr.jug2 - (jug1Capacity - curr.jug1)); 57 | states.add(new Jugs(jug1, jug2)); 58 | } 59 | return states; 60 | } 61 | 62 | private static final class Jugs { 63 | private final int jug1; 64 | private final int jug2; 65 | 66 | private Jugs(final int jug1, final int jug2) { 67 | this.jug1 = jug1; 68 | this.jug2 = jug2; 69 | } 70 | 71 | public int hashCode(){ 72 | return Objects.hash(jug1, jug2); 73 | } 74 | public boolean equals(final Object o) { 75 | if(o == null) { 76 | return false; 77 | } 78 | final Jugs jugs = (Jugs) o; 79 | return this.jug1 == jugs.jug1 && this.jug2 == jugs.jug2; 80 | } 81 | public String toString() { 82 | return "(" + jug1 + "," + jug2 + ")"; 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /Java/ZigzagConversion.java: -------------------------------------------------------------------------------- 1 | public class Solution{ 2 | 3 | public String convert(String s, int numRows) { 4 | if (s == null || s.isEmpty() || numRows <= 0) { 5 | return ""; 6 | } 7 | if (numRows == 1) { 8 | return s; 9 | } 10 | StringBuilder result = new StringBuilder(); 11 | int step = 2 * numRows - 2; 12 | for (int i = 0; i < numRows; i++) { 13 | for (int j = i; j < s.length(); j += step) { 14 | result.append(s.charAt(j)); 15 | if (i != 0 && i != numRows - 1 && (j + step - 2 * i) < s.length()) { 16 | result.append(s.charAt(j + step - 2 * i)); 17 | } 18 | } 19 | } 20 | return result.toString(); 21 | } 22 | } -------------------------------------------------------------------------------- /Java/findallduplicatesinanarray.java: -------------------------------------------------------------------------------- 1 | class findallduplicatesinanarray { 2 | public List findDuplicates(int[] nums) { 3 | List list=new ArrayList(); 4 | HashSet hm = new HashSet(); 5 | for(int i=0;inums2[index2]){ 29 | nums[i] = nums2[index2]; 30 | index2 ++; 31 | }else{ 32 | nums[i] = nums1[index1]; 33 | index1 ++; 34 | } 35 | } 36 | } 37 | result = (nums[leftIndex] + nums[rightIndex])/2.0; 38 | return result; 39 | 40 | } 41 | 42 | 43 | 44 | public static void main(String[] args) { 45 | Solution solution = new Solution(); 46 | System.out.println(solution.findMedianSortedArrays(new int[]{},new int[]{3,4}));; 47 | } 48 | } -------------------------------------------------------------------------------- /Java/mergingTwoTrees.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { 3 | if (t1 == null) 4 | return t2; 5 | if (t2 == null) 6 | return t1; 7 | t1.val += t2.val; 8 | t1.left = mergeTrees(t1.left, t2.left); 9 | t1.right = mergeTrees(t1.right, t2.right); 10 | return t1; 11 | 12 | } 13 | } -------------------------------------------------------------------------------- /Java/peakIndexInAMountainArray.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/peak-index-in-a-mountain-array/ 2 | 3 | public class peakIndexInAMountainArray { 4 | 5 | static int peakIndexInMountainArray(int[] arr) { 6 | int startIndex = 0; 7 | int endIndex = arr.length - 1; 8 | 9 | while (startIndex < endIndex) { 10 | int middleIndex = startIndex + (endIndex - startIndex) / 2; 11 | if (arr[middleIndex] > arr[middleIndex + 1]) { 12 | endIndex = middleIndex; 13 | } else { 14 | startIndex = middleIndex + 1; 15 | } 16 | } 17 | return startIndex; 18 | } 19 | 20 | public static void main(String[] args) { 21 | int[] arr = {-3,-2,0, 1,2,1, 0,-2,-3}; 22 | System.out.println(peakIndexInMountainArray(arr)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Java/remove-element.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeElement(int[] nums, int val) { 3 | int n = 0; 4 | for (int m = 0; m < nums.length; m++) { 5 | if (nums[m] != val) { 6 | nums [n]=nums[m]; 7 | n++; 8 | } 9 | } 10 | return n; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Java/reverseWords.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Reverse Words in a String 3 | * Medium 4 | * 5 | * Given an input string, reverse the string word by word 6 | 7 | Example 1: 8 | 9 | Input: "the sky is blue" 10 | Output: "blue is sky the" 11 | 12 | Example 2: 13 | 14 | Input: " hello world! " 15 | Output: "world! hello" 16 | Explanation: Your reversed string should not contain leading or trailing spaces. 17 | * 18 | * Runtime: 7 ms 19 | * Memory Usage: 41.8 MB 20 | * 21 | */ 22 | class Solution { 23 | public String reverseWords(String s) { 24 | s = s.trim(); 25 | 26 | String [] strArr = s.split(" "); 27 | 28 | String ans = ""; 29 | 30 | for (int i=strArr.length-1; i>=0; i--) { 31 | if (strArr[i].isEmpty()){ 32 | continue; 33 | } 34 | ans += strArr[i].trim() + " "; 35 | } 36 | 37 | return ans.trim(); 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /Java/reverse_integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int reverse(int x) { 3 | int newValue = 0; 4 | while (x!=0) { 5 | int mod = x % 10; 6 | newValue = newValue*10 + mod; 7 | x /=10; 8 | } 9 | return newValue; 10 | } 11 | } -------------------------------------------------------------------------------- /Java/word-ladder.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: 3 | Only one letter can be changed at a time. 4 | Each transformed word must exist in the word list. 5 | Note: 6 | Return 0 if there is no such transformation sequence. 7 | All words have the same length. 8 | All words contain only lowercase alphabetic characters. 9 | You may assume no duplicates in the word list. 10 | You may assume beginWord and endWord are non-empty and are not the same. 11 | Problem Link: https://leetcode.com/problems/word-ladder/ 12 | It is a popular interview program which is based on BFS 13 | */ 14 | import java.util.*; 15 | class Solution { 16 | public int ladderLength(String beginWord, String endWord, List wordList) { 17 | HashSet hs=new HashSet<>(wordList); 18 | if(!hs.contains(endWord)) 19 | { 20 | return 0; 21 | } 22 | int steps=1; 23 | Queue q=new LinkedList<>(); 24 | q.add(beginWord); 25 | while(!q.isEmpty()) 26 | { 27 | int count=q.size(); 28 | for(int i=0;i a - b); 4 | // Length of the array 5 | const n = nums.length; 6 | // Resultant list 7 | const triplets = []; 8 | // Loop for each element of the array 9 | for (let i = 0; i < n; i++) { 10 | // Skip the duplicates 11 | if (i > 0 && nums[i] === nums[i - 1]) { 12 | continue; 13 | } 14 | // Left and right pointers 15 | let j = i + 1; 16 | let k = n - 1; 17 | // Loop for all the remaining pairs 18 | while (j < k) { 19 | if (nums[i] + nums[j] + nums[k] === 0) { 20 | triplets.push([nums[i], nums[j], nums[k]]); 21 | j++; 22 | // Never let j refer to the same value twice (in an output) to avoid duplicates 23 | while (j < k && nums[j] === nums[j - 1]) { 24 | j++; 25 | } 26 | } else if (nums[i] + nums[j] + nums[k] < 0) { 27 | j++; 28 | } else { 29 | k--; 30 | } 31 | } 32 | } 33 | return triplets; 34 | }; 35 | -------------------------------------------------------------------------------- /JavaScript/FunctionComposite.js: -------------------------------------------------------------------------------- 1 | var compose = function (functions) { 2 | 3 | return function (x) { 4 | return functions.reduceRight((acc, fn) => { 5 | return fn(acc); 6 | }, x); 7 | } 8 | 9 | }; 10 | -------------------------------------------------------------------------------- /JavaScript/MergeTwoSortedLists.js: -------------------------------------------------------------------------------- 1 | var mergeTwoLists = function (l1, l2) { 2 | let newList = new ListNode(0); 3 | let headOfNewList = newList; 4 | while (l1 != null && l2 != null) { 5 | if (l1.val < l2.val) { 6 | newList.next = l1; 7 | l1 = l1.next; 8 | } else { 9 | newList.next = l2; 10 | l2 = l2.next; 11 | } 12 | newList = newList.next; 13 | } 14 | if (l1 == null) { 15 | newList.next = l2; 16 | } 17 | else { 18 | newList.next = l1; 19 | } 20 | return headOfNewList.next; 21 | }; 22 | -------------------------------------------------------------------------------- /JavaScript/RemoveElement.js: -------------------------------------------------------------------------------- 1 | var removeElement = function (nums, val) { 2 | let j = 0; 3 | for (let i = 0; i < nums.length; i++) { 4 | if (nums[i] !== val) { 5 | nums[j++] = nums[i]; 6 | } 7 | } 8 | 9 | return j; 10 | }; 11 | -------------------------------------------------------------------------------- /JavaScript/ValidParentheses.js: -------------------------------------------------------------------------------- 1 | var isValid = function (inputString) { 2 | let expectedBrackets = []; 3 | 4 | for (let letter = 0; letter < inputString.length; letter++) { 5 | if (inputString[letter] == '{') { 6 | expectedBrackets.push('}'); 7 | } else if (inputString[letter] == '[') { 8 | expectedBrackets.push(']'); 9 | } else if (inputString[letter] == '(') { 10 | expectedBrackets.push(')'); 11 | } 12 | else if (expectedBrackets.pop() !== inputString[letter]) { 13 | return false; 14 | } 15 | } 16 | 17 | return !expectedBrackets.length; 18 | }; 19 | -------------------------------------------------------------------------------- /JavaScript/ValidSudoku.js: -------------------------------------------------------------------------------- 1 | var isValidSudoku = function(board) { 2 | var map = {}; 3 | var tmp = 0; 4 | for (var i = 0; i < 9; i++) { 5 | for (var j = 0; j < 9; j++) { 6 | tmp = board[i][j]; 7 | if (tmp === '.') continue; 8 | if (map['i' + i + tmp] || map['j' + j + tmp] || map['b' + Math.floor(i / 3) + Math.floor(j / 3) + tmp]) return false; 9 | map['i' + i + tmp] = 1; 10 | map['j' + j + tmp] = 1; 11 | map['b' + Math.floor(i / 3) + Math.floor(j / 3) + tmp] = 1; 12 | } 13 | } 14 | return true; 15 | }; 16 | -------------------------------------------------------------------------------- /JavaScript/array-prototype-last.js: -------------------------------------------------------------------------------- 1 | // Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1. 2 | 3 | Array.prototype.last = function () { 4 | if (this.length === 0) { 5 | return -1; 6 | } 7 | return this[this.length - 1]; 8 | }; -------------------------------------------------------------------------------- /JavaScript/counter.js: -------------------------------------------------------------------------------- 1 | // Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc). 2 | var createCounter = function (n) { 3 | 4 | let count = n; 5 | 6 | return function () { 7 | return count++; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /JavaScript/divTwoInt.js: -------------------------------------------------------------------------------- 1 | var divide = function (dividend, divisor) { 2 | let res = 0; 3 | let limit = 2147483648; 4 | let s = divisor > 0 ? 1 : -1; 5 | let s1 = dividend > 0 ? 1 : -1; 6 | 7 | let sum = Math.floor(Math.abs(dividend) / Math.abs(divisor)); 8 | if (sum == limit) { 9 | res = sum * s * s1 < 0 ? -(2 ** 31) : 2 ** 31 - 1; 10 | } else { 11 | res = sum < limit ? sum * s * s1 : 2147483647; 12 | } 13 | 14 | return res; 15 | }; 16 | -------------------------------------------------------------------------------- /JavaScript/palindrome-number.js: -------------------------------------------------------------------------------- 1 | var isPalindrome = function(x) { 2 | // Base condition 3 | if (x < 0) { 4 | return false; 5 | } 6 | // Store the number in a variable 7 | let number = x; 8 | // This will store the reverse of the number 9 | let reverse = 0; 10 | while (number > 0) { 11 | reverse = reverse * 10 + number % 10; 12 | number = parseInt(number / 10); 13 | } 14 | return x === reverse; 15 | }; 16 | -------------------------------------------------------------------------------- /JavaScript/reverse-integer.js: -------------------------------------------------------------------------------- 1 | var reverse = function (x) { 2 | let isNegative = false; 3 | if (x < 0) { 4 | isNegative = true; 5 | x = -x; 6 | } 7 | let reverse = 0; 8 | while (x > 0) { 9 | reverse = reverse * 10 + x % 10; 10 | x = parseInt(x / 10); 11 | } 12 | if (reverse >= Math.pow(2, 31) - 1 || reverse <= Math.pow(-2, 31)) { 13 | return 0; 14 | } 15 | return isNegative ? -reverse : reverse; 16 | }; 17 | -------------------------------------------------------------------------------- /JavaScript/sleep.js: -------------------------------------------------------------------------------- 1 | // Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value. 2 | 3 | 4 | async function sleep(millis) { 5 | return new Promise(resolve => { 6 | setTimeout(resolve, millis); 7 | }); 8 | } -------------------------------------------------------------------------------- /JavaScript/two-sum.js: -------------------------------------------------------------------------------- 1 | var twoSum = function (nums, target) { 2 | // Array to store the result 3 | result = []; 4 | // Map to store the difference and its index 5 | index_map = new Map(); 6 | // Loop for each element in the array 7 | for (let i = 0; i < nums.length; i++) { 8 | let difference = target - nums[i]; 9 | if (index_map.has(difference)) { 10 | result[0] = i; 11 | result[1] = index_map.get(difference); 12 | break; 13 | } else { 14 | index_map.set(nums[i], i); 15 | } 16 | } 17 | return result; 18 | }; 19 | -------------------------------------------------------------------------------- /JavaScript/valid-parentheses.js: -------------------------------------------------------------------------------- 1 | var isValid = function (s) { 2 | // Stack to store left symbols 3 | const leftSymbols = []; 4 | // Loop for each character of the string 5 | for (let i = 0; i < s.length; i++) { 6 | // If left symbol is encountered 7 | if (s[i] === '(' || s[i] === '{' || s[i] === '[') { 8 | leftSymbols.push(s[i]); 9 | } 10 | // If right symbol is encountered 11 | else if (s[i] === ')' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '(') { 12 | leftSymbols.pop(); 13 | } else if (s[i] === '}' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '{') { 14 | leftSymbols.pop(); 15 | } else if (s[i] === ']' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '[') { 16 | leftSymbols.pop(); 17 | } 18 | // If none of the valid symbols is encountered 19 | else { 20 | return false; 21 | } 22 | } 23 | return leftSymbols.length === 0; 24 | }; 25 | -------------------------------------------------------------------------------- /Kotlin/10. Regular Expression Matching.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun isMatch(s: String, p: String): Boolean { 3 | val rows = s.length 4 | val columns = p.length 5 | if (rows == 0 && columns == 0) { 6 | return true 7 | } else if (columns == 0) { 8 | return false 9 | } 10 | val dp = Array(rows + 1) { BooleanArray(columns + 1) } 11 | dp[0][0] = true 12 | (2 until columns + 1) 13 | .filter { p[it - 1] == '*' } 14 | .forEach { dp[0][it] = dp[0][it - 2] } 15 | (1 until rows + 1).forEach { i -> 16 | (1 until columns + 1).forEach { j -> 17 | if (s[i - 1] == p[j - 1] || p[j - 1] == '.') { 18 | dp[i][j] = dp[i - 1][j - 1] 19 | } else if (j > 1 && p[j - 1] == '*') { 20 | dp[i][j] = dp[i][j - 2] 21 | if (p[j - 2] == '.' || p[j - 2] == s[i - 1]) { 22 | dp[i][j] = dp[i][j] or dp[i - 1][j] 23 | } 24 | } 25 | } 26 | } 27 | return dp[rows][columns] 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Kotlin/22. Generate Parentheses.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun generateParenthesis(n: Int): List { 3 | val result: MutableList = ArrayList() 4 | generateParenthesis(result, "", 0, 0, n) 5 | return result 6 | } 7 | 8 | private fun generateParenthesis( 9 | result: MutableList, 10 | s: String, 11 | open: Int, 12 | close: Int, 13 | n: Int 14 | ) { 15 | if (open == n && close == n) { 16 | result.add(s) 17 | return 18 | } 19 | if (open < n) { 20 | generateParenthesis(result, "$s(", open + 1, close, n) 21 | } 22 | if (close < open) { 23 | generateParenthesis(result, "$s)", open, close + 1, n) 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Kotlin/32. Longest Valid Parentheses.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun longestValidParentheses(s: String): Int { 3 | var count = 0 4 | var left = 0 5 | var right = 0 6 | s.forEach { element -> 7 | when (element) { 8 | '(' -> left++ 9 | ')' -> right++ 10 | } 11 | if (left == right) { 12 | count = count.coerceAtLeast(left + right) 13 | } 14 | if (right > left) { 15 | right = 0 16 | left = 0 17 | } 18 | } 19 | right = 0 20 | left = 0 21 | (s.length - 1 downTo 0).forEach { i -> 22 | when (s[i]) { 23 | '(' -> left++ 24 | ')' -> right++ 25 | } 26 | if (left == right) { 27 | count = count.coerceAtLeast(left + right) 28 | } 29 | if (left > right) { 30 | right = 0 31 | left = 0 32 | } 33 | } 34 | return count 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Kotlin/4. Median of Two Sorted Arrays.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { 3 | if (nums1.size > nums2.size) { 4 | return findMedianSortedArrays(nums2, nums1) 5 | } 6 | val m = nums1.size 7 | val n = nums2.size 8 | var start = 0 9 | var end = m 10 | while (start <= end) { 11 | val partitionNums1 = (start + end) / 2 12 | val partitionNums2 = (m + n + 1) / 2 - partitionNums1 13 | val maxLeftNums1 = if (partitionNums1 == 0) Int.MIN_VALUE else nums1[partitionNums1 - 1] 14 | val minRightNums1 = if (partitionNums1 == m) Int.MAX_VALUE else nums1[partitionNums1] 15 | val maxLeftNums2 = if (partitionNums2 == 0) Int.MIN_VALUE else nums2[partitionNums2 - 1] 16 | val minRightNums2 = if (partitionNums2 == n) Int.MAX_VALUE else nums2[partitionNums2] 17 | if (maxLeftNums1 <= minRightNums2 && maxLeftNums2 <= minRightNums1) { 18 | return if ((m + n) % 2 == 0) { 19 | (maxLeftNums1.coerceAtLeast(maxLeftNums2) + minRightNums1.coerceAtMost( 20 | minRightNums2 21 | )) / 2.0 22 | } else { 23 | maxLeftNums1.coerceAtLeast(maxLeftNums2).toDouble() 24 | } 25 | } else if (maxLeftNums1 > minRightNums2) { 26 | end = partitionNums1 - 1 27 | } else { 28 | start = partitionNums1 + 1 29 | } 30 | } 31 | throw IllegalArgumentException() 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Kotlin/reverse-integer.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun reverse(x: Int): Int { 3 | var final = 0 4 | var num = x 5 | while (num != 0) { 6 | if (Math.abs(final) > Int.MAX_VALUE/10) return 0 7 | 8 | final = final*10 + num % 10 9 | num /= 10 10 | } 11 | return final 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Kotlin/two-sum.kt: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fun twoSum(nums: IntArray, target: Int): IntArray { 3 | for (n in 0 until nums.size) { 4 | for (m in n + 1 until nums.size) { 5 | if (nums[n] + nums[m] == target) { 6 | return intArrayOf(n, m) 7 | } 8 | } 9 | } 10 | 11 | throw IllegalArgumentException("No feasible solution possible") 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Mysql/Combine Two Tables: -------------------------------------------------------------------------------- 1 | SELECT FirstName, LastName, City, State FROM Person LEFT JOIN Address ON Person.PersonId=Address.PersonId 2 | -------------------------------------------------------------------------------- /Mysql/Customers Who Never Order: -------------------------------------------------------------------------------- 1 | select Customers.Name 'Customers' from Customers left join Orders ON Customers.Id = Orders.CustomerId WHERE Orders.CustomerId is NULL 2 | -------------------------------------------------------------------------------- /Mysql/Employees Earning More Than Their Managers: -------------------------------------------------------------------------------- 1 | SELECT e.Name AS Employee FROM Employee AS e JOIN Employee AS m ON e.ManagerId = m.Id 2 | WHERE e.Salary > m.Salary; 3 | -------------------------------------------------------------------------------- /Mysql/Second Highest Salary: -------------------------------------------------------------------------------- 1 | SELECT MAX(salary) AS SecondHighestSalary 2 | FROM employee 3 | WHERE salary < (SELECT MAX(salary) 4 | FROM employee); 5 | -------------------------------------------------------------------------------- /Mysql/classes-more-than-5-students: -------------------------------------------------------------------------------- 1 | select class from courses group by class having count(distinct student)>=5 2 | ; 3 | -------------------------------------------------------------------------------- /Mysql/consecutive-numbers: -------------------------------------------------------------------------------- 1 | SELECT Score, 2 | DENSE_RANK() OVER (ORDER BY Score DESC) as 'Rank' 3 | FROM Scores; 4 | -------------------------------------------------------------------------------- /Mysql/department-highest-salary: -------------------------------------------------------------------------------- 1 | SELECT 2 | Department.name AS 'Department', 3 | Employee.name AS 'Employee', 4 | Salary 5 | FROM 6 | Employee 7 | JOIN 8 | Department ON Employee.DepartmentId = Department.Id 9 | WHERE 10 | (Employee.DepartmentId , Salary) IN 11 | ( SELECT 12 | DepartmentId, MAX(Salary) 13 | FROM 14 | Employee 15 | GROUP BY DepartmentId 16 | ) 17 | ; 18 | -------------------------------------------------------------------------------- /Mysql/department-top-three-salaries: -------------------------------------------------------------------------------- 1 | SELECT 2 | d.Name AS 'Department', e1.Name AS 'Employee', e1.Salary 3 | FROM 4 | Employee e1 5 | JOIN 6 | Department d ON e1.DepartmentId = d.Id 7 | WHERE 8 | 3 > (SELECT 9 | COUNT(DISTINCT e2.Salary) 10 | FROM 11 | Employee e2 12 | WHERE 13 | e2.Salary > e1.Salary 14 | AND e1.DepartmentId = e2.DepartmentId 15 | ) 16 | ; 17 | -------------------------------------------------------------------------------- /Mysql/duplicate emails: -------------------------------------------------------------------------------- 1 | SELECT Email FROM Person GROUP BY Email HAVING COUNT(Email) > 1 2 | -------------------------------------------------------------------------------- /Mysql/duplicate-emails: -------------------------------------------------------------------------------- 1 | select Email from Person group by Email having count(Email) > 1; 2 | -------------------------------------------------------------------------------- /Mysql/human-traffic-of-stadium: -------------------------------------------------------------------------------- 1 | WITH stadium_data AS 2 | ( 3 | SELECT s.id, 4 | s.visit_date, 5 | s.id - ROW_NUMBER() OVER(ORDER BY s.id ASC) AS id_group, 6 | s.people 7 | FROM stadium s 8 | WHERE s.people >= 100 9 | ) 10 | 11 | 12 | SELECT s.id, 13 | s.visit_date, 14 | s.people 15 | FROM stadium_data s 16 | WHERE s.id_group IN 17 | ( 18 | SELECT s.id_group 19 | FROM stadium_data s 20 | GROUP BY s.id_group 21 | HAVING COUNT(s.id) >= 3 22 | ); 23 | -------------------------------------------------------------------------------- /Mysql/nth-highest-salary: -------------------------------------------------------------------------------- 1 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 2 | BEGIN 3 | declare off int; 4 | set off = N - 1; 5 | RETURN ( 6 | select (select distinct Salary from Employee order by Salary desc limit 1 offset off) 7 | ); 8 | END 9 | -------------------------------------------------------------------------------- /Mysql/rank-scores: -------------------------------------------------------------------------------- 1 | SELECT Score, 2 | DENSE_RANK() OVER (ORDER BY Score DESC) as 'Rank' 3 | FROM Scores; 4 | -------------------------------------------------------------------------------- /Mysql/rising-temperature: -------------------------------------------------------------------------------- 1 | SELECT weather.id AS 'Id' FROM weather JOIN 2 | weather w ON DATEDIFF(weather.recordDate, w.recordDate) = 1 3 | AND weather.Temperature > w.Temperature 4 | ; 5 | -------------------------------------------------------------------------------- /Mysql/swap-salary: -------------------------------------------------------------------------------- 1 | UPDATE salary SET sex = CASE sex WHEN 'm' THEN 'f' ELSE 'm' END; 2 | -------------------------------------------------------------------------------- /Mysql/trips-and-users: -------------------------------------------------------------------------------- 1 | SELECT Request_at as Day, 2 | COALESCE(ROUND(SUM(CASE WHEN status LIKE 'cancelled%' THEN TRUE END )/COUNT(*),2),0) 3 | AS 'Cancellation Rate' 4 | FROM trips t 5 | WHERE Request_at >= '2013-10-01' and Request_at <= '2013-10-03' 6 | AND Client_Id IN(SELECT users_id FROM users WHERE banned = 'No') 7 | AND Driver_Id IN(SELECT users_id FROM users WHERE banned = 'No') 8 | GROUP BY Request_at 9 | ORDER BY Day; 10 | -------------------------------------------------------------------------------- /Python/3SumClosest.py: -------------------------------------------------------------------------------- 1 | # Problem Link: https://leetcode.com/problems/3sum-closest/submissions/ 2 | 3 | class Solution: 4 | def threeSumClosest(self, num: List[int], target: int) -> int: 5 | num.sort() 6 | error = float("infinity") 7 | if len(num)<3: 8 | return 0 9 | for i in range(0, len(num)-2): 10 | begin = i+1 11 | end = len(num)-1 12 | while begin target: 17 | end -= 1 18 | else: 19 | begin += 1 20 | return solution 21 | -------------------------------------------------------------------------------- /Python/AddTwoNumbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addTwoNumbers(self, l1, l2 ,c = 0): 3 | """ 4 | :type l1: ListNode 5 | :type l2: ListNode 6 | :rtype: ListNode 7 | """ 8 | val = l1.val + l2.val + c 9 | c = val // 10 10 | ret = ListNode(val % 10 ) 11 | 12 | if (l1.next != None or l2.next != None or c != 0): 13 | if l1.next == None: 14 | l1.next = ListNode(0) 15 | if l2.next == None: 16 | l2.next = ListNode(0) 17 | ret.next = self.addTwoNumbers(l1.next,l2.next,c) 18 | return ret 19 | -------------------------------------------------------------------------------- /Python/Binary_Search_Tree_Traversals.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | class TreeNode(object): 3 | def __init__(self, val=0, left=None, right=None): 4 | self.val = val 5 | self.left = left 6 | self.right = right 7 | 8 | #Binary Search Tree(BST) Inorder Traversal 9 | 10 | 11 | class Solution(object): 12 | def inorderTraversal(self, root): 13 | lis = [] 14 | 15 | def ino(x): 16 | if x is None: 17 | return 18 | ino(x.left) 19 | lis.append(x.val) 20 | ino(x.right) 21 | 22 | ino(root) 23 | return lis 24 | 25 | 26 | #Binary Search Tree(BST) PreOrder Traversal 27 | 28 | class Solution(object): 29 | def preorderTraversal(self, root): 30 | lis = [] 31 | 32 | def fic(x): 33 | if x is None: 34 | return 35 | lis.append(x.val) 36 | fic(x.left) 37 | fic(x.right) 38 | 39 | fic(root) 40 | return lis 41 | 42 | 43 | #Binary Search Tree(BST) PostOrder Traversal 44 | 45 | class Solution(object): 46 | def postorderTraversal(self, root): 47 | lis = [] 48 | 49 | def pos(x): 50 | if x is None: 51 | return 52 | pos(x.left) 53 | pos(x.right) 54 | lis.append(x.val) 55 | 56 | pos(root) 57 | return lis 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /Python/BreakAPalindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def breakPalindrome(self, palindrome: str) -> str: 3 | length = len(palindrome) 4 | palindrome = list(palindrome) 5 | if length <= 1: 6 | return '' 7 | for i in range(int(length/2)): 8 | if palindrome[i] != 'a': 9 | palindrome[i] = 'a' 10 | return (''.join(palindrome)) 11 | palindrome[length-1] = 'b' 12 | return (''.join(palindrome)) 13 | -------------------------------------------------------------------------------- /Python/ContinuousSubarraySum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkSubarraySum(self, nums: List[int], k: int) -> bool: 3 | h = {0: -1} 4 | s = 0 5 | for i, n in enumerate(nums): 6 | s = (s + n) % k 7 | if s not in h: 8 | h[s] = i 9 | elif i - h[s] >= 2: 10 | return True 11 | return False 12 | -------------------------------------------------------------------------------- /Python/DecodeWays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numDecodings(self, s: str) -> int: 3 | dp = [0] * (len(s) + 1) 4 | dp[0] = 1 5 | for i in range(1, len(dp)): 6 | if int(s[i-1]) != 0: 7 | dp[i] = dp[i-1] 8 | if i != 1 and '09' < s[i-2:i] < '27': 9 | dp[i] += dp[i-2] 10 | return dp[-1] 11 | -------------------------------------------------------------------------------- /Python/EarliestPossibleDayOfBloom.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int: 3 | a = list(sorted(list(zip(plantTime, growTime)), key=lambda x: -x[1])) 4 | ans = s = 0 5 | for x, y in a: 6 | s += x 7 | ans = max(ans, s + y) 8 | return ans 9 | -------------------------------------------------------------------------------- /Python/GenParentheses.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | class Solution: 3 | def generateParenthesis(self, n: int) -> List[str]: 4 | dq = deque() 5 | dq.append(["(", 1, 0]) 6 | ans = [] 7 | while dq: 8 | comb, left, right = dq.popleft() 9 | if left == n and right == n: 10 | ans.append(comb) 11 | continue 12 | if left == right: 13 | dq.append([comb + "(", left + 1, right]) 14 | elif left == n: 15 | dq.append([comb + ")", left, right + 1]) 16 | else: 17 | dq.append([comb + "(", left + 1, right]) 18 | dq.append([comb + ")", left, right + 1]) 19 | 20 | return ans 21 | -------------------------------------------------------------------------------- /Python/Group_Anagrams.py: -------------------------------------------------------------------------------- 1 | def group_anagrams(strs: list[str]) -> list[list[str]]: 2 | 3 | dict = {} 4 | for word in strs: 5 | sortedword = "".join(sorted(word)) 6 | if sortedword not in dict: 7 | dict[sortedword] = [word] 8 | else: 9 | dict[sortedword].append(word) 10 | result = [] 11 | for item in dict.values(): 12 | result.append(item) 13 | return result 14 | -------------------------------------------------------------------------------- /Python/ImageOverlap.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int: 3 | h = collections.defaultdict(int) 4 | i1 = [] 5 | i2 = [] 6 | for i in range(len(img1)): 7 | for j in range(len(img1[0])): 8 | if img1[i][j]: 9 | i1.append((i, j)) 10 | if img2[i][j]: 11 | i2.append((i, j)) 12 | ans = 0 13 | for x in i1: 14 | for y in i2: 15 | z = (y[0] - x[0], y[1] - x[1]) 16 | h[z] += 1 17 | ans = max(ans, h[z]) 18 | return ans 19 | -------------------------------------------------------------------------------- /Python/IntegerReplacement.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def integerReplacement(self, n: int) -> int: 3 | count = 0 4 | while(n!=1): 5 | if n==3: 6 | count+=2 7 | return count 8 | while(n%2!=0): 9 | if n%4==3: 10 | n+=1 11 | else: 12 | n-=1 13 | count+=1 14 | while(n%2==0): 15 | n=n/2 16 | count+=1 17 | return count 18 | 19 | -------------------------------------------------------------------------------- /Python/LongestSubstring.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def lengthOfLongestSubstring(self, s): 3 | chars = {} 4 | L = len(s) 5 | start = 0 6 | max_len = 0 7 | for i in range(L): 8 | if s[i] in chars: 9 | max_len = max(max_len,i-start) 10 | start = max(start,chars[s[i]]+1) 11 | chars[s[i]] = i 12 | max_len = max(max_len,L-start) 13 | return max_len 14 | -------------------------------------------------------------------------------- /Python/MaximumPopulationYear.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maximumPopulation(self, logs): 3 | """ 4 | :type logs: List[List[int]] 5 | :rtype: int 6 | """ 7 | data = [] 8 | 9 | for log in logs: 10 | data.append((log[0],1)) 11 | data.append((log[1],-1)) 12 | 13 | population = history = year = 0 14 | 15 | data.sort() 16 | 17 | for i in data: 18 | population += i[1] 19 | if population > history: 20 | history = population 21 | year = i[0] 22 | 23 | return year 24 | -------------------------------------------------------------------------------- /Python/MedianTwoSortedArrays.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMedianSortedArrays(self, nums1, nums2): 3 | """ 4 | :type nums1: List[int] 5 | :type nums2: List[int] 6 | :rtype: float 7 | """ 8 | i1 = 0 9 | i2 = 0 10 | num1 = 0 11 | num2 = 0 12 | len1 = len(nums1) 13 | len2 = len(nums2) 14 | len4 = len1 + len2 15 | len3 = int(len4 / 2) + 1 16 | for x in range(len3): 17 | if len1 > i1 and len2 > i2: 18 | if nums1[i1] <= nums2[i2]: 19 | num1 = num2 20 | num2 = nums1[i1] 21 | i1 = i1 + 1 22 | else: 23 | num1 = num2 24 | num2 = nums2[i2] 25 | i2 = i2 + 1 26 | elif len1 > i1: 27 | num1 = num2 28 | num2 = nums1[i1] 29 | i1 = i1 + 1 30 | else: 31 | num1 = num2 32 | num2 = nums2[i2] 33 | i2 = i2 + 1 34 | 35 | if len4 % 2 == 0: 36 | return (num1 + num2)/2 37 | else: 38 | return float(num2) 39 | -------------------------------------------------------------------------------- /Python/MergeTwoListed.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 3 | if not l1: 4 | return l2 5 | if not l2: 6 | return l1 7 | if l1.val len(s): 14 | return False 15 | 16 | # 1. if second is * p[i+1] 17 | if j < len(p)-1 and p[j+1] == '*': 18 | # Zero means advance p[j+2] 19 | # one or more compare and advance if match 20 | return (self.match(s, i, p, j) and self.helper(s, i+1, p, j)) or self.helper(s, i, p, j+2) 21 | 22 | # 2. Match either same or '.' 23 | if self.match(s, i, p, j): 24 | return self.helper(s, i+1, p, j+1) 25 | 26 | # 3. No match or * 27 | return False 28 | 29 | def isMatch(self, s, p): 30 | """ 31 | :type s: str 32 | :type p: str 33 | :rtype: bool 34 | """ 35 | return self.helper(s, 0, p, 0) 36 | -------------------------------------------------------------------------------- /Python/RemoveDupFromSortedArray.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeDuplicates(self, nums): 3 | if nums == []: 4 | return 0 5 | 6 | current_element = nums[0] 7 | scan_index = 1 8 | fill_index = 1 9 | 10 | while scan_index < len(nums): 11 | if nums[scan_index] != current_element: 12 | nums[fill_index] = nums[scan_index] 13 | fill_index += 1 14 | current_element = nums[scan_index] 15 | scan_index += 1 16 | 17 | return fill_index 18 | -------------------------------------------------------------------------------- /Python/ReplaceAllDigitsWithCharacters.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def replaceDigits(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | ans = "" 8 | 9 | for i in range(len(s)): 10 | if ord(s[i])>96 and ord(s[i])<123: 11 | ans=ans+s[i] 12 | else: 13 | ans=ans+(chr(ord(s[i-1])+int(s[i]))) 14 | return ans 15 | -------------------------------------------------------------------------------- /Python/ReverseInteger.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverse(self, x): 3 | 4 | s = str(x) 5 | if s[0] == '-': 6 | s_reversed = '-'+s[:0:-1] 7 | else: 8 | s_reversed = s[::-1] 9 | 10 | solution = int(s_reversed) 11 | if solution > 2**31 or solution < -2**31: 12 | solution = 0 13 | 14 | return solution 15 | -------------------------------------------------------------------------------- /Python/RomanToInteger.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def romanToInt(self, s): 3 | output = 0 4 | for i in range(0,len(s)): 5 | if s[i] == 'M': 6 | output += 1000 7 | elif s[i] == 'D': 8 | output += 500 9 | elif s[i] == 'L': 10 | output += 50 11 | elif s[i] == 'V': 12 | output += 5 13 | elif s[i] == 'C': 14 | if i != len(s)-1 and (s[i+1] == 'M' or s[i+1] == 'D'): 15 | output -= 100 16 | else: 17 | output += 100 18 | elif s[i] == 'X': 19 | if i != len(s)-1 and (s[i+1] == 'C' or s[i+1] == 'L'): 20 | output -= 10 21 | else: 22 | output += 10 23 | elif s[i] == 'I': 24 | if i != len(s)-1 and (s[i+1] == 'X' or s[i+1] == 'V'): 25 | output -= 1 26 | else: 27 | output += 1 28 | 29 | return output 30 | -------------------------------------------------------------------------------- /Python/Rotate_Image.py: -------------------------------------------------------------------------------- 1 | def rotate(matrix: list[list[int]]) -> None: 2 | 3 | for i in range(len(matrix)): 4 | for j in range(i, len(matrix)): 5 | matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] 6 | for i in range(len(matrix)): 7 | left = 0 8 | right = len(matrix) - 1 9 | while left < right: 10 | matrix[i][left], matrix[i][right] = matrix[i][right], matrix[i][left] 11 | left += 1 12 | right -= 1 13 | -------------------------------------------------------------------------------- /Python/SetMismatch.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findErrorNums(self, nums: List[int]) -> List[int]: 3 | dic={} 4 | for i in range(1,len(nums)+1): 5 | dic[i]=0 6 | for n in nums: 7 | dic[n]+=1 8 | f1=int(list(dic.values()).index(2))+1 9 | f2=int(list(dic.values()).index(0))+1 10 | return[f1,f2] 11 | -------------------------------------------------------------------------------- /Python/ShortestPathInGridWithElim.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shortestPath(self, graph: List[List[int]], k: int) -> int: 3 | m, n = len(graph), len(graph[0]) 4 | if k >= m + n - 2: 5 | return m + n - 2 6 | dr = [ -1, 0, 1, 0] 7 | dc = [ 0, 1, 0, -1] 8 | q = collections.deque() 9 | q.append((0, 0, k)) 10 | s = set() 11 | s.add((0, 0, k)) 12 | 13 | ans = 0 14 | 15 | while q: 16 | for _ in range(len(q)): 17 | x, y, k = q.popleft() 18 | if x == m - 1 and y == n - 1: 19 | return ans 20 | for i in range(4): 21 | ax = x + dr[i] 22 | ay = y + dc[i] 23 | if ax < 0 or ay < 0 or ax == m or ay == n: 24 | continue 25 | ak = k - graph[x][y] 26 | _a = (ax, ay, ak) 27 | if ak >= 0 and _a not in s: 28 | q.append(_a) 29 | s.add(_a) 30 | ans += 1 31 | return -1 32 | -------------------------------------------------------------------------------- /Python/SingleNumber.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def singleNumber(self, nums): 3 | unique_nums = set(nums) 4 | for element in unique_nums: 5 | count = nums.count(element) 6 | if count == 1: 7 | return element 8 | -------------------------------------------------------------------------------- /Python/SortingTheSentence.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sortSentence(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | numbers = [int(i) for i in s if i.isdigit()] 8 | 9 | numbers.sort() 10 | 11 | s_split = s.split() 12 | 13 | n_s = [] 14 | 15 | for number in numbers: 16 | for word in s_split: 17 | if str(number) in word: 18 | word = "".join([i for i in word if not i.isdigit()]) 19 | n_s.append(word) 20 | 21 | return " ".join(n_s) 22 | 23 | -------------------------------------------------------------------------------- /Python/String2Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myAtoi(self, s: str) -> int: 3 | if not s.strip(): return 0 4 | r = s.strip()[0]*(s.strip()[0] in '+-') 5 | for x in s.strip()[len(r):].lstrip('0'): 6 | if x.isnumeric(): 7 | r+=x 8 | else: 9 | break 10 | try: 11 | return max(min(int(r),2147483647),-2147483648) 12 | except: 13 | return 0 14 | -------------------------------------------------------------------------------- /Python/SumofDigitsInBaseK.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sumBase(self, n, k): 3 | """ 4 | :type n: int 5 | :type k: int 6 | :rtype: int 7 | """ 8 | ans = 0 9 | while (n >= k): 10 | ans += n%k 11 | n //= k 12 | return ans + n 13 | -------------------------------------------------------------------------------- /Python/Trapping_Rain_Water.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | # Function to find the amount of water that can be trapped within 5 | # a given set of bars in linear time and extra space 6 | def trap(height): 7 | 8 | n = len(bars) 9 | if n <= 2: 10 | return 0 11 | 12 | water = 0 13 | 14 | # `left[i]` stores the maximum height of a bar to the left 15 | # of the current bar 16 | left = [None] * (n - 1) 17 | left[0] = -sys.maxsize 18 | 19 | # process bars from left to right 20 | for i in range(1, n - 1): 21 | left[i] = max(left[i - 1], height[i - 1]) 22 | 23 | # `right` stores the maximum height of a bar to the right 24 | # of the current bar 25 | right = -sys.maxsize 26 | 27 | # process bars from right to left 28 | for i in reversed(range(1, n - 1)): 29 | right = max(right, height[i + 1]) 30 | 31 | # check if it is possible to store water in the current bar 32 | if min(left[i], right) > height[i]: 33 | water += min(left[i], right) - height[i] 34 | 35 | return water 36 | -------------------------------------------------------------------------------- /Python/TwoSum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: List[int] 7 | """ 8 | h = {} 9 | for i, num in enumerate(nums): 10 | n = target - num 11 | if n not in h: 12 | h[num] = i 13 | else: 14 | return [h[n], i] 15 | -------------------------------------------------------------------------------- /Python/TwoSums.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | length = len(nums) 4 | for i in range(length): 5 | for j in range(i+1,length): 6 | if nums[i] + nums[j] == target: 7 | return [i,j] 8 | -------------------------------------------------------------------------------- /Python/UniqueEmailAddress: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/unique-email-addresses/ 2 | 3 | class Solution: 4 | def numUniqueEmails(self, emails: List[str]) -> int: 5 | valid = set() 6 | for email in emails: 7 | local , domain = email.split('@') 8 | local = local.split('+')[0].replace('.','') 9 | mail = local+'@'+domain 10 | valid.add(mail) 11 | return len(valid) 12 | -------------------------------------------------------------------------------- /Python/ZigZagConversion.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def convert(self, s, numRows): 4 | L = len(s) 5 | s_zigzag = '' 6 | if L == 0: 7 | return '' 8 | if numRows == 1: 9 | return s 10 | 11 | pivots = range(0,L+2*numRows-2,2*numRows-2) 12 | for p in pivots: 13 | s_zigzag += self.get_char(s,L,p) 14 | for diff in range(1,numRows-1): 15 | s_zigzag += self.get_char(s,L,pivots[0]+diff) 16 | for p in pivots[1:]: 17 | s_zigzag += self.get_char(s,L,p-diff) 18 | s_zigzag += self.get_char(s,L,p+diff) 19 | for p in pivots: 20 | s_zigzag += self.get_char(s,L,p+numRows-1) 21 | return s_zigzag 22 | 23 | def get_char(self,s,L,index): 24 | if index > L-1: 25 | return '' 26 | return s[index] 27 | -------------------------------------------------------------------------------- /Python/ZigzagConversion.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def convert(self, s: str, numRows: int) -> str: 3 | if(numRows < 2): 4 | return s 5 | arr = ['' for i in range(numRows)] 6 | direction = 'down' 7 | row = 0 8 | for i in s: 9 | arr[row] += i 10 | if row == numRows-1: 11 | direction = 'up' 12 | elif row == 0: 13 | direction = 'down' 14 | if(direction == 'down'): 15 | row += 1 16 | else: 17 | row -= 1 18 | return(''.join(arr)) 19 | -------------------------------------------------------------------------------- /Python/add-binary.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # @param a, a string 3 | # @param b, a string 4 | # @return a string 5 | def addBinary(self, a, b): 6 | result, carry, val = "", 0, 0 7 | for i in xrange(max(len(a), len(b))): 8 | val = carry 9 | if i < len(a): 10 | val += int(a[-(i + 1)]) 11 | if i < len(b): 12 | val += int(b[-(i + 1)]) 13 | carry, val = divmod(val, 2) 14 | result += str(val) 15 | if carry: 16 | result += str(carry) 17 | return result[::-1] 18 | 19 | 20 | # Time: O(n) 21 | # Space: O(1) 22 | from itertools import izip_longest 23 | 24 | 25 | class Solution2(object): 26 | def addBinary(self, a, b): 27 | """ 28 | :type a: str 29 | :type b: str 30 | :rtype: str 31 | """ 32 | result = "" 33 | carry = 0 34 | for x, y in izip_longest(reversed(a), reversed(b), fillvalue="0"): 35 | carry, remainder = divmod(int(x)+int(y)+carry, 2) 36 | result += str(remainder) 37 | 38 | if carry: 39 | result += str(carry) 40 | 41 | return result[::-1] 42 | -------------------------------------------------------------------------------- /Python/baseball-game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def calPoints(self, ops: List[str]) -> int: 3 | points=[] 4 | total=0 5 | for op in ops: 6 | if op == "C": 7 | points.pop() 8 | elif op == "D": 9 | points.append(2*(int(points[-1]))) 10 | elif op == "+": 11 | points.append((int(points[-1])+int(points[-2]))) 12 | else: 13 | points.append(int(op)) 14 | for i in points: 15 | total+=i 16 | return total 17 | -------------------------------------------------------------------------------- /Python/count-and-say.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countAndSay(self, n: int) -> str: 3 | result = "1" 4 | for _ in range(n - 1): 5 | s, curr_digit, count = "", result[0], 1 6 | for digit in result[1:]: 7 | if digit == curr_digit: 8 | count += 1 9 | else: 10 | s += str(count) + curr_digit 11 | curr_digit, count = digit, 1 12 | result = s + str(count) + curr_digit 13 | return result 14 | 15 | -------------------------------------------------------------------------------- /Python/fibonacci-number.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | 4 | class Solution(object): 5 | def fib(self, N): 6 | """ 7 | :type N: int 8 | :rtype: int 9 | """ 10 | def matrix_expo(A, K): 11 | result = [[int(i==j) for j in xrange(len(A))] \ 12 | for i in xrange(len(A))] 13 | while K: 14 | if K % 2: 15 | result = matrix_mult(result, A) 16 | A = matrix_mult(A, A) 17 | K /= 2 18 | return result 19 | 20 | def matrix_mult(A, B): 21 | ZB = zip(*B) 22 | return [[sum(a*b for a, b in itertools.izip(row, col)) \ 23 | for col in ZB] for row in A] 24 | 25 | T = [[1, 1], 26 | [1, 0]] 27 | return matrix_mult([[1, 0]], matrix_expo(T, N))[0][1] # [a1, a0] * T^N 28 | 29 | 30 | # Time: O(n) 31 | # Space: O(1) 32 | class Solution2(object): 33 | def fib(self, N): 34 | """ 35 | :type N: int 36 | :rtype: int 37 | """ 38 | prev, current = 0, 1 39 | for i in xrange(N): 40 | prev, current = current, prev + current, 41 | return prev 42 | -------------------------------------------------------------------------------- /Python/find-the-difference.py: -------------------------------------------------------------------------------- 1 | import operator 2 | import collections 3 | from functools import reduce 4 | 5 | 6 | class Solution(object): 7 | def findTheDifference(self, s, t): 8 | """ 9 | :type s: str 10 | :type t: str 11 | :rtype: str 12 | """ 13 | return chr(reduce(operator.xor, map(ord, s), 0) ^ reduce(operator.xor, map(ord, t), 0)) 14 | 15 | def findTheDifference2(self, s, t): 16 | """ 17 | :type s: str 18 | :type t: str 19 | :rtype: str 20 | """ 21 | t = list(t) 22 | s = list(s) 23 | for i in s: 24 | t.remove(i) 25 | return t[0] 26 | 27 | def findTheDifference3(self, s, t): 28 | return chr(reduce(operator.xor, map(ord, s + t))) 29 | 30 | def findTheDifference4(self, s, t): 31 | return list((collections.Counter(t) - collections.Counter(s)))[0] 32 | 33 | def findTheDifference5(self, s, t): 34 | s, t = sorted(s), sorted(t) 35 | return t[-1] if s == t[:-1] else [x[1] for x in zip(s, t) if x[0] != x[1]][0] 36 | -------------------------------------------------------------------------------- /Python/firstMissingPositive.py: -------------------------------------------------------------------------------- 1 | ### Problem Link: https://leetcode.com/problems/first-missing-positive/ 2 | 3 | class Solution: 4 | def firstMissingPositive(self, nums: List[int]) -> int: 5 | numLen = len(nums) 6 | record = [0 for _ in range(numLen+1)] 7 | for i in range(numLen): 8 | if nums[i] <= 0 or nums[i] > numLen+1: 9 | continue 10 | record[nums[i]-1] = i+1 # i+1 can make sure 0 is default empty 11 | for j in range(numLen+1): 12 | if record[j] == 0: 13 | return j + 1 14 | return -1 # default wrong answer 15 | -------------------------------------------------------------------------------- /Python/integer-to-english-words.py: -------------------------------------------------------------------------------- 1 | # Time: O(logn) = O(1), n is the value of the integer, which is less than 2^31 - 1 2 | # Space: O(1) 3 | 4 | class Solution(object): 5 | def numberToWords(self, num): 6 | """ 7 | :type num: int 8 | :rtype: str 9 | """ 10 | if num == 0: 11 | return "Zero" 12 | 13 | lookup = {0: "Zero", 1:"One", 2: "Two", 3: "Three", 4: "Four", \ 14 | 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", \ 15 | 10: "Ten", 11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen", \ 16 | 15: "Fifteen", 16: "Sixteen", 17: "Seventeen", 18: "Eighteen", 19: "Nineteen", \ 17 | 20: "Twenty", 30: "Thirty", 40: "Forty", 50: "Fifty", 60: "Sixty", \ 18 | 70: "Seventy", 80: "Eighty", 90: "Ninety"} 19 | unit = ["", "Thousand", "Million", "Billion"] 20 | 21 | res, i = [], 0 22 | while num: 23 | cur = num % 1000 24 | if num % 1000: 25 | res.append(self.threeDigits(cur, lookup, unit[i])) 26 | num //= 1000 27 | i += 1 28 | return " ".join(res[::-1]) 29 | 30 | def threeDigits(self, num, lookup, unit): 31 | res = [] 32 | if num / 100: 33 | res = [lookup[num / 100] + " " + "Hundred"] 34 | if num % 100: 35 | res.append(self.twoDigits(num % 100, lookup)) 36 | if unit != "": 37 | res.append(unit) 38 | return " ".join(res) 39 | 40 | def twoDigits(self, num, lookup): 41 | if num in lookup: 42 | return lookup[num] 43 | return lookup[(num / 10) * 10] + " " + lookup[num % 10] 44 | -------------------------------------------------------------------------------- /Python/integer-to-roman.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intToRoman(self, n: int) -> str: 3 | symbols = [["I", 1], ["IV", 4], ["V", 5], ["IX", 9], ["X", 10], ["XL", 40], ["L", 50], ["XC",90], ["C", 100], ["CD", 400], ["D", 500], ["CM", 900],["M", 1000]] 4 | final = "" 5 | for symbols, v in reversed (symbols): 6 | if n // v: 7 | count = n // v 8 | final += (symbols* count) 9 | n = n % v 10 | return final 11 | -------------------------------------------------------------------------------- /Python/intersectionofTwoLinkedLists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: 9 | d2, d1 = headB, headA 10 | while d2 is not d1: 11 | if d1 == None: d1 = headB 12 | else: d1 = d1.next 13 | 14 | if d2 == None: d2 = headA 15 | else: d2 = d2.next 16 | return d1 17 | -------------------------------------------------------------------------------- /Python/jump-game-II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, arr): 3 | lastMaxReach, currentMaxReach = 0, 0 4 | nJump, i = 0, 0 5 | while currentMaxReach < len(arr)-1: 6 | while i <= lastMaxReach: 7 | currentMaxReach = max(i+arr[i], currentMaxReach) 8 | i+=1 9 | if lastMaxReach == currentMaxReach: 10 | return -1 11 | lastMaxReach = currentMaxReach 12 | nJump+=1 13 | return nJump -------------------------------------------------------------------------------- /Python/length-of-last-word.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # @param s, a string 3 | # @return an integer 4 | def lengthOfLastWord(self, s): 5 | length = 0 6 | for i in reversed(s): 7 | if i == ' ': 8 | if length: 9 | break 10 | else: 11 | length += 1 12 | return length 13 | 14 | # Time: O(n) 15 | # Space: O(n) 16 | class Solution2(object): 17 | # @param s, a string 18 | # @return an integer 19 | def lengthOfLastWord(self, s): 20 | return len(s.strip().split(" ")[-1]) 21 | -------------------------------------------------------------------------------- /Python/linkedListCycle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hasCycle(self, head: ListNode) -> bool: 3 | if head is None or head.next is None: return False 4 | slow = fast = head 5 | while fast is not None and fast.next is not None: 6 | #slow = slow.next 7 | fast = fast.next.next 8 | slow = slow.next 9 | if fast == slow: return True 10 | 11 | return False 12 | -------------------------------------------------------------------------------- /Python/loud-and-rich.py: -------------------------------------------------------------------------------- 1 | # Time: O(q + r) 2 | # Space: O(q + r) 3 | 4 | 5 | class Solution(object): 6 | def loudAndRich(self, richer, quiet): 7 | """ 8 | :type richer: List[List[int]] 9 | :type quiet: List[int] 10 | :rtype: List[int] 11 | """ 12 | def dfs(graph, quiet, node, result): 13 | if result[node] is None: 14 | result[node] = node 15 | for nei in graph[node]: 16 | smallest_person = dfs(graph, quiet, nei, result) 17 | if quiet[smallest_person] < quiet[result[node]]: 18 | result[node] = smallest_person 19 | return result[node] 20 | 21 | graph = [[] for _ in range(len(quiet))] 22 | for u, v in richer: 23 | graph[v].append(u) 24 | result = [None]*len(quiet) 25 | return map(lambda x: dfs(graph, quiet, x, result), range(len(quiet))) 26 | -------------------------------------------------------------------------------- /Python/min-cost-climbing-stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCostClimbingStairs(self, cost: List[int]) -> int: 3 | c = len(cost) 4 | dp = [-1] * (c + 2) 5 | dp[c] = dp[c + 1] = 0 6 | for n in range(c - 1, -1, -1): 7 | dp[n] = cost[n] + min(dp[n + 1], dp[n + 2]) 8 | return min(dp[0], dp[1]) 9 | -------------------------------------------------------------------------------- /Python/move_zeroes.py: -------------------------------------------------------------------------------- 1 | def moveZeroes(nums: List[int]) -> None: 2 | pos = 0 3 | 4 | for i in range(len(nums)): 5 | el = nums[i] 6 | if el != 0: 7 | nums[pos], nums[i] = nums[i], nums[pos] 8 | pos += 1 9 | -------------------------------------------------------------------------------- /Python/multiply_strings.py: -------------------------------------------------------------------------------- 1 | def multiply_str(str1, str2): 2 | len1 = len(str1) 3 | len2 = len(str2) 4 | 5 | str1 = list(map(int, reversed(str1))) 6 | str2 = list(map(int, reversed(str2))) 7 | 8 | res = [0 for i in range(len1+len2)] 9 | 10 | for j in range(len2): 11 | for i in range(len1): 12 | 13 | res[i+j] = res[i+j]+str1[i]*str2[j] 14 | res[i+j+1] = res[i+j+1] + res[i+j]//10 #carry 15 | res[i+j] = res[i+j] % 10 16 | 17 | i = len(res)-1 18 | while (res[i] == 0 and i > 0): 19 | i = i-1 20 | 21 | return "".join(map(str, res[:i+1][::-1])) 22 | 23 | 24 | str1 = "123" 25 | str2 = "456" 26 | print(multiply_str(str1, str2)) 27 | -------------------------------------------------------------------------------- /Python/palindrome-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, x: int) -> bool: 3 | if str(x) == str(x)[::-1]:return 1 4 | else:return 0 5 | -------------------------------------------------------------------------------- /Python/powx-n.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x: float, n: int) -> float: 3 | value = 1 4 | if x == 0: return 0 5 | elif n == 0: return 1 6 | elif n < 0: 7 | while n < 0: 8 | value = value / x 9 | n += 1 10 | return value 11 | else: 12 | while n > 0: 13 | value = value * x 14 | n -= 1 15 | return value 16 | -------------------------------------------------------------------------------- /Python/removeLinkedListElements.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: 8 | temp, prev = head, None 9 | while temp is not None: 10 | if temp.val == val: 11 | if prev != None: 12 | prev.next = temp.next 13 | else: 14 | head = temp.next 15 | else: 16 | prev = temp 17 | temp = temp.next 18 | return head 19 | -------------------------------------------------------------------------------- /Python/remove_duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums: List[int]) -> int: 3 | 4 | pos = 0 5 | temp = None 6 | for num in nums: 7 | if num != temp: 8 | nums[pos] = num 9 | temp = num 10 | pos += 1 11 | 12 | return pos -------------------------------------------------------------------------------- /Python/remove_element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeElement(self, nums: List[int], val: int) -> int: 3 | y = nums.count(val) 4 | for x in range(y): 5 | nums.remove(val) 6 | return (len(nums)) 7 | -------------------------------------------------------------------------------- /Python/reverseLinkedList.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | if head is None: return None 9 | curr = head 10 | prev = nex = None 11 | while curr is not None : 12 | nex = curr.next 13 | curr.next = prev 14 | prev = curr 15 | curr = nex 16 | head = prev 17 | return head 18 | -------------------------------------------------------------------------------- /Python/search_insert_position.py: -------------------------------------------------------------------------------- 1 | def searchInsert(nums: List[int], target: int) -> int: 2 | return len([x for x in nums if x int: 3 | if len(haystack) == 0 and len(needle) == 0: 4 | return 0 5 | return haystack.find(needle) 6 | 7 | -------------------------------------------------------------------------------- /Python/valid-parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s: str) -> bool: 3 | n=0 4 | for ch in s: 5 | n=n+1 6 | if ch=="(": 7 | if s[n]==")": 8 | return True 9 | else: return False 10 | elif ch=="[": 11 | if s[n]=="]": 12 | return True 13 | else: return False 14 | elif ch=="{": 15 | if s[n]=="}": 16 | return True 17 | else: return False 18 | else: return False 19 | -------------------------------------------------------------------------------- /Python/wildcard-matching.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isMatch(self, s, p): 3 | """ 4 | :type s: str 5 | :type p: str 6 | :rtype: bool 7 | """ 8 | count = 0 # used for complexity check 9 | p_ptr, s_ptr, last_s_ptr, last_p_ptr = 0, 0, -1, -1 10 | while s_ptr < len(s): 11 | if p_ptr < len(p) and (s[s_ptr] == p[p_ptr] or p[p_ptr] == '?'): 12 | s_ptr += 1 13 | p_ptr += 1 14 | elif p_ptr < len(p) and p[p_ptr] == '*': 15 | p_ptr += 1 16 | last_s_ptr = s_ptr 17 | last_p_ptr = p_ptr 18 | elif last_p_ptr != -1: 19 | last_s_ptr += 1 20 | s_ptr = last_s_ptr 21 | p_ptr = last_p_ptr 22 | else: 23 | assert(count <= (len(p)+1) * (len(s)+1)) 24 | return False 25 | count += 1 # used for complexity check 26 | 27 | while p_ptr < len(p) and p[p_ptr] == '*': 28 | p_ptr += 1 29 | count += 1 # used for complexity check 30 | 31 | assert(count <= (len(p)+1) * (len(s)+1)) 32 | return p_ptr == len(p) 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode Solutions 2 | 3 | This repository has been created to contain solutions of various LeetCode Challenges. 4 | 5 | Some Problems to solve can be found [here](https://leetcode.com/problemset/all/) 6 | 7 | Pull Requests are Welcomed. 8 | -------------------------------------------------------------------------------- /Rust/best-time-to-buy-and-sell-stock.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn max_profit(prices: Vec) -> i32 { 3 | let mut min = i32::MAX; 4 | let mut max = 0; 5 | for i in prices{ 6 | if i < min { 7 | min = i; 8 | } else if i - min > max { 9 | max = i - min; 10 | } 11 | } 12 | max 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Rust/contains_duplicate.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | impl Solution { 4 | pub fn contains_duplicate(nums: Vec) -> bool { 5 | let mut hashmap = HashMap::new(); 6 | nums.into_iter().any(|i| hashmap.insert(i, i).is_some()) 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Rust/decode_ways.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn num_decodings(s: impl std::string::ToString) -> i32 { 5 | let s = s.to_string(); 6 | let mut dp = vec![1, if &s[0..1] == "0" { 0 } else { 1 }]; 7 | dp.extend(vec![0; s.len() - 1]); 8 | for i in 2..dp.len() { 9 | let jumps = (1..=2) 10 | .map(|j| s[i - j..i].parse::().unwrap()) 11 | .collect::>(); 12 | if 0 < jumps[0] && jumps[0] <= 9 { 13 | dp[i] += dp[i - 1]; 14 | } 15 | if 10 <= jumps[1] && jumps[1] <= 26 { 16 | dp[i] += dp[i - 2]; 17 | } 18 | } 19 | dp[s.len()] 20 | } 21 | } 22 | 23 | fn main() { 24 | Solution::num_decodings("12"); 25 | } 26 | -------------------------------------------------------------------------------- /Rust/find_the_difference.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn find_the_difference(s: String, t: String) -> char { 3 | let mut s = s.into_bytes(); 4 | let mut t = t.into_bytes(); 5 | s.sort(); 6 | t.sort(); 7 | for (a, b) in s.iter().zip(t.iter()) { 8 | if a != b { 9 | return *b as char; 10 | } 11 | } 12 | t[s.len()] as char 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Rust/fizz_buzz.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn fizz_buzz(n: i32) -> Vec { 3 | let mut answer = Vec::new(); 4 | for i in 1..=n { 5 | answer.push( 6 | match (i % 3 == 0, i % 5 == 0) { 7 | (true, true) => "FizzBuzz".to_string(), 8 | (true, false) => "Fizz".to_string(), 9 | (false, true) => "Buzz".to_string(), 10 | (false, false) => i.to_string(), 11 | } 12 | ) 13 | } 14 | answer 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Rust/group_anagrams.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn group_anagrams(strs: Vec) -> Vec> { 5 | use std::collections::HashMap; 6 | 7 | let mut res: Vec> = vec![]; 8 | let mut m: HashMap<[u8; 26], usize> = HashMap::new(); 9 | let mut i = 0; 10 | 11 | for str in strs.iter() { 12 | let mut s: [u8; 26] = [0; 26]; 13 | for c in str.chars() { 14 | let ci = c as usize - 'a' as usize; 15 | s[ci] += 1; 16 | } 17 | match m.get(&s) { 18 | Some(j) => { 19 | res[*j].push(str.to_string()); 20 | } 21 | None => { 22 | m.insert(s, i); 23 | if res.len() < i + 1 { 24 | res.push(vec![]); 25 | } 26 | res[i].push(str.to_string()); 27 | i += 1; 28 | } 29 | } 30 | } 31 | res 32 | } 33 | } 34 | fn main() { 35 | Solution::group_anagrams( 36 | vec!["eat", "tea", "tan", "ate", "nat", "bat"] 37 | .into_iter() 38 | .map(ToString::to_string) 39 | .collect(), 40 | ); 41 | } 42 | -------------------------------------------------------------------------------- /Rust/int_to_roman.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn int_to_roman(mut num: i32) -> String { 3 | let symbol: Vec<&str> = vec![ 4 | "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I", 5 | ]; 6 | let value: Vec = vec![1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; 7 | let mut s = String::from(""); 8 | for (i, v) in value.iter().enumerate() { 9 | while num >= *v { 10 | s.push_str(symbol[i]); 11 | num -= v; 12 | } 13 | } 14 | return s; 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /Rust/letter_combinations_for_phone_number.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | impl Solution { 3 | fn get_char(c: char) -> String { 4 | let mut res = ""; 5 | if c == '2' { 6 | res = "abc"; 7 | } else if c == '3' { 8 | res = "def"; 9 | } else if c == '4' { 10 | res = "ghi"; 11 | } else if c == '5' { 12 | res = "jkl"; 13 | } else if c == '6' { 14 | res = "mno"; 15 | } else if c == '7' { 16 | res = "pqrs"; 17 | } else if c == '8' { 18 | res = "tuv"; 19 | } else if c == '9' { 20 | res = "wxyz"; 21 | } 22 | return res.into(); 23 | } 24 | pub fn letter_combinations(digits: String) -> Vec { 25 | if digits.is_empty() { 26 | return vec![]; 27 | } 28 | digits.chars().fold(vec![String::from("")], |acc, digit| { 29 | acc.iter() 30 | .flat_map(|x| { 31 | Self::get_char(digit) 32 | .chars() 33 | .map(|y| format!("{}{}", x, y)) 34 | .collect::>() 35 | }) 36 | .collect() 37 | }) 38 | } 39 | } 40 | 41 | fn main() { 42 | Solution::letter_combinations("23".to_string()); 43 | } 44 | -------------------------------------------------------------------------------- /Rust/palindrome.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/palindrome-number/ 2 | 3 | pub fn is_palindrome(x: i32) -> bool { 4 | x.to_string() == x.to_string().chars().rev().collect::() 5 | } 6 | -------------------------------------------------------------------------------- /Rust/power_of_four.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn is_power_of_four(n: i32) -> bool { 3 | return n > 0 && n & (n - 1) == 0 && n % 3 == 1; 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Rust/reverse-integer.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-integer/ 2 | 3 | impl Solution { 4 | pub fn reverse(x: i32) -> i32 { 5 | let mut reversed: i32 = 0; 6 | let mut start_value = x; 7 | let mut _overflow: Option = None; 8 | 9 | while start_value != 0 { 10 | _overflow = reversed.checked_mul(10); 11 | match _overflow { 12 | Some(x) => { 13 | reversed = x; 14 | _overflow = reversed.checked_add(start_value % 10); 15 | match _overflow { 16 | Some(x) => reversed = x, 17 | None => return 0, 18 | } 19 | } 20 | None => return 0, 21 | } 22 | start_value = start_value / 10; 23 | } 24 | reversed 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Rust/three_sum.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn three_sum(nums: Vec) -> Vec> { 5 | let mut ret = Vec::new(); 6 | 7 | if nums.is_empty() { 8 | return ret; 9 | } 10 | if nums.len() == 1 { 11 | return ret; 12 | } 13 | 14 | let mut nums = nums; 15 | nums.sort(); 16 | 17 | for i in 0..(nums.len() - 2) { 18 | if i > 0 && nums[i] == nums[i - 1] { 19 | continue; 20 | } 21 | 22 | if nums[i] > 0 { 23 | return ret; 24 | } 25 | 26 | let mut left = i + 1; 27 | let mut right = nums.len() - 1; 28 | 29 | while left < right { 30 | let L = nums[left]; 31 | let R = nums[right]; 32 | let X = nums[i]; 33 | let total = L + R + X; 34 | if total > 0 { 35 | right -= 1; 36 | } else if total < 0 { 37 | left += 1; 38 | } else { 39 | ret.push(vec![L, R, X]); 40 | while left < right && nums[left] == nums[left + 1] { 41 | left += 1; 42 | } 43 | while left < right && nums[right] == nums[right - 1] { 44 | right -= 1; 45 | } 46 | 47 | left += 1; 48 | right -= 1; 49 | } 50 | } 51 | } 52 | ret 53 | } 54 | } 55 | 56 | fn main() { 57 | Solution::three_sum(vec![-1, 0, 1, 2, -1, -4]); 58 | } 59 | -------------------------------------------------------------------------------- /Rust/three_sum_closest.rs: -------------------------------------------------------------------------------- 1 | struct Solution; 2 | 3 | impl Solution { 4 | pub fn three_sum_closest(nums: Vec, target: i32) -> i32 { 5 | let mut result = 10_i32.pow(5); // the question specs state target < 10^4 6 | 7 | let mut nums = nums; 8 | nums.sort(); // we need a sorted list for the algorithm to work 9 | 10 | for i in 0..nums.len() - 2 { 11 | let mut left_ptr = i + 1; 12 | let mut right_ptr = nums.len() - 1; 13 | 14 | while left_ptr < right_ptr { 15 | let sum = nums[i] + nums[left_ptr] + nums[right_ptr]; 16 | if (sum - target).abs() < (result - target).abs() { 17 | result = sum; 18 | } 19 | match sum.cmp(&target) { 20 | std::cmp::Ordering::Greater => right_ptr -= 1, 21 | std::cmp::Ordering::Less => left_ptr += 1, 22 | std::cmp::Ordering::Equal => return sum, 23 | } 24 | } 25 | } 26 | 27 | result 28 | } 29 | } 30 | 31 | fn main() { 32 | Solution::three_sum_closest(vec![-1, 2, 1, -4], 1); 33 | } 34 | -------------------------------------------------------------------------------- /Rust/two-sum.rs: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/two-sum/ 2 | 3 | use std::collections::HashMap; 4 | 5 | impl Solution { 6 | pub fn two_sum(nums: Vec, target: i32) -> Vec { 7 | let nums_len = nums.len(); 8 | let mut map = HashMap::new(); 9 | 10 | for i in 0..nums_len { 11 | let t = target - nums[i]; 12 | 13 | if let Some(x) = map.get(&t) { 14 | return vec![*x, i as i32]; 15 | } else { 16 | map.insert(nums[i], i as i32); 17 | } 18 | } 19 | vec![] 20 | } 21 | -------------------------------------------------------------------------------- /Rust/zigzag-conversion.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn convert(s: String, num_rows: i32) -> String { 3 | if num_rows == 1 { 4 | return s; 5 | } 6 | let mut sol: Vec = vec![String::from(""); num_rows as usize]; 7 | let mut row = 0; 8 | let mut down = false; 9 | for c in s.chars() { 10 | sol[row] += &c.to_string(); 11 | if row == 0 || row == (num_rows - 1) as usize { 12 | down = !down; 13 | } 14 | if down { 15 | row += 1; 16 | } else { 17 | row -= 1; 18 | } 19 | } 20 | sol.join("") 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /java/valid-sudoku.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem Name : Valid Sudoku 3 | * Concept Involved : 2D Array, Frequency Count 4 | * 5 | * Execution Time : 2 ms 6 | * Memory Consumed : 38.8 mb 7 | * 8 | * Solution : We have been given with a Sudoku 9 | * Puzzle, we have to determine whether the puzzle 10 | * is valid or not. 11 | * In order to check the validity every row and column 12 | * of sudoku must have numbers from 0 to 9 and in a non 13 | * repeating fashion and same for in every 3x3 block. 14 | * I have used array based indexing to compute the 15 | * frequency of elements in every rows, columns and blocks 16 | * and checking its validity afterwards. 17 | * If every check is passed then we return True at the end. 18 | */ 19 | class Solution { 20 | public boolean isValid(ArrayList arr){ 21 | int[] fre = new int[10]; 22 | for(int ele : arr){ 23 | fre[ele]++; 24 | if(fre[ele] > 1){ 25 | return false; 26 | } 27 | } 28 | return true; 29 | } 30 | public boolean isValidSudoku(char[][] board) { 31 | for(int i=0; i<9; i++){ 32 | ArrayList row = new ArrayList<>(); 33 | for(int j=0; j<9; j++){ 34 | if(board[i][j] != '.'){ 35 | int num = board[i][j] - '0'; 36 | row.add(num); 37 | } 38 | } 39 | if(!isValid(row)){ 40 | return false; 41 | } 42 | } 43 | 44 | for(int i=0; i<9; i++){ 45 | ArrayList col = new ArrayList<>(); 46 | for(int j=0; j<9; j++){ 47 | if(board[j][i] != '.'){ 48 | int num = board[j][i] - '0'; 49 | col.add(num); 50 | } 51 | } 52 | if(!isValid(col)){ 53 | return false; 54 | } 55 | } 56 | 57 | for(int i=0; i<9; i+=3){ 58 | for(int j=0; j<9; j+=3){ 59 | ArrayList block = new ArrayList<>(); 60 | for(int k=i;k