├── README.md └── src ├── 3Sum.java ├── AccountsMege.java ├── AddLLNumbers.java ├── AddTwoNumbersLL2.java ├── AddTwoNums.java ├── AlienDictionary.java ├── AlphabetBoardPath.java ├── Anagram.java ├── BSTInorder.java ├── BSTLeafSameLevel.java ├── BSTMaxCommonAncestor.java ├── BSTSerializeDeserialize.java ├── BSTSplit.java ├── BSTToString.java ├── BSTVerticalTraversal.java ├── BackspaceCompare.java ├── BadSensor.java ├── BalanceBinaryTree.java ├── BalancingParanthesis.java ├── BestTimeToBuy.java ├── BinaryDFS.java ├── BinaryTreeRightSideView.java ├── Bipartite.java ├── BoatToSavePeople.java ├── Calendar.java ├── CamelCaseMatching.java ├── CarFleet.java ├── CardsDeckMax.java ├── CircularArrayLoop.java ├── CircularLL.java ├── ClosedIslands.java ├── CoinChange.java ├── Combination.java ├── CombinationSum2.java ├── ConsecutiveSum.java ├── ConsistenStrings.java ├── ContigousSubArraySum.java ├── CountBinarySubstring.java ├── CountSquares.java ├── CourseSchedule.java ├── DecodeStrings.java ├── DecodeWays.java ├── DecodeXORedArray.java ├── DegreeOfArray.java ├── DeleteDuplicatesLL.java ├── DesignWordDict.java ├── DiagonalSum.java ├── DuplicateFiles.java ├── DuplicateSubtree.java ├── EditDistance.java ├── ExpressionParanthesizer.java ├── FailyTemperatures.java ├── FileChunkSharing.java ├── FindDuplicate.java ├── FindDuplicateFile.java ├── FirstMissingPositive.java ├── FrogJump.java ├── GenerateParanthesis.java ├── GoodNodesInBT.java ├── GraphDeepCopy.java ├── GroupAnagram.java ├── HalfVowelCount.java ├── HammingDistance.java ├── HighFive.java ├── HistorgramMaxRect.java ├── InMemoryFileSystem.java ├── IncreasingPermutaion.java ├── IncreasingSubsequence.java ├── IndexStringPait.java ├── InsertInterval.java ├── IntegerToRoman.java ├── IntervalIntersection.java ├── InvertBinaryTree.java ├── IslandCount.java ├── KDiffPairs.java ├── KLargestElement.java ├── KandanesMaxSubarray.java ├── KnightMinMoves.java ├── Kosaraju.java ├── LFUCache.java ├── LLIntersection.java ├── LRUCache.java ├── LastSubStrLexiOrder.java ├── LetterCombinationPhoneNumber.java ├── LevelOrder.java ├── LinkedListPalindrome.java ├── LoggerTime.java ├── LongestBeautifulSubstring.java ├── LongestCommonPrefix.java ├── LongestCommonSubSequence.java ├── LongestConsecutiveOnes.java ├── LongestConsecutiveSequence.java ├── LongestMountain.java ├── LongestSubstringEvenVowels.java ├── LongestWordInDict.java ├── MagicDictionary.java ├── MapSumPair.java ├── MatrixRangeSum.java ├── MatrixRotaton.java ├── MatrixSpiralFill.java ├── MaxAreaIsland.java ├── MaxLenConcat.java ├── MaxSubArray.java ├── MaxSubstrOccurence.java ├── MaximumRectangle.java ├── MaximumSquare.java ├── Maze.java ├── MedianOfSortedArrays.java ├── MeetingRoom.java ├── MergeInterval.java ├── MergeKLinkedList.java ├── MergeSortedArray.java ├── MergeSortedLinkedList.java ├── MinDeletionCost.java ├── MinDiff3Moves.java ├── MinStack.java ├── MinSubSequence.java ├── MinimumDistanceWords.java ├── MinimumOperationsToStrictlyInc.java ├── MoveZeros.java ├── MovingAverage.java ├── NestedListSum.java ├── NumberOfComponents.java ├── NumberOfPlaylists.java ├── NumberToWords.java ├── OptimalAccountBalance.java ├── PaintHouseIII.java ├── PairsOfSongMod60.java ├── PalindromicSubstring.java ├── PartitionArray.java ├── PartitionLabel.java ├── PathCrossing.java ├── Permutation.java ├── PoisonTime.java ├── Pow.java ├── PrefixSum.java ├── ProductExcludingSelf.java ├── QueueUsingStack.java ├── RLEIterator.java ├── RandomPickWeight.java ├── RandomPointerCopyLL.java ├── RandomSet.java ├── RangeAddition.java ├── RangeSum.java ├── RemoveAdjacentDuplicates.java ├── RemoveKDigits.java ├── RemoveNthElementLL.java ├── ReverseInteger.java ├── ReverseLL.java ├── ReverseLLGroup.java ├── ReverseNumberMax.java ├── ReversePartOfLinkedList.java ├── ReverseStringGroups.java ├── ReverseWords.java ├── RobotCircularPath.java ├── RobotCleaner.java ├── RomanToInteger.java ├── RunLengthEncoding.java ├── SecondLargestDigit.java ├── SecondMinimumTree.java ├── SentenceScreenFitting.java ├── SetMatrixZero.java ├── ShortestPalindrome.java ├── ShortestPathInMatrix.java ├── SingleNumber.java ├── SingleRowKeyboard.java ├── SkyLine.java ├── SmallestDivisorThreshold.java ├── SnapshotArray.java ├── Sort.java ├── SortLinkedList.java ├── SortThreeColors.java ├── SortTransformedArray.java ├── SortedArrayNearestElements.java ├── Sorting.java ├── SpiralMatrix.java ├── SplitReverseWords.java ├── SplitWords.java ├── SquareSortedArray.java ├── StackUsingQueue.java ├── StockProfit.java ├── StringBalanceParanthesis.java ├── StringCompression.java ├── StringTransformation.java ├── StringZigZag.java ├── SubDomainCount.java ├── SubStringAnagram.java ├── SubStringRepeatingChar.java ├── SubordinatesSum.java ├── Sudoku.java ├── SumDivisible.java ├── TargetSum.java ├── TextJustification.java ├── TimeToInform.java ├── TopKFrequentElements.java ├── TopoLogicalSort.java ├── TrappingRainWater.java ├── TreeAncestors.java ├── TreeBalancedCheck.java ├── TreeDeleteNodes.java ├── TreeLevelOrderZigZag.java ├── TreeMapProblem.java ├── TreePostOrder.java ├── TreePostOrderDP.java ├── Trie.java ├── TrieErase.java ├── Twitter.java ├── TwoSum.java ├── UndergroundStation.java ├── UnionFind.java ├── UniqueSubStrings.java ├── ValidPalindromeWithDeletion.java ├── VerticalLinesInTree.java ├── VowelPermutation.java ├── WallAndGates.java ├── WaysToPaintGrid.java ├── WindowMax.java ├── WordSearch.java ├── WordSearchInGrid.java └── atoi.java /README.md: -------------------------------------------------------------------------------- 1 | # Leet Code Solutions Index 2 | 3 | --- 4 | 5 | ## TODO 6 | 7 | Index each solution with problem link/number/tag 8 | 9 | --- 10 | -------------------------------------------------------------------------------- /src/3Sum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 3 | 4 | Notice that the solution set must not contain duplicate triplets. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [-1,0,1,2,-1,-4] 11 | Output: [[-1,-1,2],[-1,0,1]] 12 | Example 2: 13 | 14 | Input: nums = [] 15 | Output: [] 16 | Example 3: 17 | 18 | Input: nums = [0] 19 | Output: [] 20 | 21 | 22 | Constraints: 23 | 24 | 0 <= nums.length <= 3000 25 | -105 <= nums[i] <= 105 26 | 27 | */ 28 | class Solution { 29 | public List> threeSum(int[] nums) { 30 | Arrays.sort(nums); 31 | 32 | List> result = new ArrayList<>(); 33 | 34 | for(int it=0; it 0 && nums[it - 1] == nums[it]) 36 | continue; 37 | int target = -nums[it]; 38 | int left = it + 1, right = nums.length - 1; 39 | 40 | while(left < right) { 41 | int sum = nums[left] + nums[right]; 42 | 43 | if(sum == target) { 44 | result.add(Arrays.asList(nums[it],nums[left], nums[right])); 45 | left++; 46 | right--; 47 | while(left < right && nums[left] == nums[left-1]) left++; 48 | while(left < right && nums[right] == nums[right + 1]) right--; 49 | } else if(sum < target) { 50 | left++; 51 | } else { 52 | right--; 53 | } 54 | } 55 | } 56 | 57 | return result; 58 | } 59 | } -------------------------------------------------------------------------------- /src/AddLLNumbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. 4 | 5 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | 12 | Input: l1 = [2,4,3], l2 = [5,6,4] 13 | Output: [7,0,8] 14 | Explanation: 342 + 465 = 807. 15 | Example 2: 16 | 17 | Input: l1 = [0], l2 = [0] 18 | Output: [0] 19 | Example 3: 20 | 21 | Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] 22 | Output: [8,9,9,9,0,0,0,1] 23 | 24 | 25 | Constraints: 26 | 27 | The number of nodes in each linked list is in the range [1, 100]. 28 | 0 <= Node.val <= 9 29 | It is guaranteed that the list represents a number that does not have leading zeros. 30 | 31 | 32 | * Definition for singly-linked list. 33 | * public class ListNode { 34 | * int val; 35 | * ListNode next; 36 | * ListNode() {} 37 | * ListNode(int val) { this.val = val; } 38 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 39 | * } 40 | */ 41 | class Solution { 42 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 43 | ListNode head = new ListNode(); 44 | ListNode trav = head; 45 | int carry = 0; 46 | while(l1 != null || l2 != null) { 47 | int sum = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + carry; 48 | carry = sum / 10; 49 | 50 | ListNode newNode = new ListNode(); 51 | newNode.val = sum % 10; 52 | 53 | trav.next = newNode; 54 | trav = trav.next; 55 | 56 | l1 = l1 != null ? l1.next : null; 57 | l2 = l2 != null ? l2.next : null; 58 | } 59 | 60 | if(carry != 0) { 61 | ListNode newNode = new ListNode(); 62 | newNode.val = carry; 63 | 64 | trav.next = newNode; 65 | trav = trav.next; 66 | } 67 | return head.next; 68 | } 69 | } -------------------------------------------------------------------------------- /src/AddTwoNums.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. 3 | 4 | Note: 5 | 6 | The length of both num1 and num2 is < 5100. 7 | Both num1 and num2 contains only digits 0-9. 8 | Both num1 and num2 does not contain any leading zero. 9 | You must not use any built-in BigInteger library or convert the inputs to integer directly. 10 | 11 | */ 12 | 13 | class Solution { 14 | public String addStrings(String num1, String num2) { 15 | StringBuilder res = new StringBuilder(); 16 | 17 | int carry = 0; 18 | int p1 = num1.length() - 1; 19 | int p2 = num2.length() - 1; 20 | while (p1 >= 0 || p2 >= 0) { 21 | int x1 = p1 >= 0 ? num1.charAt(p1) - '0' : 0; 22 | int x2 = p2 >= 0 ? num2.charAt(p2) - '0' : 0; 23 | int value = (x1 + x2 + carry) % 10; 24 | carry = (x1 + x2 + carry) / 10; 25 | res.append(value); 26 | p1--; 27 | p2--; 28 | } 29 | 30 | if (carry != 0) 31 | res.append(carry); 32 | 33 | return res.reverse().toString(); 34 | } 35 | } -------------------------------------------------------------------------------- /src/Anagram.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two strings s and t , write a function to determine if t is an anagram of s. 3 | 4 | Example 1: 5 | 6 | Input: s = "anagram", t = "nagaram" 7 | Output: true 8 | Example 2: 9 | 10 | Input: s = "rat", t = "car" 11 | Output: false 12 | Note: 13 | You may assume the string contains only lowercase alphabets. 14 | 15 | Follow up: 16 | What if the inputs contain unicode characters? How would you adapt your solution to such case? 17 | 18 | 19 | */ 20 | class Solution { 21 | public boolean isAnagram(String s, String t) { 22 | int[] dic = new int[26]; 23 | 24 | if(s.length() != t.length()) return false; 25 | 26 | for(int it=0; it= 0 || j >= 0) { // While there may be chars in build(S) or build (T) 41 | while (i >= 0) { // Find position of next possible char in build(S) 42 | if (S.charAt(i) == '#') {skipS++; i--;} 43 | else if (skipS > 0) {skipS--; i--;} 44 | else break; 45 | } 46 | while (j >= 0) { // Find position of next possible char in build(T) 47 | if (T.charAt(j) == '#') {skipT++; j--;} 48 | else if (skipT > 0) {skipT--; j--;} 49 | else break; 50 | } 51 | // If two actual characters are different 52 | if (i >= 0 && j >= 0 && S.charAt(i) != T.charAt(j)) 53 | return false; 54 | // If expecting to compare char vs nothing 55 | if ((i >= 0) != (j >= 0)) 56 | return false; 57 | i--; j--; 58 | } 59 | return true; 60 | } 61 | } -------------------------------------------------------------------------------- /src/BalancingParanthesis.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: 3 | 4 | Any left parenthesis '(' must have a corresponding right parenthesis ')'. 5 | Any right parenthesis ')' must have a corresponding left parenthesis '('. 6 | Left parenthesis '(' must go before the corresponding right parenthesis ')'. 7 | '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. 8 | An empty string is also valid. 9 | Example 1: 10 | Input: "()" 11 | Output: True 12 | Example 2: 13 | Input: "(*)" 14 | Output: True 15 | Example 3: 16 | Input: "(*))" 17 | Output: True 18 | Note: 19 | The string size will be in the range [1, 100]. 20 | */ 21 | class Solution { 22 | public boolean checkValidString(String s) { 23 | Stack stack = new Stack<>(); 24 | Stack starStack = new Stack<>(); 25 | 26 | char[] arr = s.toCharArray(); 27 | for(int it=0; it result = new ArrayList<>(); 45 | 46 | public List rightSideView(TreeNode root) { 47 | dfs(root, 0); 48 | return result; 49 | } 50 | 51 | private void dfs(TreeNode node, int val) { 52 | if(node == null) 53 | return; 54 | 55 | if(val > leftMax) { 56 | result.add(node.val); 57 | leftMax = val; 58 | } 59 | dfs(node.right, val + 1); 60 | dfs(node.left, val + 1); 61 | 62 | } 63 | } -------------------------------------------------------------------------------- /src/Bipartite.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size. 3 | 4 | Each person may dislike some other people, and they should not go into the same group. 5 | 6 | Formally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group. 7 | 8 | Return true if and only if it is possible to split everyone into two groups in this way. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: N = 4, dislikes = [[1,2],[1,3],[2,4]] 15 | Output: true 16 | Explanation: group1 [1,4], group2 [2,3] 17 | Example 2: 18 | 19 | Input: N = 3, dislikes = [[1,2],[1,3],[2,3]] 20 | Output: false 21 | Example 3: 22 | 23 | Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]] 24 | Output: false 25 | 26 | 27 | Constraints: 28 | 29 | 1 <= N <= 2000 30 | 0 <= dislikes.length <= 10000 31 | dislikes[i].length == 2 32 | 1 <= dislikes[i][j] <= N 33 | dislikes[i][0] < dislikes[i][1] 34 | There does not exist i != j for which dislikes[i] == dislikes[j]. 35 | 36 | */ 37 | class Solution { 38 | 39 | HashMap colors = new HashMap<>(); 40 | ArrayList[] adjList; 41 | 42 | public boolean possibleBipartition(int N, int[][] dislikes) { 43 | 44 | adjList = new ArrayList[N+1]; 45 | 46 | for(int it=0; it<=N; it++) 47 | adjList[it] = new ArrayList<>(); 48 | 49 | for(int it=0; it amount ? -1 : dp[amount]; 53 | } 54 | } -------------------------------------------------------------------------------- /src/Combination.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 3 | 4 | You may return the answer in any order. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: n = 4, k = 2 11 | Output: 12 | [ 13 | [2,4], 14 | [3,4], 15 | [2,3], 16 | [1,2], 17 | [1,3], 18 | [1,4], 19 | ] 20 | Example 2: 21 | 22 | Input: n = 1, k = 1 23 | Output: [[1]] 24 | 25 | 26 | Constraints: 27 | 28 | 1 <= n <= 20 29 | 1 <= k <= n 30 | 31 | */ 32 | class Solution { 33 | private ArrayList> result = new ArrayList<>(); 34 | 35 | private void backtrack(int index, LinkedList list, int k, int n) { 36 | if(list.size() == k){ 37 | result.add(new ArrayList<>(list)); 38 | return; 39 | } 40 | 41 | for(int it=index; it<=n; it++) { 42 | list.add(it); 43 | backtrack(it+1, list, k, n); 44 | list.removeLast(); 45 | } 46 | } 47 | 48 | public List> combine(int n, int k) { 49 | backtrack(1, new LinkedList<>(), k, n); 50 | return result; 51 | } 52 | } 53 | 54 | //Combination without duplicates 55 | 56 | class SubsetWithDuplicates { 57 | 58 | public static List> findSubsets(int[] nums) { 59 | List> subsets = new ArrayList<>(); 60 | Arrays.sort(nums); 61 | combinations(subsets, new LinkedList(), nums, 0); 62 | return subsets; 63 | } 64 | 65 | private static void combinations(List> subsets, LinkedList curr, int[] nums, int index) { 66 | 67 | subsets.add(new ArrayList<>(curr)); 68 | 69 | for(int it=index; it index && nums[it - 1] == nums[it]) 71 | continue; 72 | curr.add(nums[it]); 73 | combinations(subsets, curr, nums, it + 1); 74 | curr.removeLast(); 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /src/CombinationSum2.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. 3 | 4 | Each number in candidates may only be used once in the combination. 5 | 6 | Note: The solution set must not contain duplicate combinations. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: candidates = [10,1,2,7,6,1,5], target = 8 13 | Output: 14 | [ 15 | [1,1,6], 16 | [1,2,5], 17 | [1,7], 18 | [2,6] 19 | ] 20 | Example 2: 21 | 22 | Input: candidates = [2,5,2,1,2], target = 5 23 | Output: 24 | [ 25 | [1,2,2], 26 | [5] 27 | ] 28 | 29 | 30 | Constraints: 31 | 32 | 1 <= candidates.length <= 100 33 | 1 <= candidates[i] <= 50 34 | 1 <= target <= 30 35 | */ 36 | class Solution { 37 | 38 | private List> result = new ArrayList<>(); 39 | 40 | private void backtrack(int index, LinkedList list, int target, int curr, int[] arr) { 41 | if(curr == target){ 42 | result.add(new ArrayList<>(list)); 43 | return; 44 | } else if(curr > target) { 45 | return; 46 | } 47 | 48 | for(int it=index; it index && arr[it] == arr[it-1]) 51 | continue; 52 | list.add(arr[it]); 53 | curr+=arr[it]; 54 | backtrack(it+1, list, target, curr, arr); 55 | list.removeLast(); 56 | curr-=arr[it]; 57 | } 58 | } 59 | 60 | public List> combinationSum2(int[] candidates, int target) { 61 | Arrays.sort(candidates); 62 | backtrack(0, new LinkedList<>(), target, 0, candidates); 63 | return result; 64 | } 65 | } -------------------------------------------------------------------------------- /src/ConsecutiveSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | N -> Sum 3 | X -> Base 4 | K -> number of numbers 5 | 6 | N = xk + k(k+1)/2 7 | xk = N - k(k+1)/2 8 | x = N/k - (k+1)/2 9 | 10 | x > 0 so assume x is 0 then value of RHS must be greater than 0 11 | 12 | 0 < N/k - (k+1)/2 13 | -N/k < -(k+1)/2 14 | N/k >= (k+1)/2 15 | 16 | 2N >= k^2 + k 17 | 2N + 1/4 >= (k+1/2)^1/2 18 | 19 | (2N + 1/4)^1/2 - 1/2 >= k 20 | */ 21 | 22 | class Solution { 23 | public int consecutiveNumbersSum(int N) { 24 | int answer = 0; 25 | int limit = (int)Math.sqrt(2*N + 1/4) - 1/2; 26 | 27 | for(int k=1; k<=limit; k++) { 28 | N-=k; 29 | 30 | if(N % k == 0) 31 | answer++; 32 | } 33 | return answer; 34 | } 35 | } -------------------------------------------------------------------------------- /src/ConsistenStrings.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed. 3 | 4 | Return the number of consistent strings in the array words. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"] 11 | Output: 2 12 | Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'. 13 | Example 2: 14 | 15 | Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"] 16 | Output: 7 17 | Explanation: All strings are consistent. 18 | Example 3: 19 | 20 | Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"] 21 | Output: 4 22 | Explanation: Strings "cc", "acd", "ac", and "d" are consistent. 23 | 24 | 25 | Constraints: 26 | 27 | 1 <= words.length <= 104 28 | 1 <= allowed.length <= 26 29 | 1 <= words[i].length <= 10 30 | The characters in allowed are distinct. 31 | words[i] and allowed contain only lowercase English letters. 32 | 33 | */ 34 | class Solution { 35 | public int countConsistentStrings(String allowed, String[] words) { 36 | int result = 0; 37 | boolean[] dict = new boolean[26]; 38 | 39 | for(int it=0; it map = new HashMap<>(); 28 | map.put(0, 1); 29 | 30 | for(int it=0; it 1 5 | 'B' -> 2 6 | ... 7 | 'Z' -> 26 8 | Given a non-empty string containing only digits, determine the total number of ways to decode it. 9 | 10 | The answer is guaranteed to fit in a 32-bit integer. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: s = "12" 17 | Output: 2 18 | Explanation: It could be decoded as "AB" (1 2) or "L" (12). 19 | Example 2: 20 | 21 | Input: s = "226" 22 | Output: 3 23 | Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). 24 | Example 3: 25 | 26 | Input: s = "0" 27 | Output: 0 28 | Explanation: There is no character that is mapped to a number starting with '0'. We cannot ignore a zero when we face it while decoding. So, each '0' should be part of "10" --> 'J' or "20" --> 'T'. 29 | Example 4: 30 | 31 | Input: s = "1" 32 | Output: 1 33 | 34 | 35 | Constraints: 36 | 37 | 1 <= s.length <= 100 38 | s contains only digits and may contain leading zero(s). 39 | */ 40 | class Solution { 41 | 42 | public int numDecodings(String s) { 43 | if(s == null || s.length() == 0) 44 | return 0; 45 | 46 | int dp[] = new int[s.length() + 1]; 47 | dp[0] = 1; //if it is double digit then there is one solution 48 | dp[1] = s.charAt(0) == '0' ? 0 : 1; 49 | 50 | for(int it=1; it= 10 && number <=26) { 61 | dp[currentDpWays] += dp[currentDpWays - 2]; 62 | } 63 | } 64 | 65 | 66 | return dp[dp.length - 1]; 67 | } 68 | } -------------------------------------------------------------------------------- /src/DecodeXORedArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | There is a hidden integer array arr that consists of n non-negative integers. 3 | 4 | It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3]. 5 | 6 | You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0]. 7 | 8 | Return the original array arr. It can be proved that the answer exists and is unique. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: encoded = [1,2,3], first = 1 15 | Output: [1,0,2,1] 16 | Explanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3] 17 | Example 2: 18 | 19 | Input: encoded = [6,2,7,3], first = 4 20 | Output: [4,2,0,7,4] 21 | 22 | 23 | Constraints: 24 | 25 | 2 <= n <= 104 26 | encoded.length == n - 1 27 | 0 <= encoded[i] <= 105 28 | 0 <= first <= 105 29 | 30 | */ 31 | class Solution { 32 | public int[] decode(int[] encoded, int first) { 33 | int[] result = new int[encoded.length + 1]; 34 | result[0] = first; 35 | 36 | for(int it=0; it map = new HashMap<>(); 50 | ArrayList result = new ArrayList<>(); 51 | 52 | public List findDuplicateSubtrees(TreeNode root) { 53 | dfs(root); 54 | return result; 55 | } 56 | 57 | private String dfs(TreeNode node) { 58 | 59 | if(node == null) 60 | return null; 61 | 62 | StringBuilder sb = new StringBuilder(); 63 | if(node.left != null) { 64 | sb.append(dfs(node.left)); 65 | sb.append(":"); 66 | } 67 | 68 | sb.append(node.val); 69 | 70 | if(node.right != null) { 71 | sb.append(","); 72 | sb.append(dfs(node.right)); 73 | } 74 | 75 | String str = sb.toString(); 76 | if(map.containsKey(str)) { 77 | if(!map.get(str)) { 78 | map.put(str, true); 79 | result.add(node); 80 | } 81 | } else { 82 | map.put(str, false); 83 | } 84 | return str; 85 | } 86 | } -------------------------------------------------------------------------------- /src/EditDistance.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. 3 | 4 | You have the following three operations permitted on a word: 5 | 6 | Insert a character 7 | Delete a character 8 | Replace a character 9 | 10 | 11 | Example 1: 12 | 13 | Input: word1 = "horse", word2 = "ros" 14 | Output: 3 15 | Explanation: 16 | horse -> rorse (replace 'h' with 'r') 17 | rorse -> rose (remove 'r') 18 | rose -> ros (remove 'e') 19 | Example 2: 20 | 21 | Input: word1 = "intention", word2 = "execution" 22 | Output: 5 23 | Explanation: 24 | intention -> inention (remove 't') 25 | inention -> enention (replace 'i' with 'e') 26 | enention -> exention (replace 'n' with 'x') 27 | exention -> exection (replace 'n' with 'c') 28 | exection -> execution (insert 'u') 29 | 30 | 31 | Constraints: 32 | 33 | 0 <= word1.length, word2.length <= 500 34 | word1 and word2 consist of lowercase English letters. 35 | */ 36 | class Solution { 37 | public int minDistance(String word1, String word2) { 38 | int[][] dp = new int[word1.length()+1][word2.length()+1]; 39 | 40 | for(int it=0; it<=word1.length(); it++) 41 | dp[it][0] = it; 42 | for(int it=0; it<=word2.length(); it++) 43 | dp[0][it] = it; 44 | 45 | for(int i=0; i diffWaysToCompute(String input) { 24 | 25 | if(input.length() == 1) { 26 | List res = new ArrayList<>(); 27 | res.add(Integer.parseInt(input)); 28 | return res; 29 | } 30 | 31 | List result = new ArrayList<>(); 32 | for(int it=0; it left = diffWaysToCompute(input.substring(0, it)); 38 | List right = diffWaysToCompute(input.substring(it+1)); 39 | 40 | for(int leftNum : left) { 41 | for(int rightNum : right) { 42 | if(ch == '+') { 43 | result.add(leftNum + rightNum); 44 | } else if(ch == '-') { 45 | result.add(leftNum - rightNum); 46 | } else { 47 | result.add(leftNum * rightNum); 48 | } 49 | } 50 | } 51 | } 52 | } 53 | 54 | if(result.size() == 0) result.add(Integer.parseInt(input)); 55 | return result; 56 | } 57 | } -------------------------------------------------------------------------------- /src/FailyTemperatures.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. 3 | 4 | For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. 5 | 6 | Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. 7 | */ 8 | class Solution { 9 | public int[] dailyTemperatures(int[] T) { 10 | 11 | int[] result = new int[T.length]; 12 | Stack stack = new Stack<>(); 13 | 14 | for(int it=T.length-1; it>=0; it--) { 15 | while(!stack.isEmpty() && T[it] >= T[stack.peek()]) 16 | stack.pop(); 17 | result[it] = stack.isEmpty() ? 0 : stack.peek() - it; 18 | stack.push(it); 19 | } 20 | 21 | return result; 22 | } 23 | } -------------------------------------------------------------------------------- /src/FindDuplicate.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. 3 | 4 | There is only one repeated number in nums, return this repeated number. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [1,3,4,2,2] 11 | Output: 2 12 | Example 2: 13 | 14 | Input: nums = [3,1,3,4,2] 15 | Output: 3 16 | Example 3: 17 | 18 | Input: nums = [1,1] 19 | Output: 1 20 | Example 4: 21 | 22 | Input: nums = [1,1,2] 23 | Output: 1 24 | 25 | 26 | Constraints: 27 | 28 | 2 <= n <= 3 * 104 29 | nums.length == n + 1 30 | 1 <= nums[i] <= n 31 | All the integers in nums appear only once except for precisely one integer which appears two or more times. 32 | 33 | 34 | Follow up: 35 | 36 | How can we prove that at least one duplicate number must exist in nums? 37 | Can you solve the problem without modifying the array nums? 38 | Can you solve the problem using only constant, O(1) extra space? 39 | Can you solve the problem with runtime complexity less than O(n2)? 40 | */ 41 | 42 | //Using tortoise and rabbit stratergy 43 | class Solution { 44 | public int findDuplicate(int[] nums) { 45 | int rabbit = nums[0], tortoise = nums[0]; 46 | 47 | do { 48 | rabbit = nums[nums[rabbit]]; 49 | tortoise = nums[tortoise]; 50 | } while(rabbit != tortoise); 51 | 52 | tortoise = nums[0]; 53 | while(tortoise != rabbit) { 54 | tortoise = nums[tortoise]; 55 | rabbit = nums[rabbit]; 56 | } 57 | 58 | return rabbit; 59 | } 60 | } 61 | 62 | //Using array modification 63 | class Solution { 64 | public int findDuplicate(int[] nums) { 65 | 66 | for(int it=0; it nums.length || nums[it] <= 0) 39 | nums[it] = 1; 40 | } 41 | 42 | if(!foundOne) return 1; 43 | 44 | for(int it=0; it 0) 47 | nums[val] = -nums[val]; 48 | } 49 | int it = 0; 50 | for(; it 0) 52 | break; 53 | } 54 | return it + 1; 55 | } 56 | } -------------------------------------------------------------------------------- /src/FrogJump.java: -------------------------------------------------------------------------------- 1 | /* 2 | A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. 3 | 4 | Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. 5 | 6 | If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: stones = [0,1,3,5,6,8,12,17] 13 | Output: true 14 | Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. 15 | Example 2: 16 | 17 | Input: stones = [0,1,2,3,4,8,9,11] 18 | Output: false 19 | Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. 20 | 21 | 22 | Constraints: 23 | 24 | 2 <= stones.length <= 2000 25 | 0 <= stones[i] <= 231 - 1 26 | stones[0] == 0 27 | */ 28 | class Solution { 29 | 30 | private int goal; 31 | private HashSet stones; 32 | private HashMap memo; 33 | 34 | public boolean canCross(int[] stones) { 35 | goal = stones[stones.length - 1]; 36 | this.stones = new HashSet<>(); 37 | this.memo = new HashMap<>(); 38 | for(int it=0; it goal || k < 1 || k > goal) 45 | return false; 46 | 47 | if(curr == goal) 48 | return true; 49 | 50 | if(!stones.contains(curr)) 51 | return false; 52 | 53 | if(memo.containsKey(k + "," + curr)) 54 | return memo.get(k+","+curr); 55 | boolean result = recur(k, curr+k) || recur(k+1, curr+k+1) || recur(k-1, curr+k-1); 56 | memo.put(k+","+curr, result); 57 | return result; 58 | } 59 | } -------------------------------------------------------------------------------- /src/GenerateParanthesis.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: n = 3 9 | Output: ["((()))","(()())","(())()","()(())","()()()"] 10 | Example 2: 11 | 12 | Input: n = 1 13 | Output: ["()"] 14 | 15 | 16 | Constraints: 17 | 18 | 1 <= n <= 8 19 | 20 | */ 21 | class Solution { 22 | 23 | List result; 24 | 25 | public List generateParenthesis(int n) { 26 | result = new ArrayList<>(); 27 | if(n == 0) 28 | return result; 29 | 30 | recur("(", n, 1, n-1); 31 | 32 | return result; 33 | } 34 | 35 | private void recur(String curr, int n, int balance, int opensLeft) { 36 | if(n == 0) { 37 | result.add(curr); 38 | return; 39 | } 40 | 41 | if(balance > 0) 42 | recur(curr + ")", n - 1, balance-1, opensLeft); 43 | 44 | if(opensLeft > 0) 45 | recur(curr+"(", n, balance + 1, opensLeft - 1); 46 | } 47 | } -------------------------------------------------------------------------------- /src/GoodNodesInBT.java: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X. 4 | 5 | Return the number of good nodes in the binary tree. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | 12 | 13 | Input: root = [3,1,4,3,null,1,5] 14 | Output: 4 15 | Explanation: Nodes in blue are good. 16 | Root Node (3) is always a good node. 17 | Node 4 -> (3,4) is the maximum value in the path starting from the root. 18 | Node 5 -> (3,4,5) is the maximum value in the path 19 | Node 3 -> (3,1,3) is the maximum value in the path. 20 | Example 2: 21 | 22 | 23 | 24 | Input: root = [3,3,null,4,2] 25 | Output: 3 26 | Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it. 27 | Example 3: 28 | 29 | Input: root = [1] 30 | Output: 1 31 | Explanation: Root is considered as good. 32 | 33 | 34 | Constraints: 35 | 36 | The number of nodes in the binary tree is in the range [1, 10^5]. 37 | Each node's value is between [-10^4, 10^4]. 38 | * Definition for a binary tree node. 39 | * public class TreeNode { 40 | * int val; 41 | * TreeNode left; 42 | * TreeNode right; 43 | * TreeNode() {} 44 | * TreeNode(int val) { this.val = val; } 45 | * TreeNode(int val, TreeNode left, TreeNode right) { 46 | * this.val = val; 47 | * this.left = left; 48 | * this.right = right; 49 | * } 50 | * } 51 | */ 52 | class Solution { 53 | public int goodNodes(TreeNode root) { 54 | if(root == null) return 0; 55 | 56 | return dfs(root, Integer.MIN_VALUE); 57 | } 58 | 59 | private int dfs(TreeNode node, int max) { 60 | 61 | int count = 0; 62 | 63 | if(node.val >= max) { 64 | max = node.val; 65 | count = 1; 66 | } 67 | 68 | if(node.right != null) { 69 | count += dfs(node.right, max); 70 | } 71 | if(node.left != null) { 72 | count += dfs(node.left, max); 73 | } 74 | 75 | return count; 76 | } 77 | } -------------------------------------------------------------------------------- /src/GroupAnagram.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of strings strs, group the anagrams together. You can return the answer in any order. 3 | 4 | An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: strs = ["eat","tea","tan","ate","nat","bat"] 11 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]] 12 | Example 2: 13 | 14 | Input: strs = [""] 15 | Output: [[""]] 16 | Example 3: 17 | 18 | Input: strs = ["a"] 19 | Output: [["a"]] 20 | 21 | 22 | Constraints: 23 | 24 | 1 <= strs.length <= 104 25 | 0 <= strs[i].length <= 100 26 | strs[i] consists of lower-case English letters. 27 | 28 | */ 29 | class Solution { 30 | public List> groupAnagrams(String[] strs) { 31 | if (strs.length == 0) return new ArrayList(); 32 | Map ans = new HashMap(); 33 | int[] count = new int[26]; 34 | for (String s : strs) { 35 | Arrays.fill(count, 0); 36 | for (char c : s.toCharArray()) count[c - 'a']++; 37 | 38 | StringBuilder sb = new StringBuilder(""); 39 | for (int i = 0; i < 26; i++) { 40 | sb.append('#'); 41 | sb.append(count[i]); 42 | } 43 | String key = sb.toString(); 44 | if (!ans.containsKey(key)) ans.put(key, new ArrayList()); 45 | ans.get(key).add(s); 46 | } 47 | return new ArrayList(ans.values()); 48 | } 49 | } -------------------------------------------------------------------------------- /src/HalfVowelCount.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. 3 | 4 | Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters. 5 | 6 | Return true if a and b are alike. Otherwise, return false. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: s = "book" 13 | Output: true 14 | Explanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike. 15 | Example 2: 16 | 17 | Input: s = "textbook" 18 | Output: false 19 | Explanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike. 20 | Notice that the vowel o is counted twice. 21 | Example 3: 22 | 23 | Input: s = "MerryChristmas" 24 | Output: false 25 | Example 4: 26 | 27 | Input: s = "AbCdEfGh" 28 | Output: true 29 | 30 | 31 | Constraints: 32 | 33 | 2 <= s.length <= 1000 34 | s.length is even. 35 | s consists of uppercase and lowercase letters. 36 | */ 37 | class Solution { 38 | public boolean halvesAreAlike(String s) { 39 | int n = s.length(); 40 | 41 | HashSet set = new HashSet<>(); 42 | set.add('a'); 43 | set.add('e'); 44 | set.add('i'); 45 | set.add('o'); 46 | set.add('u'); 47 | set.add('A'); 48 | set.add('E'); 49 | set.add('I'); 50 | set.add('O'); 51 | set.add('U'); 52 | 53 | int count = 0; 54 | for (int i = 0; i < n / 2; i++) { 55 | if (set.contains(s.charAt(i))) { 56 | count++; 57 | } 58 | } 59 | 60 | int secondHalfCount = 0; 61 | for (int i = n / 2; i < n; i++) { 62 | if (set.contains(s.charAt(i))) { 63 | secondHalfCount++; 64 | } 65 | } 66 | 67 | return count == secondHalfCount; 68 | } 69 | } -------------------------------------------------------------------------------- /src/HammingDistance.java: -------------------------------------------------------------------------------- 1 | /* 2 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 3 | 4 | Given two integers x and y, return the Hamming distance between them. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: x = 1, y = 4 11 | Output: 2 12 | Explanation: 13 | 1 (0 0 0 1) 14 | 4 (0 1 0 0) 15 | ↑ ↑ 16 | The above arrows point to positions where the corresponding bits are different. 17 | Example 2: 18 | 19 | Input: x = 3, y = 1 20 | Output: 1 21 | 22 | 23 | Constraints: 24 | 25 | 0 <= x, y <= 231 - 1 26 | */ 27 | 28 | //Efficient loop to count 1s 29 | class Solution { 30 | public int hammingDistance(int x, int y) { 31 | int xor = x ^ y; 32 | int distance = 0; 33 | while (xor != 0) { 34 | distance += 1; 35 | // remove the rightmost bit of '1' 36 | xor = xor & (xor - 1); 37 | } 38 | return distance; 39 | } 40 | } 41 | 42 | //Full iteration to count 1s 43 | class Solution { 44 | public int hammingDistance(int x, int y) { 45 | int diff = x ^ y; 46 | int count = 0; 47 | while(diff > 0) { 48 | if((diff & 1) == 1) 49 | count++; 50 | diff = diff >> 1; 51 | } 52 | 53 | return count; 54 | } 55 | } -------------------------------------------------------------------------------- /src/IncreasingPermutaion.java: -------------------------------------------------------------------------------- 1 | /* 2 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 3 | 4 | If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). 5 | 6 | The replacement must be in place and use only constant extra memory. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [1,2,3] 13 | Output: [1,3,2] 14 | Example 2: 15 | 16 | Input: nums = [3,2,1] 17 | Output: [1,2,3] 18 | Example 3: 19 | 20 | Input: nums = [1,1,5] 21 | Output: [1,5,1] 22 | Example 4: 23 | 24 | Input: nums = [1] 25 | Output: [1] 26 | 27 | 28 | Constraints: 29 | 30 | 1 <= nums.length <= 100 31 | 0 <= nums[i] <= 100 32 | */ 33 | 34 | class Solution { 35 | public void nextPermutation(int[] nums) { 36 | if(nums.length <= 1) return; 37 | 38 | int left = -1, right = -1; 39 | 40 | for(int it=nums.length-2; it>=0; it--) { 41 | if(nums[it] < nums[it+1]) { 42 | left = it; 43 | break; 44 | } 45 | } 46 | 47 | if(left == -1) { 48 | reverse(nums, 0, nums.length-1); 49 | return; 50 | } 51 | 52 | for(right=nums.length-1; right>=0; right--) { 53 | if(nums[right] > nums[left]){ 54 | swap(nums, left, right); 55 | break; 56 | } 57 | } 58 | reverse(nums, left+1, nums.length - 1); 59 | } 60 | 61 | private void reverse(int[] nums, int left, int right) { 62 | while(left < right) { 63 | swap(nums, left, right); 64 | left++; 65 | right--; 66 | } 67 | } 68 | 69 | private void swap(int[] nums, int i, int j) { 70 | int temp = nums[i]; 71 | nums[i] = nums[j]; 72 | nums[j] = temp; 73 | } 74 | } -------------------------------------------------------------------------------- /src/IntervalIntersection.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order. 3 | 4 | Return the intersection of these two interval lists. 5 | 6 | A closed interval [a, b] (with a < b) denotes the set of real numbers x with a <= x <= b. 7 | 8 | The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3]. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | 15 | Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]] 16 | Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] 17 | Example 2: 18 | 19 | Input: firstList = [[1,3],[5,9]], secondList = [] 20 | Output: [] 21 | Example 3: 22 | 23 | Input: firstList = [], secondList = [[4,8],[10,12]] 24 | Output: [] 25 | Example 4: 26 | 27 | Input: firstList = [[1,7]], secondList = [[3,10]] 28 | Output: [[3,7]] 29 | 30 | 31 | Constraints: 32 | 33 | 0 <= firstList.length, secondList.length <= 1000 34 | firstList.length + secondList.length >= 1 35 | 0 <= starti < endi <= 109 36 | endi < starti+1 37 | 0 <= startj < endj <= 109 38 | endj < startj+1 39 | 40 | */ 41 | class Solution { 42 | public int[][] intervalIntersection(int[][] firstList, int[][] secondList) { 43 | LinkedList result = new LinkedList<>(); 44 | 45 | int firstIt = 0, secondIt = 0; 46 | while(firstIt < firstList.length && secondIt < secondList.length) { 47 | 48 | int start = Math.max(firstList[firstIt][0], secondList[secondIt][0]); 49 | int end = Math.min(firstList[firstIt][1], secondList[secondIt][1]); 50 | 51 | if(start <= end) 52 | result.add(new int[] {start, end}); 53 | 54 | if(firstList[firstIt][1] < secondList[secondIt][1]) 55 | firstIt++; 56 | else 57 | secondIt++; 58 | } 59 | 60 | return result.toArray(new int[result.size()][]); 61 | } 62 | } -------------------------------------------------------------------------------- /src/InvertBinaryTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | Invert a binary tree. 3 | 4 | Example: 5 | 6 | Input: 7 | 8 | 4 9 | / \ 10 | 2 7 11 | / \ / \ 12 | 1 3 6 9 13 | Output: 14 | 15 | 4 16 | / \ 17 | 7 2 18 | / \ / \ 19 | 9 6 3 1 20 | 21 | * Definition for a binary tree node. 22 | * public class TreeNode { 23 | * int val; 24 | * TreeNode left; 25 | * TreeNode right; 26 | * TreeNode() {} 27 | * TreeNode(int val) { this.val = val; } 28 | * TreeNode(int val, TreeNode left, TreeNode right) { 29 | * this.val = val; 30 | * this.left = left; 31 | * this.right = right; 32 | * } 33 | * } 34 | */ 35 | class Solution { 36 | public TreeNode invertTree(TreeNode root) { 37 | return invert(root); 38 | } 39 | 40 | private TreeNode invert(TreeNode node) { 41 | if(node == null) 42 | return null; 43 | 44 | TreeNode right = node.right; 45 | 46 | node.right = invert(node.left); 47 | node.left = invert(right); 48 | 49 | return node; 50 | } 51 | } -------------------------------------------------------------------------------- /src/IslandCount.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an m x n 2d grid map of '1's (land) and '0's (water), return the number of islands. 3 | 4 | An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: grid = [ 11 | ["1","1","1","1","0"], 12 | ["1","1","0","1","0"], 13 | ["1","1","0","0","0"], 14 | ["0","0","0","0","0"] 15 | ] 16 | Output: 1 17 | Example 2: 18 | 19 | Input: grid = [ 20 | ["1","1","0","0","0"], 21 | ["1","1","0","0","0"], 22 | ["0","0","1","0","0"], 23 | ["0","0","0","1","1"] 24 | ] 25 | Output: 3 26 | 27 | 28 | Constraints: 29 | 30 | m == grid.length 31 | n == grid[i].length 32 | 1 <= m, n <= 300 33 | grid[i][j] is '0' or '1'. 34 | */ 35 | 36 | class Solution { 37 | public int numIslands(char[][] grid) { 38 | boolean[][] visited = new boolean[grid.length][grid[0].length]; 39 | 40 | int count = 0; 41 | for(int i=0; i= 0 && grid[x-1][y] != '0' && !visited[x-1][y]) 59 | dfs(grid, visited, x-1, y, rows, columns); 60 | if(y-1 >= 0 && grid[x][y-1] != '0' && !visited[x][y-1]) 61 | dfs(grid, visited, x, y-1, rows, columns); 62 | } 63 | } -------------------------------------------------------------------------------- /src/KDiffPairs.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. 3 | 4 | A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: 5 | 6 | 0 <= i, j < nums.length 7 | i != j 8 | |nums[i] - nums[j]| == k 9 | Notice that |val| denotes the absolute value of val. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: nums = [3,1,4,1,5], k = 2 16 | Output: 2 17 | Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). 18 | Although we have two 1s in the input, we should only return the number of unique pairs. 19 | Example 2: 20 | 21 | Input: nums = [1,2,3,4,5], k = 1 22 | Output: 4 23 | Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). 24 | Example 3: 25 | 26 | Input: nums = [1,3,1,5,4], k = 0 27 | Output: 1 28 | Explanation: There is one 0-diff pair in the array, (1, 1). 29 | Example 4: 30 | 31 | Input: nums = [1,2,4,4,3,3,0,9,2,3], k = 3 32 | Output: 2 33 | Example 5: 34 | 35 | Input: nums = [-1,-2,-3], k = 1 36 | Output: 2 37 | 38 | 39 | Constraints: 40 | 41 | 1 <= nums.length <= 104 42 | -107 <= nums[i] <= 107 43 | 0 <= k <= 107 44 | */ 45 | class Solution { 46 | public int findPairs(int[] nums, int k) { 47 | HashMap freq = new HashMap<>(); 48 | for(int it=0; it entry : freq.entrySet()) { 54 | int num = entry.getKey(); 55 | int count = entry.getValue(); 56 | 57 | //at least one number must be smaller 58 | if(k > 0 && freq.containsKey(num + k)) 59 | result++; 60 | else if(k == 0 && count > 1) //same number is present 2 times or more 61 | result++; 62 | } 63 | 64 | return result; 65 | } 66 | } -------------------------------------------------------------------------------- /src/KLargestElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 3 | 4 | Example 1: 5 | 6 | Input: [3,2,1,5,6,4] and k = 2 7 | Output: 5 8 | Example 2: 9 | 10 | Input: [3,2,3,1,2,4,5,5,6] and k = 4 11 | Output: 4 12 | Note: 13 | You may assume k is always valid, 1 ≤ k ≤ array's length. 14 | 15 | */ 16 | class Solution { 17 | 18 | PriorityQueue heap = null; 19 | 20 | public int findKthLargest(int[] nums, int k) { 21 | if(nums == null || nums.length == 0) 22 | return 0; 23 | 24 | heap = new PriorityQueue<>(nums.length, new Comparator() { 25 | @Override 26 | public int compare(Integer one, Integer two) { 27 | return two - one; 28 | } 29 | }); 30 | 31 | for(int it=0; it squares = new LinkedList<>(); 37 | squares.add(new int[]{0, 0}); 38 | 39 | Set visited = new HashSet<>(); 40 | visited.add(new Pair(0, 0)); 41 | 42 | int count =0; 43 | 44 | while(!squares.isEmpty()) { 45 | int len = squares.size(); 46 | 47 | for(int i=0; i= -1 && move[1] >= -1) { 56 | visited.add(new Pair(move[0], move[1])); 57 | squares.add(move); 58 | } 59 | 60 | } 61 | } 62 | 63 | count++; 64 | } 65 | 66 | return -1; 67 | } 68 | 69 | } -------------------------------------------------------------------------------- /src/Kosaraju.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | ArrayList[] adjList, rev; 3 | Stack stack; 4 | boolean[] visited; 5 | 6 | public int findCircleNum(int[][] isConnected) { 7 | 8 | int n = isConnected.length; 9 | 10 | visited = new boolean[n]; 11 | stack = new Stack<>(); 12 | adjList = new ArrayList[n]; 13 | rev = new ArrayList[n]; 14 | 15 | for(int it=0; it(); 17 | rev[it] = new ArrayList<>(); 18 | } 19 | 20 | for(int row=0; row=0; it--) { 30 | if(chr[max] < chr[it]) { 31 | max = it; 32 | } else if(chr[max] == chr[it]) { 33 | int x = it, y = max; 34 | while(x < n && y < n) { 35 | if(chr[x] > chr[y]) { 36 | max = it; 37 | break; 38 | }else if(chr[x] < chr[y]) { 39 | break; 40 | } 41 | if(x >= max) { 42 | max = it; 43 | break; 44 | } 45 | x++;y++; 46 | } 47 | if(y==n) max = it; 48 | } 49 | } 50 | 51 | return new String(chr, max, n - max); 52 | } 53 | } -------------------------------------------------------------------------------- /src/LetterCombinationPhoneNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. 3 | 4 | A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. 5 | 6 | 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: digits = "23" 13 | Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] 14 | Example 2: 15 | 16 | Input: digits = "" 17 | Output: [] 18 | Example 3: 19 | 20 | Input: digits = "2" 21 | Output: ["a","b","c"] 22 | 23 | 24 | Constraints: 25 | 26 | 0 <= digits.length <= 4 27 | digits[i] is a digit in the range ['2', '9']. 28 | */ 29 | class Solution { 30 | private HashMap map = new HashMap<>(); 31 | private List result = new ArrayList<>(); 32 | 33 | public List letterCombinations(String digits) { 34 | 35 | if(digits.length() == 0) 36 | return result; 37 | 38 | map.put(2, "abc"); 39 | map.put(3, "def"); 40 | map.put(4, "ghi"); 41 | map.put(5, "jkl"); 42 | map.put(6, "mno"); 43 | map.put(7, "pqrs"); 44 | map.put(8, "tuv"); 45 | map.put(9, "wxyz"); 46 | 47 | backtrack("", digits); 48 | 49 | return result; 50 | } 51 | 52 | private void backtrack(String curr, String digits) { 53 | 54 | if(digits.length() == 0) { 55 | result.add(curr); 56 | } else { 57 | String letters = map.get(digits.charAt(0) - '0'); 58 | String remainingDigits = digits.substring(1); 59 | for(int it=0; it> levelOrder(TreeNode root) { 45 | 46 | List> result = new ArrayList<>(); 47 | 48 | if(root == null) 49 | return result; 50 | 51 | Queue queue = new LinkedList<>(); 52 | queue.offer(root); 53 | 54 | while(!queue.isEmpty()) { 55 | 56 | ArrayList currLevel = new ArrayList<>(); 57 | int size = queue.size(); 58 | 59 | for(int it=0; it= 11, return true, next allowed timestamp for "foo" is 28 | // 11 + 10 = 21 29 | 30 | 31 | Constraints: 32 | 33 | 0 <= timestamp <= 109 34 | Every timestamp will be passed in non-decreasing order (chronological order). 35 | 1 <= message.length <= 30 36 | At most 104 calls will be made to shouldPrintMessage. 37 | 38 | */ 39 | class Logger { 40 | 41 | private HashMap map; 42 | 43 | public Logger() { 44 | map = new HashMap<>(); 45 | } 46 | 47 | public boolean shouldPrintMessage(int timestamp, String message) { 48 | if(map.containsKey(message)) { 49 | if(timestamp - map.get(message) >= 10) { 50 | map.put(message, timestamp); 51 | return true; 52 | } 53 | return false; 54 | } else { 55 | map.put(message, timestamp); 56 | return true; 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/LongestBeautifulSubstring.java: -------------------------------------------------------------------------------- 1 | /* 2 | A string is considered beautiful if it satisfies the following conditions: 3 | 4 | Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it. 5 | The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.). 6 | For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", and "aaaeeeooo" are not beautiful. 7 | 8 | Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0. 9 | 10 | A substring is a contiguous sequence of characters in a string. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: word = "aeiaaioaaaaeiiiiouuuooaauuaeiu" 17 | Output: 13 18 | Explanation: The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13. 19 | Example 2: 20 | 21 | Input: word = "aeeeiiiioooauuuaeiou" 22 | Output: 5 23 | Explanation: The longest beautiful substring in word is "aeiou" of length 5. 24 | Example 3: 25 | 26 | Input: word = "a" 27 | Output: 0 28 | Explanation: There is no beautiful substring, so return 0. 29 | 30 | 31 | Constraints: 32 | 33 | 1 <= word.length <= 5 * 105 34 | word consists of characters 'a', 'e', 'i', 'o', and 'u'. 35 | */ 36 | class Solution { 37 | public int longestBeautifulSubstring(String word) { 38 | boolean[] windowFreq = new boolean[26]; 39 | int size = 0, windowStart = 0; 40 | 41 | int max = 0; 42 | 43 | for(int windowEnd=0; windowEnd < word.length(); windowEnd++) { 44 | char chr = word.charAt(windowEnd); 45 | 46 | if(!windowFreq[chr - 'a']) 47 | size++; 48 | windowFreq[chr - 'a'] = true; 49 | 50 | 51 | if(windowEnd != windowStart && word.charAt(windowEnd - 1) > chr) { 52 | windowStart = windowEnd; 53 | Arrays.fill(windowFreq, false); 54 | size = 1; 55 | windowFreq[chr - 'a'] = true; 56 | } 57 | 58 | if(size == 5) { 59 | max = Math.max(max, windowEnd - windowStart + 1); 60 | } 61 | 62 | } 63 | 64 | return max; 65 | } 66 | 67 | } -------------------------------------------------------------------------------- /src/LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | 4 | If there is no common prefix, return an empty string "". 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: strs = ["flower","flow","flight"] 11 | Output: "fl" 12 | Example 2: 13 | 14 | Input: strs = ["dog","racecar","car"] 15 | Output: "" 16 | Explanation: There is no common prefix among the input strings. 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= strs.length <= 200 22 | 0 <= strs[i].length <= 200 23 | strs[i] consists of only lower-case English letters. 24 | */ 25 | class Solution { 26 | public String longestCommonPrefix(String[] strs) { 27 | 28 | if(strs.length == 0) 29 | return ""; 30 | 31 | StringBuilder sb = new StringBuilder(); 32 | 33 | for(int firstWordIt=0; firstWordIt= strs[wordIt].length() || strs[wordIt].charAt(firstWordIt) != chr) 38 | return sb.toString(); 39 | } 40 | 41 | sb.append(chr); 42 | } 43 | 44 | return sb.toString(); 45 | } 46 | } -------------------------------------------------------------------------------- /src/LongestCommonSubSequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | 1143. Longest Common Subsequence 3 | Medium 4 | Given two strings text1 and text2, return the length of their longest common subsequence. 5 | 6 | A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings. 7 | 8 | 9 | 10 | If there is no common subsequence, return 0. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: text1 = "abcde", text2 = "ace" 17 | Output: 3 18 | Explanation: The longest common subsequence is "ace" and its length is 3. 19 | Example 2: 20 | 21 | Input: text1 = "abc", text2 = "abc" 22 | Output: 3 23 | Explanation: The longest common subsequence is "abc" and its length is 3. 24 | Example 3: 25 | 26 | Input: text1 = "abc", text2 = "def" 27 | Output: 0 28 | Explanation: There is no such common subsequence, so the result is 0. 29 | 30 | 31 | Constraints: 32 | 33 | 1 <= text1.length <= 1000 34 | 1 <= text2.length <= 1000 35 | The input strings consist of lowercase English characters only. 36 | */ 37 | class Solution { 38 | public int longestCommonSubsequence(String text1, String text2) { 39 | int[][] dp = new int[text1.length()+1][text2.length()+1]; 40 | 41 | for(int i=0; i= 0 && prevCol >= 0 && prevRow < rows && prevCol < cols) 57 | prevVal = dp[prevRow][prevCol][it]; 58 | 59 | dp[row][col][it] = prevVal + 1; 60 | max = Math.max(dp[row][col][it], max); 61 | } 62 | } 63 | } 64 | 65 | /*for(int row=0; row set = new HashSet<>(); 34 | 35 | for(int it : nums) 36 | set.add(it); 37 | 38 | int max = 0; 39 | for(int it=0; it= 3 5 | There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: 6 | arr[0] < arr[1] < ... < arr[i - 1] < arr[i] 7 | arr[i] > arr[i + 1] > ... > arr[arr.length - 1] 8 | Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: arr = [2,1,4,7,3,2,5] 15 | Output: 5 16 | Explanation: The largest mountain is [1,4,7,3,2] which has length 5. 17 | Example 2: 18 | 19 | Input: arr = [2,2,2] 20 | Output: 0 21 | Explanation: There is no mountain. 22 | 23 | 24 | Constraints: 25 | 26 | 1 <= arr.length <= 104 27 | 0 <= arr[i] <= 104 28 | 29 | 30 | Follow up: 31 | 32 | Can you solve it using only one pass? 33 | Can you solve it in O(1) space? 34 | */ 35 | class Solution { 36 | public int longestMountain(int[] arr) { 37 | 38 | if(arr.length < 3) 39 | return 0; 40 | 41 | int it = 1, result = 0; 42 | 43 | while(it < arr.length) { 44 | 45 | //climb up 46 | int start = it - 1; 47 | while(it < arr.length && arr[it-1] < arr[it]) 48 | it++; 49 | 50 | if(start == it - 1) { 51 | it += 1; 52 | continue; 53 | } 54 | 55 | int peak = it - 1; 56 | //climb down 57 | while( it < arr.length && arr[it-1] > arr[it]) 58 | it++; 59 | 60 | if(peak == it - 1) { 61 | it+=1; 62 | continue; 63 | } 64 | 65 | int end = it - 1; 66 | 67 | int len = end - start + 1; 68 | result = Math.max(len, result); 69 | } 70 | return result; 71 | } 72 | } -------------------------------------------------------------------------------- /src/LongestSubstringEvenVowels.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: s = "eleetminicoworoep" 9 | Output: 13 10 | Explanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u. 11 | Example 2: 12 | 13 | Input: s = "leetcodeisgreat" 14 | Output: 5 15 | Explanation: The longest substring is "leetc" which contains two e's. 16 | Example 3: 17 | 18 | Input: s = "bcbcbc" 19 | Output: 6 20 | Explanation: In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times. 21 | 22 | 23 | Constraints: 24 | 25 | 1 <= s.length <= 5 x 10^5 26 | s contains only lowercase English letters. 27 | */ 28 | class Solution { 29 | public int findTheLongestSubstring(String s) { 30 | int res = 0 , cur = 0, n = s.length(); 31 | HashMap seen = new HashMap<>(); 32 | seen.put(0, -1); 33 | for (int i = 0; i < n; ++i) { 34 | cur ^= 1 << ("aeiou".indexOf(s.charAt(i)) + 1 ) >> 1; 35 | seen.putIfAbsent(cur, i); 36 | res = Math.max(res, i - seen.get(cur)); 37 | } 38 | return res; 39 | } 40 | } -------------------------------------------------------------------------------- /src/MatrixRotaton.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). 3 | 4 | You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | 11 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 12 | Output: [[7,4,1],[8,5,2],[9,6,3]] 13 | Example 2: 14 | 15 | 16 | Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] 17 | Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] 18 | Example 3: 19 | 20 | Input: matrix = [[1]] 21 | Output: [[1]] 22 | Example 4: 23 | 24 | Input: matrix = [[1,2],[3,4]] 25 | Output: [[3,1],[4,2]] 26 | 27 | 28 | Constraints: 29 | 30 | matrix.length == n 31 | matrix[i].length == n 32 | 1 <= n <= 20 33 | -1000 <= matrix[i][j] <= 1000 34 | 35 | */ 36 | class Solution { 37 | public void rotate(int[][] matrix) { 38 | transpose(matrix); 39 | reverse(matrix); 40 | } 41 | 42 | private void transpose(int[][] matrix) { 43 | for(int row=0; row=left; it--) 40 | result[down][it] = num++; 41 | down--; 42 | 43 | for(int it=down; it>=top; it--) 44 | result[it][left] = num++; 45 | left++; 46 | } 47 | 48 | return result; 49 | } 50 | } -------------------------------------------------------------------------------- /src/MaxLenConcat.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of strings arr. String s is a concatenation of a sub-sequence of arr which have unique characters. 3 | 4 | Return the maximum possible length of s. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: arr = ["un","iq","ue"] 11 | Output: 4 12 | Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique". 13 | Maximum length is 4. 14 | Example 2: 15 | 16 | Input: arr = ["cha","r","act","ers"] 17 | Output: 6 18 | Explanation: Possible solutions are "chaers" and "acters". 19 | Example 3: 20 | 21 | Input: arr = ["abcdefghijklmnopqrstuvwxyz"] 22 | Output: 26 23 | 24 | 25 | Constraints: 26 | 27 | 1 <= arr.length <= 16 28 | 1 <= arr[i].length <= 26 29 | arr[i] contains only lower case English letters. 30 | */ 31 | 32 | //DP with memo 33 | class Solution { 34 | 35 | private int max(List arr, int currChars, int index, HashMap memo) { 36 | if(index == arr.size()) 37 | return 0; 38 | 39 | String key = index + "," + currChars; 40 | if(memo.containsKey(key)) 41 | return memo.get(key); 42 | 43 | boolean isValid = true; 44 | 45 | String curr = arr.get(index); 46 | int currUsedChar = 0; 47 | for(int it=0; it arr) { 69 | return max(arr, 0, 0, new HashMap<>()); 70 | } 71 | } -------------------------------------------------------------------------------- /src/MaxSubArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: nums = [-2,1,-3,4,-1,2,1,-5,4] 9 | Output: 6 10 | Explanation: [4,-1,2,1] has the largest sum = 6. 11 | Example 2: 12 | 13 | Input: nums = [1] 14 | Output: 1 15 | Example 3: 16 | 17 | Input: nums = [5,4,-1,7,8] 18 | Output: 23 19 | 20 | 21 | Constraints: 22 | 23 | 1 <= nums.length <= 3 * 104 24 | -105 <= nums[i] <= 105 25 | 26 | 27 | Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 28 | 29 | */ 30 | class Solution { 31 | public int maxSubArray(int[] nums) { 32 | int n = nums.length, maxSoFar = nums[0]; 33 | int maxEndingHere = maxSoFar < 0 ? 0 : maxSoFar; 34 | int startIndex = 0; 35 | 36 | for(int it=1; it map = new HashMap<>(); 40 | 41 | int max = 0; 42 | 43 | for(int it=0; it maxLetters) { 55 | isValid = false; 56 | break; 57 | } 58 | } 59 | } 60 | 61 | if(isValid) { 62 | int freq = map.getOrDefault(curr, 0) + 1; 63 | map.put(curr, freq); 64 | max = Math.max(max, freq); 65 | } 66 | } 67 | 68 | return max; 69 | } 70 | } -------------------------------------------------------------------------------- /src/MaximumSquare.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | 9 | Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] 10 | Output: 4 11 | Example 2: 12 | 13 | 14 | Input: matrix = [["0","1"],["1","0"]] 15 | Output: 1 16 | Example 3: 17 | 18 | Input: matrix = [["0"]] 19 | Output: 0 20 | */ 21 | class Solution { 22 | public int maximalSquare(char[][] matrix) { 23 | if(matrix.length == 0) return 0; 24 | 25 | int dp[] = new int[matrix[0].length+1]; 26 | 27 | int max = Integer.MIN_VALUE, prev = 0; 28 | for(int row=0; row < matrix.length; row++) { 29 | for(int col=0; col < matrix[row].length; col++) { 30 | int temp = dp[col+1]; 31 | if(matrix[row][col] == '1') { 32 | dp[col+1] = Math.min(dp[col+1], Math.min(dp[col], prev)) + 1; 33 | max = Math.max(max, dp[col+1]); 34 | } else { 35 | dp[col+1] = 0; 36 | } 37 | prev = temp; 38 | } 39 | } 40 | return max*max; 41 | } 42 | } -------------------------------------------------------------------------------- /src/MeetingRoom.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: intervals = [[0,30],[5,10],[15,20]] 9 | Output: 2 10 | Example 2: 11 | 12 | Input: intervals = [[7,10],[2,4]] 13 | Output: 1 14 | 15 | 16 | Constraints: 17 | 18 | 1 <= intervals.length <= 104 19 | 0 <= starti < endi <= 106 20 | */ 21 | class Solution { 22 | public int minMeetingRooms(int[][] intervals) { 23 | if(intervals.length <= 0) return 0; 24 | 25 | Arrays.sort(intervals, new Comparator() { 26 | @Override 27 | public int compare(int[] first, int[] second) { 28 | return first[0] - second[0]; 29 | } 30 | }); 31 | 32 | PriorityQueue pq = new PriorityQueue<>(); 33 | pq.add(intervals[0][1]); 34 | for(int it=1; it < intervals.length; it++) { 35 | 36 | if(pq.peek() <= intervals[it][0]) { 37 | pq.poll(); 38 | } 39 | 40 | pq.add(intervals[it][1]); 41 | } 42 | return pq.size(); 43 | } 44 | } -------------------------------------------------------------------------------- /src/MergeInterval.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: intervals = [[1,3],[2,6],[8,10],[15,18]] 9 | Output: [[1,6],[8,10],[15,18]] 10 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 11 | Example 2: 12 | 13 | Input: intervals = [[1,4],[4,5]] 14 | Output: [[1,5]] 15 | Explanation: Intervals [1,4] and [4,5] are considered overlapping. 16 | 17 | 18 | Constraints: 19 | 20 | 1 <= intervals.length <= 104 21 | intervals[i].length == 2 22 | 0 <= starti <= endi <= 104 23 | 24 | */ 25 | class Solution { 26 | public int[][] merge(int[][] intervals) { 27 | 28 | if(intervals.length == 0) return new int[0][0]; 29 | 30 | LinkedList result = new LinkedList<>(); 31 | 32 | Arrays.sort(intervals, new Comparator() { 33 | @Override 34 | public int compare(int[] a, int[] b) { 35 | return a[0] - b[0]; 36 | } 37 | }); 38 | 39 | for(int it=0; it it = result.iterator(); it.hasNext();){ 52 | Integer[] next = it.next(); 53 | resultarr[++index][0] = next[0]; 54 | resultarr[index][1] = next[1]; 55 | }*/ 56 | return result.toArray(new int[result.size()][]); 57 | } 58 | } -------------------------------------------------------------------------------- /src/MergeSortedArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 3 | 4 | The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 11 | Output: [1,2,2,3,5,6] 12 | Example 2: 13 | 14 | Input: nums1 = [1], m = 1, nums2 = [], n = 0 15 | Output: [1] 16 | 17 | 18 | Constraints: 19 | 20 | nums1.length == m + n 21 | nums2.length == n 22 | 0 <= m, n <= 200 23 | 1 <= m + n <= 200 24 | -109 <= nums1[i], nums2[i] <= 109 25 | 26 | 27 | Follow up: Can you come up with an algorithm that runs in O(m + n) time? 28 | */ 29 | class Solution { 30 | public void merge(int[] nums1, int m, int[] nums2, int n) { 31 | int largestIndex = nums1.length - 1; 32 | m--; 33 | n--; 34 | 35 | 36 | while(largestIndex >= 0) { 37 | 38 | if(m >= 0 && (n < 0 || nums1[m] > nums2[n])) { 39 | nums1[largestIndex--] = nums1[m--]; 40 | } else { 41 | nums1[largestIndex--] = nums2[n--]; 42 | } 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /src/MergeSortedLinkedList.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | 10 | Input: l1 = [1,2,4], l2 = [1,3,4] 11 | Output: [1,1,2,3,4,4] 12 | Example 2: 13 | 14 | Input: l1 = [], l2 = [] 15 | Output: [] 16 | Example 3: 17 | 18 | Input: l1 = [], l2 = [0] 19 | Output: [0] 20 | 21 | 22 | Constraints: 23 | 24 | The number of nodes in both lists is in the range [0, 50]. 25 | -100 <= Node.val <= 100 26 | Both l1 and l2 are sorted in non-decreasing order. 27 | 28 | 29 | * Definition for singly-linked list. 30 | * public class ListNode { 31 | * int val; 32 | * ListNode next; 33 | * ListNode() {} 34 | * ListNode(int val) { this.val = val; } 35 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 36 | * } 37 | */ 38 | class Solution { 39 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 40 | ListNode preHead = new ListNode(); 41 | ListNode prev = preHead; 42 | 43 | while(l1 != null && l2 != null) { 44 | if(l1.val <= l2.val) { 45 | prev.next = l1; 46 | l1 = l1.next; 47 | } else { 48 | prev.next = l2; 49 | l2 = l2.next; 50 | } 51 | prev = prev.next; 52 | } 53 | 54 | prev.next = l1 == null ? l2 : l1; 55 | return preHead.next; 56 | } 57 | } -------------------------------------------------------------------------------- /src/MinDeletionCost.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s and an array of integers cost where cost[i] is the cost of deleting the ith character in s. 3 | 4 | Return the minimum cost of deletions such that there are no two identical letters next to each other. 5 | 6 | Notice that you will delete the chosen characters at the same time, in other words, after deleting a character, the costs of deleting other characters will not change. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: s = "abaac", cost = [1,2,3,4,5] 13 | Output: 3 14 | Explanation: Delete the letter "a" with cost 3 to get "abac" (String without two identical letters next to each other). 15 | Example 2: 16 | 17 | Input: s = "abc", cost = [1,2,3] 18 | Output: 0 19 | Explanation: You don't need to delete any character because there are no identical letters next to each other. 20 | Example 3: 21 | 22 | Input: s = "aabaa", cost = [1,2,3,4,1] 23 | Output: 2 24 | Explanation: Delete the first and the last character, getting the string ("aba"). 25 | 26 | 27 | Constraints: 28 | 29 | s.length == cost.length 30 | 1 <= s.length, cost.length <= 10^5 31 | 1 <= cost[i] <= 10^4 32 | s contains only lowercase English letters. 33 | */ 34 | 35 | //Greedy solution 36 | class Solution { 37 | public int minCost(String s, int[] cost) { 38 | 39 | int total = 0; 40 | for(int it=0; it stack = new Stack<>(); 4 | private Stack minStack = new Stack<>(); 5 | 6 | 7 | public MinStack() { } 8 | 9 | 10 | public void push(int x) { 11 | 12 | // We always put the number onto the main stack. 13 | stack.push(x); 14 | 15 | // If the min stack is empty, or this number is smaller than 16 | // the top of the min stack, put it on with a count of 1. 17 | if (minStack.isEmpty() || x < minStack.peek()[0]) { 18 | minStack.push(new int[]{x, 1}); 19 | } 20 | 21 | // Else if this number is equal to what's currently at the top 22 | // of the min stack, then increment the count at the top by 1. 23 | else if (x == minStack.peek()[0]) { 24 | minStack.peek()[1]++; 25 | } 26 | } 27 | 28 | 29 | public void pop() { 30 | 31 | // If the top of min stack is the same as the top of stack 32 | // then we need to decrement the count at the top by 1. 33 | if (stack.peek().equals(minStack.peek()[0])) { 34 | minStack.peek()[1]--; 35 | } 36 | 37 | // If the count at the top of min stack is now 0, then remove 38 | // that value as we're done with it. 39 | if (minStack.peek()[1] == 0) { 40 | minStack.pop(); 41 | } 42 | 43 | // And like before, pop the top of the main stack. 44 | stack.pop(); 45 | } 46 | 47 | 48 | public int top() { 49 | return stack.peek(); 50 | } 51 | 52 | 53 | public int getMin() { 54 | return minStack.peek()[0]; 55 | } 56 | } -------------------------------------------------------------------------------- /src/MinSubSequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given strings S and T, find the minimum (contiguous) substring W of S, so that T is a subsequence of W. 3 | 4 | If there is no such window in S that covers all characters in T, return the empty string "". If there are multiple such minimum-length windows, return the one with the left-most starting index. 5 | 6 | Example 1: 7 | 8 | Input: 9 | S = "abcdebdde", T = "bde" 10 | Output: "bcde" 11 | Explanation: 12 | "bcde" is the answer because it occurs before "bdde" which has the same length. 13 | "deb" is not a smaller window because the elements of T in the window must occur in order. 14 | 15 | 16 | Note: 17 | 18 | All the strings in the input will only contain lowercase letters. 19 | The length of S will be in the range [1, 20000]. 20 | The length of T will be in the range [1, 100]. 21 | */ 22 | class Solution { 23 | public String minWindow(String S, String T) { 24 | int j = 0; 25 | int min = S.length() + 1; 26 | int start = 0, end = 0; 27 | for(int it=0; it= 0) { 34 | if(S.charAt(it) == T.charAt(j)) 35 | j--; 36 | it--; 37 | } 38 | it++; 39 | 40 | if(currEnd - it + 1 < min) { 41 | min = currEnd - it + 1; 42 | start = it; 43 | end = currEnd; 44 | } 45 | j = 0; 46 | } 47 | } 48 | 49 | return min == S.length() + 1 ? "" : S.substring(start, end+1); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/MinimumDistanceWords.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice" 9 | Output: 3 10 | Example 2: 11 | 12 | Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding" 13 | Output: 1 14 | 15 | 16 | Constraints: 17 | 18 | 1 <= wordsDict.length <= 3 * 104 19 | 1 <= wordsDict[i].length <= 10 20 | wordsDict[i] consists of lowercase English letters. 21 | word1 and word2 are in wordsDict. 22 | word1 != word2 23 | */ 24 | class Solution { 25 | public int shortestDistance(String[] words, String word1, String word2) { 26 | int i1 = -1, i2 = -1; 27 | int minDistance = words.length; 28 | for (int i = 0; i < words.length; i++) { 29 | if (words[i].equals(word1)) { 30 | i1 = i; 31 | } else if (words[i].equals(word2)) { 32 | i2 = i; 33 | } 34 | 35 | if (i1 != -1 && i2 != -1) { 36 | minDistance = Math.min(minDistance, Math.abs(i1 - i2)); 37 | } 38 | } 39 | return minDistance; 40 | } 41 | } -------------------------------------------------------------------------------- /src/MinimumOperationsToStrictlyInc.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1. 3 | 4 | For example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3]. 5 | Return the minimum number of operations needed to make nums strictly increasing. 6 | 7 | An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: nums = [1,1,1] 14 | Output: 3 15 | Explanation: You can do the following operations: 16 | 1) Increment nums[2], so nums becomes [1,1,2]. 17 | 2) Increment nums[1], so nums becomes [1,2,2]. 18 | 3) Increment nums[2], so nums becomes [1,2,3]. 19 | Example 2: 20 | 21 | Input: nums = [1,5,2,4,1] 22 | Output: 14 23 | Example 3: 24 | 25 | Input: nums = [8] 26 | Output: 0 27 | 28 | 29 | Constraints: 30 | 31 | 1 <= nums.length <= 5000 32 | 1 <= nums[i] <= 104 33 | */ 34 | class Solution { 35 | public int minOperations(int[] nums) { 36 | int result = 0, len = nums.length; 37 | 38 | for(int it=1; it= nums[it]) { 40 | result += ((nums[it - 1] - nums[it]) + 1); 41 | nums[it] = nums[it-1] + 1; 42 | } 43 | } 44 | 45 | return result; 46 | } 47 | } -------------------------------------------------------------------------------- /src/MoveZeros.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. 3 | 4 | Note that you must do this in-place without making a copy of the array. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: nums = [0,1,0,3,12] 11 | Output: [1,3,12,0,0] 12 | Example 2: 13 | 14 | Input: nums = [0] 15 | Output: [0] 16 | 17 | 18 | Constraints: 19 | 20 | 1 <= nums.length <= 104 21 | -231 <= nums[i] <= 231 - 1 22 | 23 | 24 | Follow up: Could you minimize the total number of operations done? 25 | */ 26 | 27 | class Solution { 28 | public void moveZeroes(int[] nums) { 29 | int nonZeroIndex = 0; 30 | 31 | for(int it=0; it= 0 && j < s.length() && Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(s.charAt(j))) { 44 | i--; 45 | j++; 46 | } 47 | i++; 48 | j--; 49 | if(i < 0 || j >= s.length() || i > j) 50 | return; 51 | String palindrome = s.substring(i, j+1); 52 | if(palindrome.length() > result.length()) 53 | result = palindrome; 54 | } 55 | } -------------------------------------------------------------------------------- /src/PartitionArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array nums, partition it into two (contiguous) subarrays left and right so that: 3 | 4 | Every element in left is less than or equal to every element in right. 5 | left and right are non-empty. 6 | left has the smallest possible size. 7 | Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: nums = [5,0,3,8,6] 14 | Output: 3 15 | Explanation: left = [5,0,3], right = [8,6] 16 | Example 2: 17 | 18 | Input: nums = [1,1,1,0,6,12] 19 | Output: 4 20 | Explanation: left = [1,1,1,0], right = [6,12] 21 | 22 | 23 | Note: 24 | 25 | 2 <= nums.length <= 30000 26 | 0 <= nums[i] <= 106 27 | It is guaranteed there is at least one way to partition nums as described. 28 | */ 29 | class Solution { 30 | public int partitionDisjoint(int[] nums) { 31 | int[] maxLeft = new int[nums.length]; 32 | int[] minRight = new int[nums.length]; 33 | 34 | int val = Integer.MIN_VALUE; 35 | 36 | for(int it=0; it=0; it--) { 43 | val = Math.min(val, nums[it]); 44 | minRight[it] = val; 45 | } 46 | 47 | for(int it=1; it partitionLabels(String S) { 23 | List result = new ArrayList<>(); 24 | 25 | if(S.length() == 0) return result; 26 | int[] dict = new int[26]; 27 | 28 | for(int it=0; it> set = new HashSet<>(); 32 | 33 | int currX = 0, currY = 0; 34 | set.add(new Pair(currX, currY)); 35 | 36 | for(int it=0; it newPair = new Pair(currX, currY); 48 | 49 | if(set.contains(newPair)) { 50 | return true; 51 | } 52 | 53 | set.add(newPair); 54 | } 55 | 56 | return false; 57 | } 58 | } -------------------------------------------------------------------------------- /src/Permutation.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: nums = [1,2,3] 9 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 10 | Example 2: 11 | 12 | Input: nums = [0,1] 13 | Output: [[0,1],[1,0]] 14 | Example 3: 15 | 16 | Input: nums = [1] 17 | Output: [[1]] 18 | 19 | 20 | Constraints: 21 | 22 | 1 <= nums.length <= 6 23 | -10 <= nums[i] <= 10 24 | All the integers of nums are unique. 25 | */ 26 | class Solution { 27 | private void backtrack(int[] nums, int start, ArrayList> result) { 28 | 29 | if(start == nums.length - 1) { 30 | ArrayList list = new ArrayList<>(); 31 | for(int n : nums){ 32 | list.add(n); 33 | } 34 | result.add(list); 35 | return; 36 | } 37 | 38 | for(int it=start; it> permute(int[] nums) { 53 | ArrayList> result = new ArrayList<>(); 54 | backtrack(nums, 0, result); 55 | return result; 56 | } 57 | } -------------------------------------------------------------------------------- /src/PoisonTime.java: -------------------------------------------------------------------------------- 1 | /* 2 | In LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, you need to output the total time that Ashe is in poisoned condition. 3 | 4 | You may assume that Teemo attacks at the very beginning of a specific time point, and makes Ashe be in poisoned condition immediately. 5 | 6 | Example 1: 7 | 8 | Input: [1,4], 2 9 | Output: 4 10 | Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately. 11 | This poisoned status will last 2 seconds until the end of time point 2. 12 | And at time point 4, Teemo attacks Ashe again, and causes Ashe to be in poisoned status for another 2 seconds. 13 | So you finally need to output 4. 14 | 15 | 16 | Example 2: 17 | 18 | Input: [1,2], 2 19 | Output: 3 20 | Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned. 21 | This poisoned status will last 2 seconds until the end of time point 2. 22 | However, at the beginning of time point 2, Teemo attacks Ashe again who is already in poisoned status. 23 | Since the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, it will stop at the end of time point 3. 24 | So you finally need to output 3. 25 | 26 | 27 | Note: 28 | 29 | You may assume the length of given time series array won't exceed 10000. 30 | You may assume the numbers in the Teemo's attacking time series and his poisoning time duration per attacking are non-negative integers, which won't exceed 10,000,000. 31 | */ 32 | class Solution { 33 | public int findPoisonedDuration(int[] timeSeries, int duration) { 34 | if(duration <= 0) return 0; 35 | if(timeSeries == null || timeSeries.length == 0) return 0; 36 | 37 | int pastPoisonTime = timeSeries[0] - 1; 38 | int result = 0; 39 | 40 | for(int it=0; it 0; it/=2) { 41 | if(it % 2 == 1) 42 | ans = ans * curr; 43 | curr = curr * curr; 44 | } 45 | 46 | return ans; 47 | } 48 | } -------------------------------------------------------------------------------- /src/PrefixSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums, find the sum of the elements between indices left and right inclusive, where (left <= right). 3 | 4 | Implement the NumArray class: 5 | 6 | NumArray(int[] nums) initializes the object with the integer array nums. 7 | int sumRange(int left, int right) returns the sum of the elements of the nums array in the range [left, right] inclusive (i.e., sum(nums[left], nums[left + 1], ... , nums[right])). 8 | 9 | 10 | Example 1: 11 | 12 | Input 13 | ["NumArray", "sumRange", "sumRange", "sumRange"] 14 | [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] 15 | Output 16 | [null, 1, -1, -3] 17 | 18 | Explanation 19 | NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); 20 | numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3) 21 | numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1)) 22 | numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1)) 23 | 24 | 25 | Constraints: 26 | 27 | 1 <= nums.length <= 104 28 | -105 <= nums[i] <= 105 29 | 0 <= left <= right < nums.length 30 | At most 104 calls will be made to sumRange. 31 | */ 32 | class NumArray { 33 | 34 | int[] nums; 35 | 36 | public NumArray(int[] nums) { 37 | int sum = 0; 38 | this.nums = nums; 39 | for(int it=0; it 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 3 | 4 | Example: 5 | 6 | Input: [1,2,3,4] 7 | Output: [24,12,8,6] 8 | Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. 9 | 10 | Note: Please solve it without division and in O(n). 11 | 12 | Follow up: 13 | Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) 14 | */ 15 | class Solution { 16 | public int[] productExceptSelf(int[] nums) { 17 | if(nums.length == 0) return new int[0]; 18 | 19 | int[] res = new int[nums.length]; 20 | 21 | res[0] = 1; 22 | 23 | for(int it=1; it=0; it--) { 29 | prev = prev * nums[it+1]; 30 | res[it] = prev * res[it]; 31 | } 32 | 33 | return res; 34 | } 35 | } -------------------------------------------------------------------------------- /src/RangeAddition.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi. 3 | 4 | Count and return the number of maximum integers in the matrix after performing all the operations. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | 11 | Input: m = 3, n = 3, ops = [[2,2],[3,3]] 12 | Output: 4 13 | Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4. 14 | Example 2: 15 | 16 | Input: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] 17 | Output: 4 18 | Example 3: 19 | 20 | Input: m = 3, n = 3, ops = [] 21 | Output: 9 22 | 23 | 24 | Constraints: 25 | 26 | 1 <= m, n <= 4 * 104 27 | 1 <= ops.length <= 104 28 | ops[i].length == 2 29 | 1 <= ai <= m 30 | 1 <= bi <= n 31 | */ 32 | 33 | 34 | //O(n) 35 | class Solution { 36 | public int maxCount(int m, int n, int[][] ops) { 37 | 38 | int minM = m; 39 | int minN = n; 40 | 41 | for(int it=0; it counts = new Stack<>(); 39 | char[] sa = s.toCharArray(); 40 | int j = 0; 41 | for (int i = 0; i < s.length(); ++i, ++j) { 42 | sa[j] = sa[i]; 43 | if (j == 0 || sa[j] != sa[j - 1]) { 44 | counts.push(1); 45 | } else { 46 | int incremented = counts.pop() + 1; 47 | if (incremented == k) { 48 | j = j - k; 49 | } else { 50 | counts.push(incremented); 51 | } 52 | } 53 | } 54 | return new String(sa, 0, j); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/RemoveKDigits.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. 3 | 4 | Note: 5 | The length of num is less than 10002 and will be ≥ k. 6 | The given num does not contain any leading zero. 7 | Example 1: 8 | 9 | Input: num = "1432219", k = 3 10 | Output: "1219" 11 | Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. 12 | Example 2: 13 | 14 | Input: num = "10200", k = 1 15 | Output: "200" 16 | Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. 17 | Example 3: 18 | 19 | Input: num = "10", k = 2 20 | Output: "0" 21 | Explanation: Remove all the digits from the number and it is left with nothing which is 0. 22 | */ 23 | class Solution { 24 | public String removeKdigits(String num, int k) { 25 | if(num.length() == 0) 26 | return ""; 27 | 28 | if(num.length() <= k) 29 | return "0"; 30 | 31 | LinkedList list = new LinkedList<>(); 32 | list.addLast(num.charAt(0)); 33 | 34 | for(int it=1; it digit && k > 0) { 38 | list.removeLast(); 39 | k--; 40 | } 41 | list.addLast(digit); 42 | } 43 | 44 | for(int it=0; it n) { 55 | result = result.next; 56 | } 57 | 58 | counter++; 59 | trav = trav.next; 60 | } 61 | 62 | if(counter == n) { 63 | head = head.next; 64 | } else { 65 | result.next = result.next.next; 66 | } 67 | 68 | return head; 69 | } 70 | } -------------------------------------------------------------------------------- /src/ReverseInteger.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. 3 | 4 | Assume the environment does not allow you to store 64-bit integers (signed or unsigned). 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: x = 123 11 | Output: 321 12 | Example 2: 13 | 14 | Input: x = -123 15 | Output: -321 16 | Example 3: 17 | 18 | Input: x = 120 19 | Output: 21 20 | Example 4: 21 | 22 | Input: x = 0 23 | Output: 0 24 | 25 | 26 | Constraints: 27 | 28 | -231 <= x <= 231 - 1 29 | */ 30 | class Solution { 31 | public int reverse(int x) { 32 | int result = 0; 33 | int sign = x < 0 ? -1 : 1; 34 | x = Math.abs(x); 35 | if(x < 0) 36 | x = Integer.MAX_VALUE; 37 | 38 | while(x != 0) { 39 | int digit = x % 10; 40 | if(result > Integer.MAX_VALUE/10 || (result == Integer.MAX_VALUE/10 && digit > Integer.MAX_VALUE%10)) 41 | return 0; 42 | 43 | result = result * 10 + digit; 44 | //System.out.println(result); 45 | x /= 10; 46 | } 47 | 48 | return result*sign; 49 | } 50 | } -------------------------------------------------------------------------------- /src/ReverseLL.java: -------------------------------------------------------------------------------- 1 | /** 2 | Reverse a singly linked list. 3 | 4 | Example: 5 | 6 | Input: 1->2->3->4->5->NULL 7 | Output: 5->4->3->2->1->NULL 8 | 9 | * Definition for singly-linked list. 10 | * public class ListNode { 11 | * int val; 12 | * ListNode next; 13 | * ListNode() {} 14 | * ListNode(int val) { this.val = val; } 15 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 16 | * } 17 | */ 18 | class Solution { 19 | public ListNode reverseList(ListNode head) { 20 | ListNode prev = null, trav = head, next = null; 21 | 22 | while(trav != null) { 23 | next = trav.next; 24 | trav.next = prev; 25 | prev = trav; 26 | trav = next; 27 | } 28 | return prev; 29 | } 30 | } -------------------------------------------------------------------------------- /src/ReverseNumberMax.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. 3 | 4 | Assume the environment does not allow you to store 64-bit integers (signed or unsigned). 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: x = 123 11 | Output: 321 12 | Example 2: 13 | 14 | Input: x = -123 15 | Output: -321 16 | Example 3: 17 | 18 | Input: x = 120 19 | Output: 21 20 | Example 4: 21 | 22 | Input: x = 0 23 | Output: 0 24 | 25 | 26 | Constraints: 27 | 28 | -231 <= x <= 231 - 1 29 | */ 30 | class Solution { 31 | public int reverse(int x) { 32 | int rev = 0; 33 | while (x != 0) { 34 | int pop = x % 10; 35 | x /= 10; 36 | if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0; 37 | if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0; 38 | rev = rev * 10 + pop; 39 | } 40 | return rev; 41 | } 42 | } -------------------------------------------------------------------------------- /src/ReversePartOfLinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | 9 | Input: head = [1,2,3,4,5], left = 2, right = 4 10 | Output: [1,4,3,2,5] 11 | Example 2: 12 | 13 | Input: head = [5], left = 1, right = 1 14 | Output: [5] 15 | 16 | 17 | Constraints: 18 | 19 | The number of nodes in the list is n. 20 | 1 <= n <= 500 21 | -500 <= Node.val <= 500 22 | 1 <= left <= right <= n 23 | 24 | 25 | Follow up: Could you do it in one pass? 26 | */ 27 | class Solution { 28 | public ListNode reverseBetween(ListNode head, int left, int right) { 29 | ListNode trav = head, prevStart = null; 30 | int counter = 0; 31 | 32 | while(trav != null) { 33 | counter++; 34 | if(counter == left) { 35 | ListNode newEnd = trav, prev = prevStart; 36 | 37 | while(trav != null && counter <= right) { 38 | ListNode next = trav.next; 39 | trav.next = prev; 40 | prev = trav; 41 | trav = next; 42 | counter++; 43 | } 44 | if(prevStart != null) 45 | prevStart.next = prev; 46 | newEnd.next = trav; 47 | if(left == 1) 48 | return prev; 49 | break; 50 | } 51 | prevStart = trav; 52 | trav = trav.next; 53 | } 54 | return head; 55 | } 56 | } -------------------------------------------------------------------------------- /src/ReverseStringGroups.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string. 3 | 4 | If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: s = "abcdefg", k = 2 11 | Output: "bacdfeg" 12 | Example 2: 13 | 14 | Input: s = "abcd", k = 2 15 | Output: "bacd" 16 | 17 | 18 | Constraints: 19 | 20 | 1 <= s.length <= 104 21 | s consists of only lowercase English letters. 22 | 1 <= k <= 104 23 | */ 24 | class Solution { 25 | public String reverseStr(String s, int k) { 26 | char[] strArr = s.toCharArray(); 27 | 28 | for(int start=0; start < strArr.length; start += 2 * k) { 29 | int end = Math.min(start + k - 1, strArr.length - 1); 30 | reverse(strArr, start, end); 31 | } 32 | 33 | 34 | return new String(strArr); 35 | } 36 | 37 | private void reverse(char[] arr, int start, int end) { 38 | for(int i=start, j=end; i (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ... 29 | 30 | 31 | Constraints: 32 | 33 | 1 <= instructions.length <= 100 34 | instructions[i] is 'G', 'L' or, 'R'. 35 | */ 36 | 37 | class Solution { 38 | public boolean isRobotBounded(String instructions) { 39 | //Directions - north 0, east 1, south 2, west 3 40 | 41 | int[][] movements = new int[][] { {0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 42 | 43 | int direction = 0; // North 44 | int currX = 0, currY = 0; //Current Position 45 | 46 | for(int it=0; it> visited = new HashSet(); 5 | Robot robot; 6 | 7 | public void goBack() { 8 | robot.turnRight(); 9 | robot.turnRight(); 10 | robot.move(); 11 | robot.turnRight(); 12 | robot.turnRight(); 13 | } 14 | 15 | public void backtrack(int row, int col, int d) { 16 | visited.add(new Pair(row, col)); 17 | robot.clean(); 18 | // going clockwise : 0: 'up', 1: 'right', 2: 'down', 3: 'left' 19 | for (int i = 0; i < 4; ++i) { 20 | int newD = (d + i) % 4; 21 | int newRow = row + directions[newD][0]; 22 | int newCol = col + directions[newD][1]; 23 | 24 | if (!visited.contains(new Pair(newRow, newCol)) && robot.move()) { 25 | backtrack(newRow, newCol, newD); 26 | goBack(); 27 | } 28 | // turn the robot following chosen direction : clockwise 29 | robot.turnRight(); 30 | } 31 | } 32 | 33 | public void cleanRoom(Robot robot) { 34 | this.robot = robot; 35 | backtrack(0, 0, 0); 36 | } 37 | } -------------------------------------------------------------------------------- /src/RunLengthEncoding.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a run-length encoded lowercase alphabet string s, implement an iterator which is the decoded version of s: 3 | 4 | next() polls the next element in the iterator 5 | hasnext() which returns whether the next element exists 6 | Constraints 7 | 8 | n ≤ 100,000 where n is the number of calls to next and hasnext 9 | Example 1 10 | Input 11 | methods = ["constructor", "next", "hasnext", "next", "next", "hasnext"] 12 | arguments = [["2a1b"], [], [], [], [], []]` 13 | Output 14 | [None, "a", True, "a", "b", False] 15 | */ 16 | class RunLengthDecodedIterator { 17 | String s; 18 | int indx = 0; 19 | Deque list; 20 | 21 | private String getNum() { 22 | StringBuilder sb = new StringBuilder(); 23 | for(;indx(); 32 | for(;indx max) { 33 | result = max; 34 | max = digit; 35 | } else if(digit > result && digit != max) { 36 | result = digit; 37 | } 38 | } 39 | } 40 | 41 | return result; 42 | } 43 | } -------------------------------------------------------------------------------- /src/SetMatrixZero.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an m x n matrix. If an element is 0, set its entire row and column to 0. Do it in-place. 3 | 4 | Follow up: 5 | 6 | A straight forward solution using O(mn) space is probably a bad idea. 7 | A simple improvement uses O(m + n) space, but still not the best solution. 8 | Could you devise a constant space solution? 9 | 10 | 11 | Example 1: 12 | 13 | 14 | Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] 15 | Output: [[1,0,1],[0,0,0],[1,0,1]] 16 | Example 2: 17 | 18 | 19 | Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] 20 | Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]] 21 | 22 | 23 | Constraints: 24 | 25 | m == matrix.length 26 | n == matrix[0].length 27 | 1 <= m, n <= 200 28 | -231 <= matrix[i][j] <= 231 - 1 29 | */ 30 | class Solution { 31 | 32 | public void setZeroes(int[][] matrix) { 33 | 34 | int rows = matrix.length; 35 | if(rows == 0) return; 36 | int cols = matrix[0].length; 37 | boolean isColZero = false; 38 | 39 | for(int row=0; row> 1); 54 | while(left <= right) { 55 | mid = left + ((right - left) >> 1); 56 | 57 | int sum = calculate(nums, mid); 58 | if(sum > threshold) 59 | left = mid + 1; 60 | else 61 | right = mid - 1; 62 | } 63 | 64 | return left; 65 | } 66 | 67 | private int calculate(int[] nums, int divisor) { 68 | int sum = 0; 69 | for(int it=0; it= right) 16 | return; 17 | 18 | int index = partition(nums, left, right); 19 | quickSort(nums, left, index - 1); 20 | quickSort(nums, index + 1, right); 21 | 22 | } 23 | 24 | private int partition(int[] nums, int low, int high) { 25 | int pivot = nums[high], left = low - 1, right = high; 26 | 27 | while(true) { 28 | while(++left <= high && nums[left] < pivot); 29 | while(--right >= low && nums[right] > pivot); 30 | 31 | if(left >= right) 32 | break; 33 | 34 | swap(nums, left, right); 35 | 36 | } 37 | 38 | swap(nums, left, high); 39 | return left; 40 | } 41 | 42 | private void swap(int[] nums, int left, int right) { 43 | int temp = nums[left]; 44 | nums[left] = nums[right]; 45 | nums[right] = temp; 46 | } 47 | 48 | private void mergeSort(int[] nums, int left, int right) { 49 | if(left >= right) 50 | return; 51 | 52 | int mid = left + ((right - left) >> 1); 53 | mergeSort(nums, left, mid); 54 | mergeSort(nums, mid + 1, right); 55 | merge(nums, left, mid, right); 56 | } 57 | 58 | private void merge(int[] nums, int left, int mid, int right) { 59 | 60 | for(int it=left; it<=right; it++) 61 | aux[it] = nums[it]; 62 | 63 | int l = left, r = mid + 1; 64 | for(int it=left; it<=right; it++) { 65 | if(r > right) nums[it] = aux[l++]; 66 | else if(l > mid) nums[it] = aux[r++]; 67 | else if(aux[l] < aux[r]) nums[it] = aux[l++]; 68 | else nums[it] = aux[r++]; 69 | } 70 | 71 | 72 | } 73 | } -------------------------------------------------------------------------------- /src/SpiralMatrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an m x n matrix, return all elements of the matrix in spiral order. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | 9 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] 10 | Output: [1,2,3,6,9,8,7,4,5] 11 | Example 2: 12 | 13 | 14 | Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 15 | Output: [1,2,3,4,8,12,11,10,9,5,6,7] 16 | 17 | 18 | Constraints: 19 | 20 | m == matrix.length 21 | n == matrix[i].length 22 | 1 <= m, n <= 10 23 | -100 <= matrix[i][j] <= 100 24 | 25 | */ 26 | class Solution { 27 | public List spiralOrder(int[][] matrix) { 28 | if(matrix == null || matrix.length == 0) 29 | return null; 30 | 31 | List result = new ArrayList(); 32 | 33 | 34 | int top=0, right = matrix[0].length - 1, bottom = matrix.length - 1, left = 0; 35 | 36 | int total = matrix.length * matrix[0].length; 37 | 38 | while(result.size() < total) { 39 | 40 | //Top Row 41 | for(int it=left; it<=right && result.size() < total; it++) 42 | result.add(matrix[top][it]); 43 | top++; 44 | 45 | //Right Column 46 | for(int it=top; it<=bottom && result.size() < total; it++) 47 | result.add(matrix[it][right]); 48 | right--; 49 | 50 | //Bottom Row 51 | for(int it=right; it>=left && result.size() < total; it--) 52 | result.add(matrix[bottom][it]); 53 | bottom--; 54 | 55 | //Left Column 56 | for(int it=bottom; it>=top && result.size() < total; it--) 57 | result.add(matrix[it][left]); 58 | left++; 59 | 60 | } 61 | 62 | return result; 63 | } 64 | } -------------------------------------------------------------------------------- /src/SplitReverseWords.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an input string s, reverse the order of the words. 3 | 4 | A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. 5 | 6 | Return a string of the words in reverse order concatenated by a single space. 7 | 8 | Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: s = "the sky is blue" 15 | Output: "blue is sky the" 16 | Example 2: 17 | 18 | Input: s = " hello world " 19 | Output: "world hello" 20 | Explanation: Your reversed string should not contain leading or trailing spaces. 21 | Example 3: 22 | 23 | Input: s = "a good example" 24 | Output: "example good a" 25 | Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. 26 | Example 4: 27 | 28 | Input: s = " Bob Loves Alice " 29 | Output: "Alice Loves Bob" 30 | Example 5: 31 | 32 | Input: s = "Alice does not even like bob" 33 | Output: "bob like even not does Alice" 34 | 35 | 36 | Constraints: 37 | 38 | 1 <= s.length <= 104 39 | s contains English letters (upper-case and lower-case), digits, and spaces ' '. 40 | There is at least one word in s. 41 | 42 | 43 | Follow up: 44 | 45 | Could you solve it in-place with O(1) extra space? 46 | */ 47 | class Solution { 48 | public String reverseWords(String s) { 49 | ArrayList words = new ArrayList<>(); 50 | 51 | StringBuilder sb = new StringBuilder(); 52 | for(int it=0; it 0) { 56 | words.add(sb.toString()); 57 | sb = new StringBuilder(); 58 | } 59 | } else { 60 | sb.append(chr); 61 | } 62 | } 63 | if(sb.length() > 0) { 64 | words.add(sb.toString()); 65 | sb = new StringBuilder(); 66 | } 67 | 68 | for(int it=words.size()-1; it>=0; it--) { 69 | sb.append(words.get(it)); 70 | if(it != 0) 71 | sb.append(' '); 72 | } 73 | 74 | return sb.toString(); 75 | } 76 | } -------------------------------------------------------------------------------- /src/SplitWords.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. 3 | 4 | Note: 5 | 6 | The same word in the dictionary may be reused multiple times in the segmentation. 7 | You may assume the dictionary does not contain duplicate words. 8 | Example 1: 9 | 10 | Input: s = "leetcode", wordDict = ["leet", "code"] 11 | Output: true 12 | Explanation: Return true because "leetcode" can be segmented as "leet code". 13 | Example 2: 14 | 15 | Input: s = "applepenapple", wordDict = ["apple", "pen"] 16 | Output: true 17 | Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". 18 | Note that you are allowed to reuse a dictionary word. 19 | Example 3: 20 | 21 | Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] 22 | Output: false 23 | 24 | */ 25 | 26 | //Memo solution 27 | class Solution { 28 | HashSet set; 29 | Boolean[] mem; 30 | public boolean wordBreak(String s, List wordDict) { 31 | set = new HashSet<>(wordDict); 32 | mem =new Boolean[s.length()]; 33 | 34 | return check(s, 0); 35 | } 36 | 37 | private boolean check(String s, int start) { 38 | if(start == s.length()) 39 | return true; 40 | 41 | if(mem[start] != null) 42 | return mem[start]; 43 | 44 | for(int end = start+1; end <= s.length(); end++) { 45 | if(set.contains(s.substring(start, end)) && check(s, end)) 46 | return mem[start] = true; 47 | } 48 | 49 | return mem[start] = false; 50 | } 51 | } 52 | 53 | //DP solution 54 | class Solution { 55 | public boolean wordBreak(String s, List wordDict) { 56 | HashSet set = new HashSet<>(wordDict); 57 | boolean[] dp = new boolean[s.length() + 1]; 58 | dp[0] = true; 59 | 60 | for(int i=0; i rval) { 37 | res[it--] = lval; 38 | left++; 39 | } else { 40 | res[it--] = rval; 41 | right--; 42 | } 43 | } 44 | 45 | return res; 46 | } 47 | } -------------------------------------------------------------------------------- /src/StockProfit.java: -------------------------------------------------------------------------------- 1 | /* 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. 5 | 6 | Note that you cannot sell a stock before you buy one. 7 | 8 | Example 1: 9 | 10 | Input: [7,1,5,3,6,4] 11 | Output: 5 12 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 13 | Not 7-1 = 6, as selling price needs to be larger than buying price. 14 | Example 2: 15 | 16 | Input: [7,6,4,3,1] 17 | Output: 0 18 | Explanation: In this case, no transaction is done, i.e. max profit = 0. 19 | */ 20 | class Solution { 21 | public int maxProfit(int[] prices) { 22 | if(prices.length == 0) return 0; 23 | 24 | int currentMinPrice = Integer.MAX_VALUE; 25 | int max = 0; 26 | 27 | for(int it=0; it prices[it]) 29 | currentMinPrice = prices[it]; 30 | else 31 | max = Math.max(prices[it] - currentMinPrice, max); 32 | } 33 | return max; 34 | } 35 | } -------------------------------------------------------------------------------- /src/StringTransformation.java: -------------------------------------------------------------------------------- 1 | /* 2 | 1153. String Transforms Into Another String 3 | Hard 4 | 5 | 555 6 | 7 | 208 8 | 9 | Add to List 10 | 11 | Share 12 | Given two strings str1 and str2 of the same length, determine whether you can transform str1 into str2 by doing zero or more conversions. 13 | 14 | In one conversion you can convert all occurrences of one character in str1 to any other lowercase English character. 15 | 16 | Return true if and only if you can transform str1 into str2. 17 | 18 | 19 | 20 | Example 1: 21 | 22 | Input: str1 = "aabcc", str2 = "ccdee" 23 | Output: true 24 | Explanation: Convert 'c' to 'e' then 'b' to 'd' then 'a' to 'c'. Note that the order of conversions matter. 25 | Example 2: 26 | 27 | Input: str1 = "leetcode", str2 = "codeleet" 28 | Output: false 29 | Explanation: There is no way to transform str1 to str2. 30 | 31 | 32 | Constraints: 33 | 34 | 1 <= str1.length == str2.length <= 104 35 | str1 and str2 contain only lowercase English letters. 36 | */ 37 | class Solution { 38 | 39 | public boolean canConvert(String str1, String str2) { 40 | if(str1.equals(str2)) 41 | return true; 42 | 43 | HashMap map = new HashMap<>(); 44 | HashSet set = new HashSet<>(); 45 | for(int it=0; it findAnagrams(String s, String p) { 31 | ArrayList result = new ArrayList<>(); 32 | 33 | int len = p.length(); 34 | int[] windowDict = new int[26]; 35 | int[] dict = new int[26]; 36 | 37 | for(int it=0; it= len) { 44 | windowDict[(int)(s.charAt(it - len) - 'a')]--; 45 | } 46 | 47 | if(Arrays.equals(windowDict, dict)) 48 | result.add(it - len + 1); 49 | } 50 | 51 | return result; 52 | } 53 | } -------------------------------------------------------------------------------- /src/SubStringRepeatingChar.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string s, find the length of the longest substring without repeating characters. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: s = "abcabcbb" 9 | Output: 3 10 | Explanation: The answer is "abc", with the length of 3. 11 | Example 2: 12 | 13 | Input: s = "bbbbb" 14 | Output: 1 15 | Explanation: The answer is "b", with the length of 1. 16 | Example 3: 17 | 18 | Input: s = "pwwkew" 19 | Output: 3 20 | Explanation: The answer is "wke", with the length of 3. 21 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 22 | Example 4: 23 | 24 | Input: s = "" 25 | Output: 0 26 | 27 | 28 | Constraints: 29 | 30 | 0 <= s.length <= 5 * 104 31 | s consists of English letters, digits, symbols and spaces. 32 | */ 33 | 34 | class Solution { 35 | public int lengthOfLongestSubstring(String s) { 36 | int max = 0; 37 | int[] dict = new int[128]; 38 | 39 | for(int start=0,end=0; end < s.length(); end++) { 40 | start = Math.max(dict[s.charAt(end)], start); 41 | max = Math.max(max, end - start + 1); 42 | dict[s.charAt(end)] = end + 1; 43 | } 44 | 45 | return max; 46 | } 47 | } 48 | 49 | class Solution { 50 | public int lengthOfLongestSubstring(String s) { 51 | int maxLen = 0, currentLen = 0, start = 0; 52 | 53 | HashMap map = new HashMap<>(); 54 | for(int it=0; it maxLen) 58 | maxLen = currentLen; 59 | int index = map.get(chr); 60 | for(int i=start; i<=index; i++) { 61 | map.remove(s.charAt(i)); 62 | currentLen--; 63 | } 64 | start = index+1; 65 | } 66 | map.put(chr, it); 67 | currentLen++; 68 | } 69 | if(currentLen > maxLen) 70 | maxLen = currentLen; 71 | return maxLen; 72 | } 73 | } -------------------------------------------------------------------------------- /src/SubordinatesSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id. 4 | 5 | For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct. 6 | 7 | Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all their subordinates. 8 | 9 | Example 1: 10 | 11 | Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1 12 | Output: 11 13 | Explanation: 14 | Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11. 15 | 16 | 17 | Note: 18 | 19 | One employee has at most one direct leader and may have several subordinates. 20 | The maximum number of employees won't exceed 2000. 21 | 22 | // Definition for Employee. 23 | class Employee { 24 | public int id; 25 | public int importance; 26 | public List subordinates; 27 | }; 28 | */ 29 | 30 | class Solution { 31 | HashMap map = new HashMap<>(); 32 | public int getImportance(List employees, int id) { 33 | for(Employee emp : employees) 34 | map.put(emp.id, emp); 35 | 36 | Employee emp = map.get(id); 37 | return subsum(emp); 38 | } 39 | 40 | private int subsum(Employee emp) { 41 | int sum = emp.importance; 42 | for(Integer it : emp.subordinates) 43 | sum += subsum(map.get(it)); 44 | return sum; 45 | } 46 | } 47 | 48 | -------------------------------------------------------------------------------- /src/SumDivisible.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers arr of even length n and an integer k. 3 | 4 | We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k. 5 | 6 | Return True If you can find a way to do that or False otherwise. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5 13 | Output: true 14 | Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10). 15 | Example 2: 16 | 17 | Input: arr = [1,2,3,4,5,6], k = 7 18 | Output: true 19 | Explanation: Pairs are (1,6),(2,5) and(3,4). 20 | Example 3: 21 | 22 | Input: arr = [1,2,3,4,5,6], k = 10 23 | Output: false 24 | Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10. 25 | Example 4: 26 | 27 | Input: arr = [-10,10], k = 2 28 | Output: true 29 | Example 5: 30 | 31 | Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3 32 | Output: true 33 | 34 | 35 | Constraints: 36 | 37 | arr.length == n 38 | 1 <= n <= 105 39 | n is even. 40 | -109 <= arr[i] <= 109 41 | 1 <= k <= 105 42 | */ 43 | 44 | // negative -> positive mod 45 | class Solution { 46 | 47 | public boolean canArrange(int[] arr, int k) { 48 | int freq[]=new int[k]; 49 | 50 | for(int it = 0;it < arr.length; it++){ 51 | freq[((arr[it]%k) + k) % k]++; 52 | } 53 | if(freq[0] % 2 != 0) return false; 54 | 55 | for(int it = 1; it < k; it++){ 56 | if(freq[it] != freq[k-it]) 57 | return false; 58 | } 59 | return true; 60 | } 61 | } -------------------------------------------------------------------------------- /src/TargetSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. 3 | 4 | Find out how many ways to assign symbols to make sum of integers equal to target S. 5 | 6 | Example 1: 7 | 8 | Input: nums is [1, 1, 1, 1, 1], S is 3. 9 | Output: 5 10 | Explanation: 11 | 12 | -1+1+1+1+1 = 3 13 | +1-1+1+1+1 = 3 14 | +1+1-1+1+1 = 3 15 | +1+1+1-1+1 = 3 16 | +1+1+1+1-1 = 3 17 | 18 | There are 5 ways to assign symbols to make the sum of nums be target 3. 19 | 20 | 21 | Constraints: 22 | 23 | The length of the given array is positive and will not exceed 20. 24 | The sum of elements in the given array will not exceed 1000. 25 | Your output answer is guaranteed to be fitted in a 32-bit integer. 26 | */ 27 | class Solution { 28 | 29 | int[][] memo; 30 | 31 | public int findTargetSumWays(int[] nums, int S) { 32 | memo = new int[nums.length][2001]; 33 | 34 | for(int row=0; row freq = new HashMap<>(); 27 | for(int it=0; it heap = new PriorityQueue(nums.length, new Comparator() { 31 | @Override 32 | public int compare(Integer one, Integer two) { 33 | return freq.get(one) - freq.get(two); 34 | } 35 | }); 36 | 37 | for(int n : freq.keySet()) { 38 | heap.add(n); 39 | if(heap.size() > k) heap.poll(); 40 | } 41 | 42 | int[] result = new int[k]; 43 | for(int i=0; i topSort(int tasks, int[][] prerequisites) { 5 | 6 | HashMap inDeg = new HashMap<>(); 7 | HashMap> adjList = new HashMap<>(); 8 | 9 | for(int it=0; it < tasks; it++) { 10 | inDeg.put(it, 0); 11 | adjList.put(it, new ArrayList<>()); 12 | } 13 | 14 | for(int it=0; it < prerequisites.length; it++) { 15 | inDeg.put(prerequisites[it][1], inDeg.get(prerequisites[it][1]) + 1); 16 | ArrayList children = adjList.get(prerequisites[it][0]); 17 | children.add(prerequisites[it][1]); 18 | } 19 | 20 | Queue queue = new LinkedList<>(); 21 | for(int it=0; it topoSort = new ArrayList<>(); 27 | while(!queue.isEmpty()) { 28 | int curr = queue.poll(); 29 | 30 | for(Integer children : adjList.get(curr)) { 31 | int inDegree = inDeg.get(children) - 1; 32 | inDeg.put(children, inDegree); 33 | 34 | if(inDegree == 0) 35 | queue.offer(children); 36 | } 37 | 38 | topoSort.add(curr); 39 | } 40 | 41 | return topoSort.size() == tasks; 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /src/TrappingRainWater.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. 3 | 4 | Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] 5 | Output: 6 6 | Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. 7 | 8 | Input: height = [4,2,0,3,2,5] 9 | Output: 9 10 | 11 | Constraints: 12 | n == height.length 13 | 0 <= n <= 3 * 104 14 | 0 <= height[i] <= 105 15 | */ 16 | 17 | 18 | class Solution { 19 | public int trap(int[] height) { 20 | if(height.length <= 0) return 0; 21 | 22 | int left = 0, right = height.length - 1; 23 | int leftMax = height[left], rightMax = height[right]; 24 | int area = 0; 25 | 26 | while(left <= right) { 27 | if(height[left] <= height[right]) { 28 | //Move left to right 29 | if(height[left] >= leftMax) { 30 | leftMax = height[left]; 31 | } else { 32 | int diff = leftMax - height[left]; 33 | area += diff; 34 | } 35 | left++; 36 | } else { 37 | //Mpve right to left 38 | if(height[right] >= rightMax){ 39 | rightMax = height[right]; 40 | } else { 41 | int diff = rightMax - height[right]; 42 | area += diff; 43 | } 44 | right--; 45 | } 46 | } 47 | 48 | return area; 49 | } 50 | } -------------------------------------------------------------------------------- /src/TreeBalancedCheck.java: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | Given a binary tree, determine if it is height-balanced. 4 | 5 | For this problem, a height-balanced binary tree is defined as: 6 | 7 | a binary tree in which the left and right subtrees of every node differ in height by no more than 1. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | 14 | Input: root = [3,9,20,null,null,15,7] 15 | Output: true 16 | Example 2: 17 | 18 | 19 | Input: root = [1,2,2,3,3,null,null,4,4] 20 | Output: false 21 | Example 3: 22 | 23 | Input: root = [] 24 | Output: true 25 | 26 | * Definition for a binary tree node. 27 | * public class TreeNode { 28 | * int val; 29 | * TreeNode left; 30 | * TreeNode right; 31 | * TreeNode() {} 32 | * TreeNode(int val) { this.val = val; } 33 | * TreeNode(int val, TreeNode left, TreeNode right) { 34 | * this.val = val; 35 | * this.left = left; 36 | * this.right = right; 37 | * } 38 | * } 39 | */ 40 | class Solution { 41 | public boolean isBalanced(TreeNode root) { 42 | return getBalancedHeight(root) != -1; 43 | } 44 | 45 | private int getBalancedHeight(TreeNode node) { 46 | if(node == null) return 0; 47 | 48 | int left = getBalancedHeight(node.left); 49 | int right = getBalancedHeight(node.right); 50 | 51 | if(left == -1 || right == -1 || Math.abs(left - right) > 1) return -1; 52 | 53 | return Math.max(left, right) + 1; 54 | } 55 | } -------------------------------------------------------------------------------- /src/TreePostOrder.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given the root of an n-ary tree, return the postorder traversal of its nodes' values. 3 | 4 | Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) 5 | 6 | 7 | 8 | Example 1: 9 | 10 | 11 | Input: root = [1,null,3,2,4,null,5,6] 12 | Output: [5,6,3,2,4,1] 13 | Example 2: 14 | 15 | 16 | Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] 17 | Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1] 18 | 19 | 20 | Constraints: 21 | 22 | The number of nodes in the tree is in the range [0, 104]. 23 | 0 <= Node.val <= 104 24 | The height of the n-ary tree is less than or equal to 1000. 25 | 26 | 27 | Follow up: Recursive solution is trivial, could you do it iteratively? 28 | 29 | 30 | 31 | // Definition for a Node. 32 | class Node { 33 | public int val; 34 | public List children; 35 | 36 | public Node() {} 37 | 38 | public Node(int _val) { 39 | val = _val; 40 | } 41 | 42 | public Node(int _val, List _children) { 43 | val = _val; 44 | children = _children; 45 | } 46 | }; 47 | */ 48 | 49 | //Recursion 50 | class Solution { 51 | 52 | ArrayList result; 53 | 54 | public List postorder(Node root) { 55 | result = new ArrayList<>(); 56 | dfs(root); 57 | return result; 58 | } 59 | 60 | private void dfs(Node node) { 61 | if(node == null) 62 | return; 63 | 64 | for(Node child : node.children) 65 | dfs(child); 66 | 67 | result.add(node.val); 68 | } 69 | } 70 | 71 | //Iteration 72 | class Solution { 73 | 74 | LinkedList result; 75 | 76 | public List postorder(Node root) { 77 | result = new LinkedList<>(); 78 | if(root == null) return result; 79 | 80 | Stack recur = new Stack<>(); 81 | recur.push(root); 82 | while(!recur.isEmpty()) { 83 | Node curr = recur.pop(); 84 | 85 | result.addFirst(curr.val); 86 | 87 | for(Node child : curr.children) 88 | recur.push(child); 89 | } 90 | 91 | return result; 92 | } 93 | } -------------------------------------------------------------------------------- /src/TreePostOrderDP.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree root, return the number of perfect nodes. A perfect node has two properties: 3 | 4 | Has both children 5 | The sum of one subtree is even and the sum of the other subtree is odd 6 | Constraints 7 | 8 | 0 ≤ n ≤ 100,000 where n is the number of nodes in root 9 | */ 10 | class Solution { 11 | 12 | int count = 0; 13 | 14 | public int solve(Tree root) { 15 | dfs(root); 16 | return count; 17 | } 18 | 19 | private int dfs(Tree node) { 20 | if(node == null) 21 | return 0; 22 | 23 | int leftSum = dfs(node.left); 24 | int rightSum = dfs(node.right); 25 | 26 | if(node.left != null && node.right != null && (leftSum + rightSum)%2 == 1 ) 27 | count++; 28 | return leftSum + rightSum + node.val; 29 | } 30 | } 31 | 32 | /* 33 | Counting Maximal Value Roots in Binary Tree 34 | Easy 35 | 36 | Given a binary tree root, count and return the number of nodes where its value is greater than or equal to the values of all of its descendants. 37 | 38 | Constraints 39 | 40 | n ≤ 100,000 where n is the number of nodes in root 41 | */ 42 | class Solution { 43 | 44 | int count = 0; 45 | public int solve(Tree root) { 46 | dfs(root); 47 | return count; 48 | } 49 | 50 | private int dfs(Tree node) { 51 | if(node == null) 52 | return Integer.MIN_VALUE; 53 | 54 | int leftMax = dfs(node.left); 55 | int rightMax = dfs(node.right); 56 | 57 | if(node.val >= leftMax && node.val >= rightMax) 58 | count++; 59 | 60 | return Math.max(Math.max(leftMax, rightMax), node.val); 61 | } 62 | } -------------------------------------------------------------------------------- /src/TwoSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | 6 | You can return the answer in any order. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [2,7,11,15], target = 9 13 | Output: [0,1] 14 | Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 15 | Example 2: 16 | 17 | Input: nums = [3,2,4], target = 6 18 | Output: [1,2] 19 | Example 3: 20 | 21 | Input: nums = [3,3], target = 6 22 | Output: [0,1] 23 | 24 | 25 | Constraints: 26 | 27 | 2 <= nums.length <= 103 28 | -109 <= nums[i] <= 109 29 | -109 <= target <= 109 30 | Only one valid answer exists. 31 | */ 32 | 33 | class Solution { 34 | public int[] twoSum(int[] nums, int target) { 35 | HashMap complements = new HashMap(); 36 | 37 | for(int it=0; it map = new HashMap<>(); 29 | } 30 | class Solution { 31 | Node root; 32 | 33 | public int countDistinct(String s) { 34 | root = new Node(); 35 | int count = 0; 36 | 37 | for(int it=0; it= word.length()) 42 | return true; 43 | 44 | if (row < 0 || row == board.length || col < 0 || col == board[0].length 45 | || board[row][col] != word.charAt(index)) 46 | return false; 47 | 48 | board[row][col] = '#'; 49 | 50 | int[] rowOffsets = {0, 1, 0, -1}; 51 | int[] colOffsets = {1, 0, -1, 0}; 52 | for (int d = 0; d < 4; ++d) { 53 | if (backtrack(board, row + rowOffsets[d], col + colOffsets[d], word, index + 1)) { 54 | board[row][col] = word.charAt(index); 55 | return true; 56 | } 57 | 58 | } 59 | 60 | board[row][col] = word.charAt(index); 61 | return false; 62 | } 63 | } --------------------------------------------------------------------------------