diff --git a/java/1-Two-Sum.java b/java/1-Two-Sum.java index 1d4425195..f6521aa37 100644 --- a/java/1-Two-Sum.java +++ b/java/1-Two-Sum.java @@ -1,19 +1,19 @@ class Solution { - public int[] twoSum(int[] nums, int target) { - HashMap prevMap = new HashMap<>(); + public int[] twoSum(int[] nums, int target) { + HashMap prevMap = new HashMap<>(); - for (int i = 0; i < nums.length; i++) { - int num = nums[i]; - int diff = target - num; + for (int i = 0; i < nums.length; i++) { + int num = nums[i]; + int diff = target - num; - if (prevMap.containsKey(nums[i])) { - return new int[] { prevMap.get(num), i }; - } + if (prevMap.containsKey(nums[i])) { + return new int[] { prevMap.get(num), i }; + } - prevMap.put(target - num, i); - } + prevMap.put(target - num, i); + } - return new int[] {}; - } + return new int[] {}; + } } diff --git a/java/100-Same-Tree.java b/java/100-Same-Tree.java index 135287910..0c34dc024 100644 --- a/java/100-Same-Tree.java +++ b/java/100-Same-Tree.java @@ -17,24 +17,24 @@ */ class Solution { - public boolean isSameTree(TreeNode p, TreeNode q) { - return dfs(p, q); - } - - private boolean dfs(TreeNode p, TreeNode q) { - if (p == null && q == null) { - return true; + public boolean isSameTree(TreeNode p, TreeNode q) { + return dfs(p, q); } - if (p == null || q == null) { - return false; - } + private boolean dfs(TreeNode p, TreeNode q) { + if (p == null && q == null) { + return true; + } - if (p.val != q.val) return false; + if (p == null || q == null) { + return false; + } - boolean left = dfs(p.left, q.left); - boolean right = dfs(p.right, q.right); + if (p.val != q.val) return false; - return left && right; - } + boolean left = dfs(p.left, q.left); + boolean right = dfs(p.right, q.right); + + return left && right; + } } diff --git a/java/102-Binary-Tree-Level-Order-Traversal.java b/java/102-Binary-Tree-Level-Order-Traversal.java index 0635d3a45..595655701 100644 --- a/java/102-Binary-Tree-Level-Order-Traversal.java +++ b/java/102-Binary-Tree-Level-Order-Traversal.java @@ -15,28 +15,28 @@ */ class Solution { - public List> levelOrder(TreeNode root) { - List> res = new ArrayList<>(); - Queue queue = new LinkedList<>(); + public List> levelOrder(TreeNode root) { + List> res = new ArrayList<>(); + Queue queue = new LinkedList<>(); - if (root == null) return res; + if (root == null) return res; - queue.add(root); - while (!queue.isEmpty()) { - int len = queue.size(); - List level = new ArrayList<>(); - for (int i = 0; i < len; i++) { - TreeNode curr = queue.poll(); - level.add(curr.val); - if (curr.left != null) { - queue.add(curr.left); + queue.add(root); + while (!queue.isEmpty()) { + int len = queue.size(); + List level = new ArrayList<>(); + for (int i = 0; i < len; i++) { + TreeNode curr = queue.poll(); + level.add(curr.val); + if (curr.left != null) { + queue.add(curr.left); + } + if (curr.right != null) { + queue.add(curr.right); + } + } + res.add(level); } - if (curr.right != null) { - queue.add(curr.right); - } - } - res.add(level); + return res; } - return res; - } } diff --git a/java/104-Maximum-Depth-of-Binary-Tree.java b/java/104-Maximum-Depth-of-Binary-Tree.java index 18fbae70f..325b5e298 100644 --- a/java/104-Maximum-Depth-of-Binary-Tree.java +++ b/java/104-Maximum-Depth-of-Binary-Tree.java @@ -1,7 +1,7 @@ class Solution { - public int maxDepth(TreeNode root) { - if (root == null) return 0; - return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); - } + public int maxDepth(TreeNode root) { + if (root == null) return 0; + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); + } } diff --git a/java/1046-Last-Stone-Weight.java b/java/1046-Last-Stone-Weight.java index 101b0ec78..aa14de0f1 100644 --- a/java/1046-Last-Stone-Weight.java +++ b/java/1046-Last-Stone-Weight.java @@ -1,13 +1,13 @@ class Solution { - public int lastStoneWeight(int[] stones) { - PriorityQueue maxHeap = new PriorityQueue(); - for (int stone : stones) maxHeap.add(-stone); - while (maxHeap.size() > 1) { - int stone1 = maxHeap.remove(); - int stone2 = maxHeap.remove(); - if (stone1 != stone2) maxHeap.add(stone1 - stone2); + public int lastStoneWeight(int[] stones) { + PriorityQueue maxHeap = new PriorityQueue(); + for (int stone : stones) maxHeap.add(-stone); + while (maxHeap.size() > 1) { + int stone1 = maxHeap.remove(); + int stone2 = maxHeap.remove(); + if (stone1 != stone2) maxHeap.add(stone1 - stone2); + } + return maxHeap.size() != 0 ? (-maxHeap.remove()) : 0; } - return maxHeap.size() != 0 ? (-maxHeap.remove()) : 0; - } } diff --git a/java/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.java b/java/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.java index de532f9a8..32bcfe8ec 100644 --- a/java/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.java +++ b/java/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.java @@ -15,68 +15,68 @@ */ class Solution { - public TreeNode buildTree(int[] preorder, int[] inorder) { - if (preorder.length == 0 || inorder.length == 0) return null; + public TreeNode buildTree(int[] preorder, int[] inorder) { + if (preorder.length == 0 || inorder.length == 0) return null; - TreeNode root = new TreeNode(preorder[0]); - int mid = 0; - for (int i = 0; i < inorder.length; i++) { - if (preorder[0] == inorder[i]) mid = i; - } + TreeNode root = new TreeNode(preorder[0]); + int mid = 0; + for (int i = 0; i < inorder.length; i++) { + if (preorder[0] == inorder[i]) mid = i; + } - root.left = - buildTree( - Arrays.copyOfRange(preorder, 1, mid + 1), - Arrays.copyOfRange(inorder, 0, mid) - ); - root.right = - buildTree( - Arrays.copyOfRange(preorder, mid + 1, preorder.length), - Arrays.copyOfRange(inorder, mid + 1, inorder.length) - ); + root.left = + buildTree( + Arrays.copyOfRange(preorder, 1, mid + 1), + Arrays.copyOfRange(inorder, 0, mid) + ); + root.right = + buildTree( + Arrays.copyOfRange(preorder, mid + 1, preorder.length), + Arrays.copyOfRange(inorder, mid + 1, inorder.length) + ); - return root; - } + return root; + } } // Solution without using Array copies class Solution { - Map inorderPositions = new HashMap<>(); + Map inorderPositions = new HashMap<>(); - public TreeNode buildTree(int[] preorder, int[] inorder) { - if (preorder.length < 1 || inorder.length < 1) return null; + public TreeNode buildTree(int[] preorder, int[] inorder) { + if (preorder.length < 1 || inorder.length < 1) return null; - for (int i = 0; i < inorder.length; i++) { - inorderPositions.put(inorder[i], i); - } + for (int i = 0; i < inorder.length; i++) { + inorderPositions.put(inorder[i], i); + } - return builder(preorder, 0, 0, inorder.length - 1); - } + return builder(preorder, 0, 0, inorder.length - 1); + } - public TreeNode builder( - int[] preorder, - int preorderIndex, - int inorderLow, - int inorderHigh - ) { - if ( - preorderIndex > preorder.length - 1 || inorderLow > inorderHigh - ) return null; + public TreeNode builder( + int[] preorder, + int preorderIndex, + int inorderLow, + int inorderHigh + ) { + if ( + preorderIndex > preorder.length - 1 || inorderLow > inorderHigh + ) return null; - int currentVal = preorder[preorderIndex]; - TreeNode n = new TreeNode(currentVal); - int mid = inorderPositions.get(currentVal); + int currentVal = preorder[preorderIndex]; + TreeNode n = new TreeNode(currentVal); + int mid = inorderPositions.get(currentVal); - n.left = builder(preorder, preorderIndex + 1, inorderLow, mid - 1); - n.right = - builder( - preorder, - preorderIndex + (mid - inorderLow) + 1, - mid + 1, - inorderHigh - ); + n.left = builder(preorder, preorderIndex + 1, inorderLow, mid - 1); + n.right = + builder( + preorder, + preorderIndex + (mid - inorderLow) + 1, + mid + 1, + inorderHigh + ); - return n; - } + return n; + } } diff --git a/java/106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.java b/java/106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.java index c4f035bbc..e0fee2f2d 100644 --- a/java/106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.java +++ b/java/106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.java @@ -2,57 +2,57 @@ class Solution { - public TreeNode buildTree(int[] inorder, int[] postorder) { - HashMap inMap = new HashMap<>(); - for (int i = 0; i < inorder.length; i++) { - inMap.put(inorder[i], i); + public TreeNode buildTree(int[] inorder, int[] postorder) { + HashMap inMap = new HashMap<>(); + for (int i = 0; i < inorder.length; i++) { + inMap.put(inorder[i], i); + } + return helper( + inorder, + 0, + inorder.length - 1, + postorder, + 0, + postorder.length - 1, + inMap + ); } - return helper( - inorder, - 0, - inorder.length - 1, - postorder, - 0, - postorder.length - 1, - inMap - ); - } - public TreeNode helper( - int[] inorder, - int iStart, - int iEnd, - int[] postorder, - int pStart, - int pEnd, - HashMap inMap - ) { - if (pStart > pEnd || iStart > iEnd) { - return null; + public TreeNode helper( + int[] inorder, + int iStart, + int iEnd, + int[] postorder, + int pStart, + int pEnd, + HashMap inMap + ) { + if (pStart > pEnd || iStart > iEnd) { + return null; + } + TreeNode root = new TreeNode(postorder[pEnd]); + int index = inMap.get(postorder[pEnd]); + int numsLeft = index - iStart; + root.left = + helper( + inorder, + iStart, + index - 1, + postorder, + pStart, + pStart + numsLeft - 1, + inMap + ); + root.right = + helper( + inorder, + index + 1, + iEnd, + postorder, + pStart + numsLeft, + pEnd - 1, + inMap + ); + return root; } - TreeNode root = new TreeNode(postorder[pEnd]); - int index = inMap.get(postorder[pEnd]); - int numsLeft = index - iStart; - root.left = - helper( - inorder, - iStart, - index - 1, - postorder, - pStart, - pStart + numsLeft - 1, - inMap - ); - root.right = - helper( - inorder, - index + 1, - iEnd, - postorder, - pStart + numsLeft, - pEnd - 1, - inMap - ); - return root; - } } diff --git a/java/107-Binary-Tree-Level-Order-Traversal-II.java b/java/107-Binary-Tree-Level-Order-Traversal-II.java index 42d01dd40..aa3e9f850 100644 --- a/java/107-Binary-Tree-Level-Order-Traversal-II.java +++ b/java/107-Binary-Tree-Level-Order-Traversal-II.java @@ -3,25 +3,25 @@ class Solution { - public List> levelOrderBottom(TreeNode root) { - List> ans = new ArrayList<>(); - if (root == null) return ans; - Queue q = new LinkedList<>(); - q.offer(root); - while (!q.isEmpty()) { - List level = new ArrayList<>(); - int size = q.size(); - for (int i = 0; i < size; i++) { - TreeNode cur = q.poll(); - level.add(cur.val); - if (cur.left != null) q.offer(cur.left); - if (cur.right != null) q.offer(cur.right); - } - ans.add(level); + public List> levelOrderBottom(TreeNode root) { + List> ans = new ArrayList<>(); + if (root == null) return ans; + Queue q = new LinkedList<>(); + q.offer(root); + while (!q.isEmpty()) { + List level = new ArrayList<>(); + int size = q.size(); + for (int i = 0; i < size; i++) { + TreeNode cur = q.poll(); + level.add(cur.val); + if (cur.left != null) q.offer(cur.left); + if (cur.right != null) q.offer(cur.right); + } + ans.add(level); + } + int i = 0, j = ans.size() - 1; + //reverse the list + Collections.reverse(ans); + return ans; } - int i = 0, j = ans.size() - 1; - //reverse the list - Collections.reverse(ans); - return ans; - } } diff --git a/java/11-Container-With-Most-Water.java b/java/11-Container-With-Most-Water.java index 53788fdb6..4d3ba5d75 100644 --- a/java/11-Container-With-Most-Water.java +++ b/java/11-Container-With-Most-Water.java @@ -1,19 +1,19 @@ class Solution { - public int maxArea(int[] height) { - int left = 0; - int right = height.length - 1; - int res = 0; - while (left < right) { - int containerLength = right - left; - int area = containerLength * Math.min(height[left], height[right]); - res = Math.max(res, area); - if (height[left] < height[right]) { - left++; - } else { - right--; - } + public int maxArea(int[] height) { + int left = 0; + int right = height.length - 1; + int res = 0; + while (left < right) { + int containerLength = right - left; + int area = containerLength * Math.min(height[left], height[right]); + res = Math.max(res, area); + if (height[left] < height[right]) { + left++; + } else { + right--; + } + } + return res; } - return res; - } } diff --git a/java/110-Balanced-Binary-Tree.java b/java/110-Balanced-Binary-Tree.java index 14d762990..ff6da988e 100644 --- a/java/110-Balanced-Binary-Tree.java +++ b/java/110-Balanced-Binary-Tree.java @@ -2,26 +2,26 @@ class BalancedBinaryTree { - private static Pair dfs(TreeNode root) { - if (root == null) { - return new Pair(true, 0); - } + private static Pair dfs(TreeNode root) { + if (root == null) { + return new Pair(true, 0); + } - var left = dfs(root.left); - var right = dfs(root.right); + var left = dfs(root.left); + var right = dfs(root.right); - var balanced = - left.getKey() && - right.getKey() && - (Math.abs(left.getValue() - right.getValue()) <= 1); + var balanced = + left.getKey() && + right.getKey() && + (Math.abs(left.getValue() - right.getValue()) <= 1); - return new Pair( - balanced, - 1 + Math.max(left.getValue(), right.getValue()) - ); - } + return new Pair( + balanced, + 1 + Math.max(left.getValue(), right.getValue()) + ); + } - public static boolean isBalanced(TreeNode root) { - return dfs(root).getKey(); - } + public static boolean isBalanced(TreeNode root) { + return dfs(root).getKey(); + } } diff --git a/java/1143-Longest-Common-Subsequence.java b/java/1143-Longest-Common-Subsequence.java index da7c73722..2ad6e6fd7 100644 --- a/java/1143-Longest-Common-Subsequence.java +++ b/java/1143-Longest-Common-Subsequence.java @@ -2,19 +2,20 @@ class Solution { - public int longestCommonSubsequence(String text1, String text2) { - int[][] dp = new int[text1.length()][text2.length()]; - return LCS(text1, text2, 0, 0, dp); - } + public int longestCommonSubsequence(String text1, String text2) { + int[][] dp = new int[text1.length()][text2.length()]; + return LCS(text1, text2, 0, 0, dp); + } - public int LCS(String s1, String s2, int i, int j, int[][] dp) { - if (i >= s1.length() || j >= s2.length()) return 0; else if ( - dp[i][j] != 0 - ) return dp[i][j]; else if (s1.charAt(i) == s2.charAt(j)) return ( - 1 + LCS(s1, s2, i + 1, j + 1, dp) - ); else { - dp[i][j] = Math.max(LCS(s1, s2, i + 1, j, dp), LCS(s1, s2, i, j + 1, dp)); - return dp[i][j]; + public int LCS(String s1, String s2, int i, int j, int[][] dp) { + if (i >= s1.length() || j >= s2.length()) return 0; else if ( + dp[i][j] != 0 + ) return dp[i][j]; else if (s1.charAt(i) == s2.charAt(j)) return ( + 1 + LCS(s1, s2, i + 1, j + 1, dp) + ); else { + dp[i][j] = + Math.max(LCS(s1, s2, i + 1, j, dp), LCS(s1, s2, i, j + 1, dp)); + return dp[i][j]; + } } - } } diff --git a/java/1155-Number-of-Dice-Rolls-With-Target-Sum.java b/java/1155-Number-of-Dice-Rolls-With-Target-Sum.java index 42a5be832..e7792ba3b 100644 --- a/java/1155-Number-of-Dice-Rolls-With-Target-Sum.java +++ b/java/1155-Number-of-Dice-Rolls-With-Target-Sum.java @@ -1,22 +1,22 @@ class Solution { - int mod = 1000000007; + int mod = 1000000007; - public int numRollsToTarget(int n, int k, int target) { - if (target > n * k || target < n) return 0; - if (n == 1) return target < n ? 0 : 1; - int[][] dp = new int[n + 1][target + 1]; - return helper(n, k, target, dp); - } + public int numRollsToTarget(int n, int k, int target) { + if (target > n * k || target < n) return 0; + if (n == 1) return target < n ? 0 : 1; + int[][] dp = new int[n + 1][target + 1]; + return helper(n, k, target, dp); + } - public int helper(int n, int k, int target, int[][] dp) { - if (target > n * k || target < n) return 0; - if (target == 0 && n == 0) return 1; - if (dp[n][target] != 0) return dp[n][target]; - int sum = 0; - for (int i = 1; i <= k; i++) { - sum = (sum + helper(n - 1, k, target - i, dp)) % mod; + public int helper(int n, int k, int target, int[][] dp) { + if (target > n * k || target < n) return 0; + if (target == 0 && n == 0) return 1; + if (dp[n][target] != 0) return dp[n][target]; + int sum = 0; + for (int i = 1; i <= k; i++) { + sum = (sum + helper(n - 1, k, target - i, dp)) % mod; + } + return dp[n][target] = sum; } - return dp[n][target] = sum; - } } diff --git a/java/1160-Find-Words-That-Can-Be-Formed-by-Characters.java b/java/1160-Find-Words-That-Can-Be-Formed-by-Characters.java index ef6862eaf..580511cff 100644 --- a/java/1160-Find-Words-That-Can-Be-Formed-by-Characters.java +++ b/java/1160-Find-Words-That-Can-Be-Formed-by-Characters.java @@ -2,23 +2,23 @@ class Solution { - public int countCharacters(String[] words, String chars) { - int[] arrChars = new int[26]; - for (int i = 0; i < chars.length(); i++) { - arrChars[chars.charAt(i) - 'a']++; + public int countCharacters(String[] words, String chars) { + int[] arrChars = new int[26]; + for (int i = 0; i < chars.length(); i++) { + arrChars[chars.charAt(i) - 'a']++; + } + int ans = 0; + for (String s : words) { + boolean flag = true; + int[] arrS = new int[26]; + for (int i = 0; i < s.length(); i++) { + arrS[s.charAt(i) - 'a']++; + } + for (int i = 0; i < 26; i++) { + if (arrS[i] > arrChars[i]) flag = false; + } + if (flag) ans += s.length(); + } + return ans; } - int ans = 0; - for (String s : words) { - boolean flag = true; - int[] arrS = new int[26]; - for (int i = 0; i < s.length(); i++) { - arrS[s.charAt(i) - 'a']++; - } - for (int i = 0; i < 26; i++) { - if (arrS[i] > arrChars[i]) flag = false; - } - if (flag) ans += s.length(); - } - return ans; - } } diff --git a/java/119-Pascal's-Triangle-II.java b/java/119-Pascal's-Triangle-II.java index 1a1ac2767..8e2011931 100644 --- a/java/119-Pascal's-Triangle-II.java +++ b/java/119-Pascal's-Triangle-II.java @@ -2,20 +2,20 @@ class Solution { - public List getRow(int rowIndex) { - List ans = new ArrayList<>(); - int[][] dp = new int[rowIndex + 1][rowIndex + 1]; - for (int i = 0; i <= rowIndex; i++) { - ans.add(value(rowIndex, i, dp)); + public List getRow(int rowIndex) { + List ans = new ArrayList<>(); + int[][] dp = new int[rowIndex + 1][rowIndex + 1]; + for (int i = 0; i <= rowIndex; i++) { + ans.add(value(rowIndex, i, dp)); + } + return ans; } - return ans; - } - public int value(int row, int col, int[][] dp) { - if (row == 0 || col == 0 || col == row) return 1; - if (dp[row][col] != 0) return dp[row][col]; - dp[row][col] = value(row - 1, col - 1, dp) + value(row - 1, col, dp); - return dp[row][col]; - } + public int value(int row, int col, int[][] dp) { + if (row == 0 || col == 0 || col == row) return 1; + if (dp[row][col] != 0) return dp[row][col]; + dp[row][col] = value(row - 1, col - 1, dp) + value(row - 1, col, dp); + return dp[row][col]; + } } //todo: add bottom up approach diff --git a/java/121-Best-Time-to-Buy-and-Sell-Stock.java b/java/121-Best-Time-to-Buy-and-Sell-Stock.java index d367f3d4f..fbef314af 100644 --- a/java/121-Best-Time-to-Buy-and-Sell-Stock.java +++ b/java/121-Best-Time-to-Buy-and-Sell-Stock.java @@ -1,12 +1,12 @@ class Solution { - public int maxProfit(int[] prices) { - int min = Integer.MAX_VALUE; - int ans = Integer.MIN_VALUE; - for (int val : prices) { - min = Math.min(min, val); - ans = Math.max(ans, val - min); + public int maxProfit(int[] prices) { + int min = Integer.MAX_VALUE; + int ans = Integer.MIN_VALUE; + for (int val : prices) { + min = Math.min(min, val); + ans = Math.max(ans, val - min); + } + return ans; } - return ans; - } } diff --git a/java/124-Binary-Tree-Maximum-Path-Sum.java b/java/124-Binary-Tree-Maximum-Path-Sum.java index 2b0a68bac..05afa2e9e 100644 --- a/java/124-Binary-Tree-Maximum-Path-Sum.java +++ b/java/124-Binary-Tree-Maximum-Path-Sum.java @@ -17,26 +17,26 @@ */ class Solution { - int[] res = new int[1]; + int[] res = new int[1]; - public int maxPathSum(TreeNode root) { - res[0] = root.val; - dfs(root); - return res[0]; - } + public int maxPathSum(TreeNode root) { + res[0] = root.val; + dfs(root); + return res[0]; + } - private int dfs(TreeNode node) { - if (node == null) return 0; + private int dfs(TreeNode node) { + if (node == null) return 0; - int leftMax = dfs(node.left); - int rightMax = dfs(node.right); + int leftMax = dfs(node.left); + int rightMax = dfs(node.right); - leftMax = Math.max(leftMax, 0); - rightMax = Math.max(rightMax, 0); + leftMax = Math.max(leftMax, 0); + rightMax = Math.max(rightMax, 0); - int allMax = leftMax + rightMax + node.val; - res[0] = Math.max(res[0], allMax); + int allMax = leftMax + rightMax + node.val; + res[0] = Math.max(res[0], allMax); - return node.val + Math.max(leftMax, rightMax); - } + return node.val + Math.max(leftMax, rightMax); + } } diff --git a/java/1275-Find-Winner-on-a-Tic-Tac-Toe-Game.java b/java/1275-Find-Winner-on-a-Tic-Tac-Toe-Game.java index 17c93eb62..e2d684369 100644 --- a/java/1275-Find-Winner-on-a-Tic-Tac-Toe-Game.java +++ b/java/1275-Find-Winner-on-a-Tic-Tac-Toe-Game.java @@ -1,31 +1,31 @@ class Solution { - public String tictactoe(int[][] moves) { - int[][][] result = new int[2][2][3]; - int[][] diag1 = new int[2][1]; - int[][] diag2 = new int[2][1]; + public String tictactoe(int[][] moves) { + int[][][] result = new int[2][2][3]; + int[][] diag1 = new int[2][1]; + int[][] diag2 = new int[2][1]; - int p = 0; - for (int i = 0; i < moves.length; i++) { - int r = moves[i][0]; - int c = moves[i][1]; + int p = 0; + for (int i = 0; i < moves.length; i++) { + int r = moves[i][0]; + int c = moves[i][1]; - if (++result[p][0][r] == 3) return getWinner(p); - if (++result[p][1][c] == 3) return getWinner(p); + if (++result[p][0][r] == 3) return getWinner(p); + if (++result[p][1][c] == 3) return getWinner(p); - if (r == c) if (++diag1[p][0] == 3) return getWinner(p); + if (r == c) if (++diag1[p][0] == 3) return getWinner(p); - if ((r == 1 && c == 1) || (r == 0 && c == 2) || (r == 2 && c == 0)) if ( - ++diag2[p][0] == 3 - ) return getWinner(p); + if ( + (r == 1 && c == 1) || (r == 0 && c == 2) || (r == 2 && c == 0) + ) if (++diag2[p][0] == 3) return getWinner(p); - if (p == 0) p = 1; else p = 0; - } + if (p == 0) p = 1; else p = 0; + } - return moves.length == 9 ? "Draw" : "Pending"; - } + return moves.length == 9 ? "Draw" : "Pending"; + } - private String getWinner(int p) { - return p == 0 ? "A" : "B"; - } + private String getWinner(int p) { + return p == 0 ? "A" : "B"; + } } diff --git a/java/128-Longest-Consecutive-Sequence.java b/java/128-Longest-Consecutive-Sequence.java index 3b0b6879d..425fc2358 100644 --- a/java/128-Longest-Consecutive-Sequence.java +++ b/java/128-Longest-Consecutive-Sequence.java @@ -1,20 +1,20 @@ class Solution { - public int longestConsecutive(int[] nums) { - if (nums.length == 0) return 0; - HashSet set = new HashSet<>(); - int ans = 1; - for (int num : nums) set.add(num); - for (int num : nums) { - if (!set.contains(num - 1)) { - int count = 1; - while (set.contains(num + 1)) { - num++; - count++; + public int longestConsecutive(int[] nums) { + if (nums.length == 0) return 0; + HashSet set = new HashSet<>(); + int ans = 1; + for (int num : nums) set.add(num); + for (int num : nums) { + if (!set.contains(num - 1)) { + int count = 1; + while (set.contains(num + 1)) { + num++; + count++; + } + ans = Math.max(count, ans); + } } - ans = Math.max(count, ans); - } + return ans; } - return ans; - } } diff --git a/java/128. Longest Consecutive Sequence.java b/java/128. Longest Consecutive Sequence.java index ea10e6155..beedd1310 100644 --- a/java/128. Longest Consecutive Sequence.java +++ b/java/128. Longest Consecutive Sequence.java @@ -1,34 +1,34 @@ class Solution { - public int longestConsecutive(int[] nums) { - Set set = new HashSet<>(); - int max = -1; - int min = 1000000000; + public int longestConsecutive(int[] nums) { + Set set = new HashSet<>(); + int max = -1; + int min = 1000000000; - // Find min and max from array & add each to set - for (int i : nums) { - set.add(i); - max = Math.max(max, i); - min = Math.min(min, i); - } + // Find min and max from array & add each to set + for (int i : nums) { + set.add(i); + max = Math.max(max, i); + min = Math.min(min, i); + } - int c = 0; // count streak - int res = 0; // longest streak - for (int i = min; i <= max; ++i) { - // Check if set contains ith value; increment count & remove from set - if (set.contains(i)) { - c++; - set.remove(i); - } else { - // If not found set count to 0 - c = 0; - } - // Find longest streak at every step in case we break out from loop - res = Math.max(res, c); + int c = 0; // count streak + int res = 0; // longest streak + for (int i = min; i <= max; ++i) { + // Check if set contains ith value; increment count & remove from set + if (set.contains(i)) { + c++; + set.remove(i); + } else { + // If not found set count to 0 + c = 0; + } + // Find longest streak at every step in case we break out from loop + res = Math.max(res, c); - // If set size is less than current longest streak break as we wont get any longer streak - if (set.size() <= res && c == 0) break; + // If set size is less than current longest streak break as we wont get any longer streak + if (set.size() <= res && c == 0) break; + } + return res; } - return res; - } } diff --git a/java/130-Surrounded-Regions.java b/java/130-Surrounded-Regions.java index cd5626aea..aadd2c75c 100644 --- a/java/130-Surrounded-Regions.java +++ b/java/130-Surrounded-Regions.java @@ -1,40 +1,40 @@ class Solution { - public void solve(char[][] board) { - int nRows = board.length; - int nCols = board[0].length; + public void solve(char[][] board) { + int nRows = board.length; + int nCols = board[0].length; - // 1a) Capture unsurrounded regions - top and bottom row (O -> T) - for (int i = 0; i < nCols; i++) { - if (board[0][i] == 'O') dfs(board, 0, i); - if (board[nRows - 1][i] == 'O') dfs(board, nRows - 1, i); - } + // 1a) Capture unsurrounded regions - top and bottom row (O -> T) + for (int i = 0; i < nCols; i++) { + if (board[0][i] == 'O') dfs(board, 0, i); + if (board[nRows - 1][i] == 'O') dfs(board, nRows - 1, i); + } - // 1b) Capture unsurrounded regions - Left and right columns (O -> T) - for (int i = 0; i < nRows; i++) { - if (board[i][0] == 'O') dfs(board, i, 0); - if (board[i][nCols - 1] == 'O') dfs(board, i, nCols - 1); - } + // 1b) Capture unsurrounded regions - Left and right columns (O -> T) + for (int i = 0; i < nRows; i++) { + if (board[i][0] == 'O') dfs(board, i, 0); + if (board[i][nCols - 1] == 'O') dfs(board, i, nCols - 1); + } - for (int r = 0; r < nRows; r++) { - for (int c = 0; c < nCols; c++) { - if (board[r][c] == 'O') board[r][c] = 'X'; // 2) Capture surrounded regions (O -> X) - if (board[r][c] == 'T') board[r][c] = 'O'; // 3) Uncapture unsurrounded regions (T- O) - } + for (int r = 0; r < nRows; r++) { + for (int c = 0; c < nCols; c++) { + if (board[r][c] == 'O') board[r][c] = 'X'; // 2) Capture surrounded regions (O -> X) + if (board[r][c] == 'T') board[r][c] = 'O'; // 3) Uncapture unsurrounded regions (T- O) + } + } } - } - private void dfs(char[][] board, int r, int c) { - int nRows = board.length; - int nCols = board[0].length; - if ( - r < 0 || c < 0 || r >= nRows || c >= nCols || board[r][c] != 'O' - ) return; + private void dfs(char[][] board, int r, int c) { + int nRows = board.length; + int nCols = board[0].length; + if ( + r < 0 || c < 0 || r >= nRows || c >= nCols || board[r][c] != 'O' + ) return; - board[r][c] = 'T'; - dfs(board, r + 1, c); - dfs(board, r - 1, c); - dfs(board, r, c + 1); - dfs(board, r, c - 1); - } + board[r][c] = 'T'; + dfs(board, r + 1, c); + dfs(board, r - 1, c); + dfs(board, r, c + 1); + dfs(board, r, c - 1); + } } diff --git a/java/131-Palindrome-Partitioning.java b/java/131-Palindrome-Partitioning.java index eb108f9cb..e81a155d5 100644 --- a/java/131-Palindrome-Partitioning.java +++ b/java/131-Palindrome-Partitioning.java @@ -1,26 +1,26 @@ public class Solution { - public List> partition(String s) { - List> res = new ArrayList>(); - if (s.equals("")) { - res.add(new ArrayList()); - return res; - } - for (int i = 0; i < s.length(); i++) { - if (isPalindrome(s, i + 1)) { - for (List list : partition(s.substring(i + 1))) { - list.add(0, s.substring(0, i + 1)); - res.add(list); + public List> partition(String s) { + List> res = new ArrayList>(); + if (s.equals("")) { + res.add(new ArrayList()); + return res; + } + for (int i = 0; i < s.length(); i++) { + if (isPalindrome(s, i + 1)) { + for (List list : partition(s.substring(i + 1))) { + list.add(0, s.substring(0, i + 1)); + res.add(list); + } + } } - } + return res; } - return res; - } - public boolean isPalindrome(String s, int n) { - for (int i = 0; i < n / 2; i++) { - if (s.charAt(i) != s.charAt(n - i - 1)) return false; + public boolean isPalindrome(String s, int n) { + for (int i = 0; i < n / 2; i++) { + if (s.charAt(i) != s.charAt(n - i - 1)) return false; + } + return true; } - return true; - } } diff --git a/java/133-Clone-Graph.java b/java/133-Clone-Graph.java index 721f4c483..2329afb1e 100644 --- a/java/133-Clone-Graph.java +++ b/java/133-Clone-Graph.java @@ -1,15 +1,15 @@ class Solution { - public HashMap map = new HashMap<>(); + public HashMap map = new HashMap<>(); - public Node cloneGraph(Node node) { - if (node == null) return null; - if (map.containsKey(node.val)) return map.get(node.val); - Node newNode = new Node(node.val, new ArrayList()); - map.put(node.val, newNode); - for (Node neighbor : node.neighbors) { - newNode.neighbors.add(cloneGraph(neighbor)); + public Node cloneGraph(Node node) { + if (node == null) return null; + if (map.containsKey(node.val)) return map.get(node.val); + Node newNode = new Node(node.val, new ArrayList()); + map.put(node.val, newNode); + for (Node neighbor : node.neighbors) { + newNode.neighbors.add(cloneGraph(neighbor)); + } + return newNode; } - return newNode; - } } diff --git a/java/134-Gas-Station.java b/java/134-Gas-Station.java index 77dfd8bf2..d41e541be 100644 --- a/java/134-Gas-Station.java +++ b/java/134-Gas-Station.java @@ -1,19 +1,19 @@ class Solution { - public int canCompleteCircuit(int[] gas, int[] cost) { - int sGas = 0, sCost = 0, res = 0, total = 0; - for (int i = 0; i < gas.length; i++) { - sGas += gas[i]; - sCost += cost[i]; + public int canCompleteCircuit(int[] gas, int[] cost) { + int sGas = 0, sCost = 0, res = 0, total = 0; + for (int i = 0; i < gas.length; i++) { + sGas += gas[i]; + sCost += cost[i]; + } + if (sGas < sCost) return -1; + for (int i = 0; i < gas.length; i++) { + total += gas[i] - cost[i]; + if (total < 0) { + total = 0; + res = i + 1; + } + } + return res; } - if (sGas < sCost) return -1; - for (int i = 0; i < gas.length; i++) { - total += gas[i] - cost[i]; - if (total < 0) { - total = 0; - res = i + 1; - } - } - return res; - } } diff --git a/java/136-Single-Number.java b/java/136-Single-Number.java index acb4cd48a..0a44ded80 100644 --- a/java/136-Single-Number.java +++ b/java/136-Single-Number.java @@ -1,9 +1,9 @@ //We can use xor operation as it cancel out itself (i.e. only when values are different in binary representation then give output). See how xor operation works if confused. class Solution { - public int singleNumber(int[] nums) { - int ans = nums[0]; - for (int i = 1; i < nums.length; i++) ans ^= nums[i]; - return ans; - } + public int singleNumber(int[] nums) { + int ans = nums[0]; + for (int i = 1; i < nums.length; i++) ans ^= nums[i]; + return ans; + } } diff --git a/java/138-Copy-List-with-Random-Pointer.java b/java/138-Copy-List-with-Random-Pointer.java index 7d83e0855..dd75285d4 100644 --- a/java/138-Copy-List-with-Random-Pointer.java +++ b/java/138-Copy-List-with-Random-Pointer.java @@ -1,18 +1,18 @@ class Solution { - public Node copyRandomList(Node head) { - Node cur = head; - HashMap map = new HashMap<>(); - while (cur != null) { - map.put(cur, new Node(cur.val)); - cur = cur.next; + public Node copyRandomList(Node head) { + Node cur = head; + HashMap map = new HashMap<>(); + while (cur != null) { + map.put(cur, new Node(cur.val)); + cur = cur.next; + } + cur = head; + while (cur != null) { + map.get(cur).next = map.get(cur.next); + map.get(cur).random = map.get(cur.random); + cur = cur.next; + } + return map.get(head); } - cur = head; - while (cur != null) { - map.get(cur).next = map.get(cur.next); - map.get(cur).random = map.get(cur.random); - cur = cur.next; - } - return map.get(head); - } } diff --git a/java/139-Word- Break.java b/java/139-Word- Break.java index 620b30680..5195d04ff 100644 --- a/java/139-Word- Break.java +++ b/java/139-Word- Break.java @@ -1,28 +1,28 @@ class Solution { - public boolean wordBreak(String s, List wordDict) { - boolean[] dp = new boolean[s.length() + 1]; - Set workDictSet = new HashSet<>(wordDict); + public boolean wordBreak(String s, List wordDict) { + boolean[] dp = new boolean[s.length() + 1]; + Set workDictSet = new HashSet<>(wordDict); - for (int i = 0; i < dp.length; i++) { - dp[i] = false; - } + for (int i = 0; i < dp.length; i++) { + dp[i] = false; + } - dp[s.length()] = true; + dp[s.length()] = true; - for (int i = s.length() - 1; i >= 0; i--) { - for (String word : wordDict) { - if ( - ((i + word.length()) <= s.length()) && - (s.substring(i, i + word.length()).startsWith(word)) - ) { - dp[i] = dp[i + word.length()]; - } - if (dp[i]) { - break; + for (int i = s.length() - 1; i >= 0; i--) { + for (String word : wordDict) { + if ( + ((i + word.length()) <= s.length()) && + (s.substring(i, i + word.length()).startsWith(word)) + ) { + dp[i] = dp[i + word.length()]; + } + if (dp[i]) { + break; + } + } } - } + return dp[0]; } - return dp[0]; - } } diff --git a/java/141. Linked List Cycle.java b/java/141. Linked List Cycle.java index 01bcdd925..6388d2dfe 100644 --- a/java/141. Linked List Cycle.java +++ b/java/141. Linked List Cycle.java @@ -2,14 +2,14 @@ public class Solution { - public boolean hasCycle(ListNode head) { - ListNode fast = head; - ListNode slow = head; - while (fast != null && fast.next != null) { - fast = fast.next.next; - slow = slow.next; - if (fast == slow) return true; + public boolean hasCycle(ListNode head) { + ListNode fast = head; + ListNode slow = head; + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + if (fast == slow) return true; + } + return false; } - return false; - } } diff --git a/java/143-Reorder-List.java b/java/143-Reorder-List.java index 26ac6334a..5005abf43 100644 --- a/java/143-Reorder-List.java +++ b/java/143-Reorder-List.java @@ -10,32 +10,32 @@ */ class Solution { - public void reorderList(ListNode head) { - ListNode slow = head; - ListNode fast = head.next; - while (fast != null && fast.next != null) { - slow = slow.next; - fast = fast.next.next; - } + public void reorderList(ListNode head) { + ListNode slow = head; + ListNode fast = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } - ListNode second = slow.next; - ListNode prev = slow.next = null; - while (second != null) { - ListNode tmp = second.next; - second.next = prev; - prev = second; - second = tmp; - } + ListNode second = slow.next; + ListNode prev = slow.next = null; + while (second != null) { + ListNode tmp = second.next; + second.next = prev; + prev = second; + second = tmp; + } - ListNode first = head; - second = prev; - while (second != null) { - ListNode tmp1 = first.next; - ListNode tmp2 = second.next; - first.next = second; - second.next = tmp1; - first = tmp1; - second = tmp2; + ListNode first = head; + second = prev; + while (second != null) { + ListNode tmp1 = first.next; + ListNode tmp2 = second.next; + first.next = second; + second.next = tmp1; + first = tmp1; + second = tmp2; + } } - } } diff --git a/java/1448-Count-Good-Nodes-in-Binary-Tree.java b/java/1448-Count-Good-Nodes-in-Binary-Tree.java index b091d88a0..52644a4ac 100644 --- a/java/1448-Count-Good-Nodes-in-Binary-Tree.java +++ b/java/1448-Count-Good-Nodes-in-Binary-Tree.java @@ -1,17 +1,17 @@ class Solution { - public int goodNodes(TreeNode root) { - return helper(root, -99999); - } + public int goodNodes(TreeNode root) { + return helper(root, -99999); + } - public int helper(TreeNode root, int max) { - if (root == null) return 0; + public int helper(TreeNode root, int max) { + if (root == null) return 0; - int res = root.val >= max ? 1 : 0; + int res = root.val >= max ? 1 : 0; - res += helper(root.left, Math.max(root.val, max)); - res += helper(root.right, Math.max(root.val, max)); + res += helper(root.left, Math.max(root.val, max)); + res += helper(root.right, Math.max(root.val, max)); - return res; - } + return res; + } } diff --git a/java/146-LRU-Cache.java b/java/146-LRU-Cache.java index 21ecff040..376e48aec 100644 --- a/java/146-LRU-Cache.java +++ b/java/146-LRU-Cache.java @@ -1,79 +1,79 @@ class LRUCache { - private Map cache; - private int capacity; - - private Node left; - private Node right; - - public LRUCache(int capacity) { - this.capacity = capacity; - cache = new HashMap<>(); - - //left = LRU , right = most recent - this.left = new Node(0, 0); - this.right = new Node(0, 0); - this.left.next = this.right; - this.right.prev = this.left; - } - - public int get(int key) { - if (cache.containsKey(key)) { - remove(cache.get(key)); - insert(cache.get(key)); - return cache.get(key).val; - } else { - return -1; + private Map cache; + private int capacity; + + private Node left; + private Node right; + + public LRUCache(int capacity) { + this.capacity = capacity; + cache = new HashMap<>(); + + //left = LRU , right = most recent + this.left = new Node(0, 0); + this.right = new Node(0, 0); + this.left.next = this.right; + this.right.prev = this.left; } - } - public void put(int key, int value) { - if (cache.containsKey(key)) { - remove(cache.get(key)); + public int get(int key) { + if (cache.containsKey(key)) { + remove(cache.get(key)); + insert(cache.get(key)); + return cache.get(key).val; + } else { + return -1; + } } - cache.put(key, new Node(key, value)); - insert(cache.get(key)); - - if (cache.size() > capacity) { - // remove from the list and delte the LRU from the hashmap - Node lru = this.left.next; - remove(lru); - cache.remove(lru.key); + + public void put(int key, int value) { + if (cache.containsKey(key)) { + remove(cache.get(key)); + } + cache.put(key, new Node(key, value)); + insert(cache.get(key)); + + if (cache.size() > capacity) { + // remove from the list and delte the LRU from the hashmap + Node lru = this.left.next; + remove(lru); + cache.remove(lru.key); + } } - } - // remove node from list - public void remove(Node node) { - Node prev = node.prev; - Node next = node.next; + // remove node from list + public void remove(Node node) { + Node prev = node.prev; + Node next = node.next; - prev.next = next; - next.prev = prev; - } + prev.next = next; + next.prev = prev; + } - // insert node at right - public void insert(Node node) { - Node prev = this.right.prev; - Node next = this.right; + // insert node at right + public void insert(Node node) { + Node prev = this.right.prev; + Node next = this.right; - prev.next = node; - next.prev = node; + prev.next = node; + next.prev = node; - node.next = next; - node.prev = prev; - } + node.next = next; + node.prev = prev; + } - private class Node { + private class Node { - private int key; - private int val; + private int key; + private int val; - Node next; - Node prev; + Node next; + Node prev; - public Node(int key, int val) { - this.key = key; - this.val = val; + public Node(int key, int val) { + this.key = key; + this.val = val; + } } - } } diff --git a/java/15-3Sum.java b/java/15-3Sum.java index db815c555..6335d9c22 100644 --- a/java/15-3Sum.java +++ b/java/15-3Sum.java @@ -1,40 +1,40 @@ class Solution { - //2 pointers - public List> threeSum(int[] nums) { - Arrays.sort(nums); - LinkedList> sol = new LinkedList>(); + //2 pointers + public List> threeSum(int[] nums) { + Arrays.sort(nums); + LinkedList> sol = new LinkedList>(); - for (int i = 0; i < nums.length - 2; i++) { - if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) { - int target = 0 - nums[i]; - int left = i + 1; - int right = nums.length - 1; + for (int i = 0; i < nums.length - 2; i++) { + if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) { + int target = 0 - nums[i]; + int left = i + 1; + int right = nums.length - 1; - while (left < right) { - if (nums[left] + nums[right] == target) { - ArrayList miniSol = new ArrayList<>(); - miniSol.add(nums[i]); - miniSol.add(nums[left]); - miniSol.add(nums[right]); - sol.add(miniSol); - while (left < right && nums[left] == nums[left + 1]) { - left++; + while (left < right) { + if (nums[left] + nums[right] == target) { + ArrayList miniSol = new ArrayList<>(); + miniSol.add(nums[i]); + miniSol.add(nums[left]); + miniSol.add(nums[right]); + sol.add(miniSol); + while (left < right && nums[left] == nums[left + 1]) { + left++; + } + while (left < right && nums[right] == nums[right - 1]) { + right--; + } + left++; + right--; + } else if (nums[left] + nums[right] > target) { + right--; + } else { + left++; + } + } } - while (left < right && nums[right] == nums[right - 1]) { - right--; - } - left++; - right--; - } else if (nums[left] + nums[right] > target) { - right--; - } else { - left++; - } } - } - } - return sol; - } + return sol; + } } diff --git a/java/150-Evaluate-Reverse-Polish-Notation.java b/java/150-Evaluate-Reverse-Polish-Notation.java index 747a84ddb..67e3ed5bf 100644 --- a/java/150-Evaluate-Reverse-Polish-Notation.java +++ b/java/150-Evaluate-Reverse-Polish-Notation.java @@ -1,24 +1,24 @@ class Solution { - public int evalRPN(String[] tokens) { - Stack stack = new Stack<>(); - for (String token : tokens) { - if (token.equals("+")) { - stack.add(stack.pop() + stack.pop()); - } else if (token.equals("-")) { - int a = stack.pop(); - int b = stack.pop(); - stack.add(b - a); - } else if (token.equals("*")) { - stack.add(stack.pop() * stack.pop()); - } else if (token.equals("/")) { - int a = stack.pop(); - int b = stack.pop(); - stack.add(b / a); - } else { - stack.add(Integer.parseInt(token)); - } + public int evalRPN(String[] tokens) { + Stack stack = new Stack<>(); + for (String token : tokens) { + if (token.equals("+")) { + stack.add(stack.pop() + stack.pop()); + } else if (token.equals("-")) { + int a = stack.pop(); + int b = stack.pop(); + stack.add(b - a); + } else if (token.equals("*")) { + stack.add(stack.pop() * stack.pop()); + } else if (token.equals("/")) { + int a = stack.pop(); + int b = stack.pop(); + stack.add(b / a); + } else { + stack.add(Integer.parseInt(token)); + } + } + return stack.pop(); } - return stack.pop(); - } } diff --git a/java/152-Maximum-Product-Subarray.java b/java/152-Maximum-Product-Subarray.java index ccbd0ee5b..77810d399 100644 --- a/java/152-Maximum-Product-Subarray.java +++ b/java/152-Maximum-Product-Subarray.java @@ -1,18 +1,18 @@ class Solution { - public int maxProduct(int[] nums) { - if (nums.length == 1) return nums[0]; + public int maxProduct(int[] nums) { + if (nums.length == 1) return nums[0]; - int res = nums[0]; - int max = 1; - int min = 1; + int res = nums[0]; + int max = 1; + int min = 1; - for (int n : nums) { - int tmp = max * n; - max = Math.max(n, Math.max(tmp, min * n)); - min = Math.min(n, Math.min(tmp, min * n)); - res = Math.max(res, max); + for (int n : nums) { + int tmp = max * n; + max = Math.max(n, Math.max(tmp, min * n)); + min = Math.min(n, Math.min(tmp, min * n)); + res = Math.max(res, max); + } + return res; } - return res; - } } diff --git a/java/153-Find-Minimum-in-Rotated-Sorted-Array.java b/java/153-Find-Minimum-in-Rotated-Sorted-Array.java index 3d5f18399..e48dde2be 100644 --- a/java/153-Find-Minimum-in-Rotated-Sorted-Array.java +++ b/java/153-Find-Minimum-in-Rotated-Sorted-Array.java @@ -1,21 +1,21 @@ class Solution { - public int findMin(int[] nums) { - int l = 0; - int r = nums.length - 1; + public int findMin(int[] nums) { + int l = 0; + int r = nums.length - 1; - while (l <= r) { - if (nums[l] <= nums[r]) { - return nums[l]; - } + while (l <= r) { + if (nums[l] <= nums[r]) { + return nums[l]; + } - int mid = (l + r) / 2; - if (nums[mid] >= nums[l]) { - l = mid + 1; - } else { - r = mid; - } + int mid = (l + r) / 2; + if (nums[mid] >= nums[l]) { + l = mid + 1; + } else { + r = mid; + } + } + return 0; } - return 0; - } } diff --git a/java/155-Min-Stack.java b/java/155-Min-Stack.java index 817d9de7e..d2d33c71d 100644 --- a/java/155-Min-Stack.java +++ b/java/155-Min-Stack.java @@ -1,33 +1,33 @@ class MinStack { - private Stack stack; - private Stack minStack; + private Stack stack; + private Stack minStack; - public MinStack() { - stack = new Stack<>(); - minStack = new Stack<>(); - } + public MinStack() { + stack = new Stack<>(); + minStack = new Stack<>(); + } - public void push(int val) { - stack.push(val); + public void push(int val) { + stack.push(val); - // The min stack may be empty, so we need to check it - val = Math.min(val, minStack.isEmpty() ? val : minStack.peek()); - minStack.push(val); - } + // The min stack may be empty, so we need to check it + val = Math.min(val, minStack.isEmpty() ? val : minStack.peek()); + minStack.push(val); + } - public void pop() { - stack.pop(); - minStack.pop(); - } + public void pop() { + stack.pop(); + minStack.pop(); + } - public int top() { - return stack.peek(); - } + public int top() { + return stack.peek(); + } - public int getMin() { - return minStack.peek(); - } + public int getMin() { + return minStack.peek(); + } } /** * Your MinStack object will be instantiated and called as such: diff --git a/java/167-Two-Sum-II.java b/java/167-Two-Sum-II.java index dfa76320a..fcdcccc81 100644 --- a/java/167-Two-Sum-II.java +++ b/java/167-Two-Sum-II.java @@ -1,24 +1,24 @@ class Solution { - public int[] twoSum(int[] numbers, int target) { - int a_pointer = 0; - int b_pointer = numbers.length - 1; - int num_a, num_b; + public int[] twoSum(int[] numbers, int target) { + int a_pointer = 0; + int b_pointer = numbers.length - 1; + int num_a, num_b; - while (a_pointer < b_pointer) { - num_a = numbers[a_pointer]; - num_b = numbers[b_pointer]; + while (a_pointer < b_pointer) { + num_a = numbers[a_pointer]; + num_b = numbers[b_pointer]; - if (num_a + num_b == target) break; + if (num_a + num_b == target) break; - if (num_a + num_b < target) { - a_pointer++; - continue; - } + if (num_a + num_b < target) { + a_pointer++; + continue; + } - b_pointer--; - } + b_pointer--; + } - return new int[] { a_pointer + 1, b_pointer + 1 }; - } + return new int[] { a_pointer + 1, b_pointer + 1 }; + } } diff --git a/java/17-Letter-Combinations-of-a-Phone-Number.java b/java/17-Letter-Combinations-of-a-Phone-Number.java index 7d72b1866..07cc797e6 100644 --- a/java/17-Letter-Combinations-of-a-Phone-Number.java +++ b/java/17-Letter-Combinations-of-a-Phone-Number.java @@ -4,52 +4,52 @@ class Solution { - private Map digitToChar = Map.of( - '2', - "abc", - '3', - "def", - '4', - "ghi", - '5', - "jkl", - '6', - "mno", - '7', - "pqrs", - '8', - "tuv", - '9', - "wxyz" - ); + private Map digitToChar = Map.of( + '2', + "abc", + '3', + "def", + '4', + "ghi", + '5', + "jkl", + '6', + "mno", + '7', + "pqrs", + '8', + "tuv", + '9', + "wxyz" + ); - public List letterCombinations(String digits) { - if (digits.length() == 0) { - return new ArrayList(); - } + public List letterCombinations(String digits) { + if (digits.length() == 0) { + return new ArrayList(); + } - List ans = new ArrayList(); - String cur = ""; - backtrack(digits, ans, cur, 0); - return ans; - } + List ans = new ArrayList(); + String cur = ""; + backtrack(digits, ans, cur, 0); + return ans; + } - public void backtrack( - String digits, - List ans, - String cur, - int index - ) { - if (cur.length() == digits.length()) { - ans.add(cur); - return; - } else if (index >= digits.length()) { - return; - } else { - String digit = digitToChar.get(digits.charAt(index)); - for (char c : digit.toCharArray()) { - backtrack(digits, ans, cur + c, index + 1); - } + public void backtrack( + String digits, + List ans, + String cur, + int index + ) { + if (cur.length() == digits.length()) { + ans.add(cur); + return; + } else if (index >= digits.length()) { + return; + } else { + String digit = digitToChar.get(digits.charAt(index)); + for (char c : digit.toCharArray()) { + backtrack(digits, ans, cur + c, index + 1); + } + } } - } } diff --git a/java/187-Repeated-DNA-Sequences.java b/java/187-Repeated-DNA-Sequences.java index 7260d8ca2..594bbbd17 100644 --- a/java/187-Repeated-DNA-Sequences.java +++ b/java/187-Repeated-DNA-Sequences.java @@ -1,17 +1,17 @@ class Solution { - public List findRepeatedDnaSequences(String s) { - HashSet set = new HashSet<>(); - int start = 0; - HashSet ans = new HashSet<>(); - for (int end = 10; end <= s.length(); end++) { - if (set.contains(s.substring(start, end))) ans.add( - s.substring(start, end) - ); - set.add(s.substring(start, end)); - start++; + public List findRepeatedDnaSequences(String s) { + HashSet set = new HashSet<>(); + int start = 0; + HashSet ans = new HashSet<>(); + for (int end = 10; end <= s.length(); end++) { + if (set.contains(s.substring(start, end))) ans.add( + s.substring(start, end) + ); + set.add(s.substring(start, end)); + start++; + } + List list = new ArrayList<>(ans); + return list; } - List list = new ArrayList<>(ans); - return list; - } } diff --git a/java/19-Remove-Nth-Node-From-End-of-List.java b/java/19-Remove-Nth-Node-From-End-of-List.java index fb6562cf7..79ff235d0 100644 --- a/java/19-Remove-Nth-Node-From-End-of-List.java +++ b/java/19-Remove-Nth-Node-From-End-of-List.java @@ -17,24 +17,24 @@ class Solution { - public ListNode removeNthFromEnd(ListNode head, int n) { - if (head == null || head.next == null) return null; + public ListNode removeNthFromEnd(ListNode head, int n) { + if (head == null || head.next == null) return null; - ListNode temp = new ListNode(0); - temp.next = head; - ListNode first = temp, second = temp; + ListNode temp = new ListNode(0); + temp.next = head; + ListNode first = temp, second = temp; - while (n > 0) { - second = second.next; - n--; - } + while (n > 0) { + second = second.next; + n--; + } - while (second.next != null) { - second = second.next; - first = first.next; - } + while (second.next != null) { + second = second.next; + first = first.next; + } - first.next = first.next.next; - return temp.next; - } + first.next = first.next.next; + return temp.next; + } } diff --git a/java/190-Reverse-Bits.java b/java/190-Reverse-Bits.java index 4a7f20471..45884fdd5 100644 --- a/java/190-Reverse-Bits.java +++ b/java/190-Reverse-Bits.java @@ -1,18 +1,18 @@ public class Solution { - // you need treat n as an unsigned value - public int reverseBits(int n) { - int res = 0; - int mask = 1; + // you need treat n as an unsigned value + public int reverseBits(int n) { + int res = 0; + int mask = 1; - for (int i = 0; i < 32; i++) { - int tmp = n & mask; - if (tmp != 0) { - int tmpMask = 1 << (31 - i); - res = res | tmpMask; - } - mask <<= 1; + for (int i = 0; i < 32; i++) { + int tmp = n & mask; + if (tmp != 0) { + int tmpMask = 1 << (31 - i); + res = res | tmpMask; + } + mask <<= 1; + } + return res; } - return res; - } } diff --git a/java/191-Number-of-1-Bits.java b/java/191-Number-of-1-Bits.java index 0d79719e3..55897bf62 100644 --- a/java/191-Number-of-1-Bits.java +++ b/java/191-Number-of-1-Bits.java @@ -1,30 +1,30 @@ //standard way public class Solution { - // you need to treat n as an unsigned value - public int hammingWeight(int n) { - int count = 0; - int mask = 1; - for (int i = 0; i < 32; i++) { - if ((n & mask) != 0) { - count++; - } - n >>= 1; + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + int count = 0; + int mask = 1; + for (int i = 0; i < 32; i++) { + if ((n & mask) != 0) { + count++; + } + n >>= 1; + } + return count; } - return count; - } } //smart way public class Solution { - // you need to treat n as an unsigned value - public int hammingWeight(int n) { - int count = 0; - while (n != 0) { - n = n & (n - 1); - count++; + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + int count = 0; + while (n != 0) { + n = n & (n - 1); + count++; + } + return count; } - return count; - } } diff --git a/java/198-House-Robber.java b/java/198-House-Robber.java index c3e40b3a1..6df76a0dd 100644 --- a/java/198-House-Robber.java +++ b/java/198-House-Robber.java @@ -1,35 +1,35 @@ class Solution { - public int rob(int[] nums) { - if (nums == null || nums.length == 0) return 0; - if (nums.length == 1) return nums[0]; - if (nums.length == 2) return Math.max(nums[0], nums[1]); + public int rob(int[] nums) { + if (nums == null || nums.length == 0) return 0; + if (nums.length == 1) return nums[0]; + if (nums.length == 2) return Math.max(nums[0], nums[1]); - int robWithOutIncludingLastHouse = 0, robWithIncludingLastHouse = 0; + int robWithOutIncludingLastHouse = 0, robWithIncludingLastHouse = 0; - for (int n : nums) { - int temp = Math.max( - robWithOutIncludingLastHouse + n, - robWithIncludingLastHouse - ); - robWithOutIncludingLastHouse = robWithIncludingLastHouse; - robWithIncludingLastHouse = temp; + for (int n : nums) { + int temp = Math.max( + robWithOutIncludingLastHouse + n, + robWithIncludingLastHouse + ); + robWithOutIncludingLastHouse = robWithIncludingLastHouse; + robWithIncludingLastHouse = temp; + } + return robWithIncludingLastHouse; } - return robWithIncludingLastHouse; - } - public int robDP(int[] nums) { - if (nums == null || nums.length == 0) return 0; - if (nums.length == 1) return nums[0]; - if (nums.length == 2) return Math.max(nums[0], nums[1]); + public int robDP(int[] nums) { + if (nums == null || nums.length == 0) return 0; + if (nums.length == 1) return nums[0]; + if (nums.length == 2) return Math.max(nums[0], nums[1]); - int[] dp = new int[nums.length]; - dp[0] = nums[0]; - dp[1] = Math.max(nums[0], nums[1]); + int[] dp = new int[nums.length]; + dp[0] = nums[0]; + dp[1] = Math.max(nums[0], nums[1]); - for (int i = 2; i < nums.length; i++) { - dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); + for (int i = 2; i < nums.length; i++) { + dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); + } + return dp[nums.length - 1]; } - return dp[nums.length - 1]; - } } diff --git a/java/199-Binary-Tree-Right-Side-View.java b/java/199-Binary-Tree-Right-Side-View.java index 9ccb4842d..470c98c9f 100644 --- a/java/199-Binary-Tree-Right-Side-View.java +++ b/java/199-Binary-Tree-Right-Side-View.java @@ -1,23 +1,23 @@ class Solution { - public List rightSideView(TreeNode root) { - List list = new ArrayList(); - if (root == null) return list; - bfs(list, root); - return list; - } + public List rightSideView(TreeNode root) { + List list = new ArrayList(); + if (root == null) return list; + bfs(list, root); + return list; + } - public void bfs(List list, TreeNode root) { - Queue q = new LinkedList<>(); - q.offer(root); - while (!q.isEmpty()) { - int levelSize = q.size(); - for (int i = 0; i < levelSize; i++) { - TreeNode cur = q.poll(); - if (i == 0) list.add(cur.val); - if (cur.right != null) q.offer(cur.right); - if (cur.left != null) q.offer(cur.left); - } + public void bfs(List list, TreeNode root) { + Queue q = new LinkedList<>(); + q.offer(root); + while (!q.isEmpty()) { + int levelSize = q.size(); + for (int i = 0; i < levelSize; i++) { + TreeNode cur = q.poll(); + if (i == 0) list.add(cur.val); + if (cur.right != null) q.offer(cur.right); + if (cur.left != null) q.offer(cur.left); + } + } } - } } diff --git a/java/2-Add-Two-Numbers.java b/java/2-Add-Two-Numbers.java index e3b0db3dc..15bbc5536 100644 --- a/java/2-Add-Two-Numbers.java +++ b/java/2-Add-Two-Numbers.java @@ -8,48 +8,48 @@ class Solution { - public ListNode addTwoNumbers(ListNode first, ListNode second) { - int q = 0; - int r = 0; - int sum = 0; - ListNode head = null; - ListNode temp = null; - while (first != null || second != null) { - sum = - q + - ( - ((first != null) ? first.val : 0) + - ((second != null) ? second.val : 0) - ); - r = sum % 10; - q = sum / 10; - ListNode newNode = new ListNode(r); - if (head == null) { - head = newNode; - } else { - temp = head; - while (temp.next != null) { - temp = temp.next; + public ListNode addTwoNumbers(ListNode first, ListNode second) { + int q = 0; + int r = 0; + int sum = 0; + ListNode head = null; + ListNode temp = null; + while (first != null || second != null) { + sum = + q + + ( + ((first != null) ? first.val : 0) + + ((second != null) ? second.val : 0) + ); + r = sum % 10; + q = sum / 10; + ListNode newNode = new ListNode(r); + if (head == null) { + head = newNode; + } else { + temp = head; + while (temp.next != null) { + temp = temp.next; + } + temp.next = newNode; + newNode.next = null; + } + if (first != null) { + first = first.next; + } + if (second != null) { + second = second.next; + } } - temp.next = newNode; - newNode.next = null; - } - if (first != null) { - first = first.next; - } - if (second != null) { - second = second.next; - } - } - if (q > 0) { - ListNode newNode = new ListNode(q); - temp = head; - while (temp.next != null) { - temp = temp.next; - } - temp.next = newNode; - newNode.next = null; + if (q > 0) { + ListNode newNode = new ListNode(q); + temp = head; + while (temp.next != null) { + temp = temp.next; + } + temp.next = newNode; + newNode.next = null; + } + return head; } - return head; - } } diff --git a/java/20-Valid-Parentheses.java b/java/20-Valid-Parentheses.java index fb1028e29..ff4bd75af 100644 --- a/java/20-Valid-Parentheses.java +++ b/java/20-Valid-Parentheses.java @@ -1,22 +1,24 @@ class Solution { - public boolean isValid(String s) { - if (s.length() % 2 != 0) return false; - Stack stack = new Stack<>(); - for (int i = 0; i < s.length(); i++) { - if ( - stack.isEmpty() && - (s.charAt(i) == ')' || s.charAt(i) == '}' || s.charAt(i) == ']') - ) return false; else { - if (!stack.isEmpty()) { - if (stack.peek() == '(' && s.charAt(i) == ')') stack.pop(); else if ( - stack.peek() == '{' && s.charAt(i) == '}' - ) stack.pop(); else if ( - stack.peek() == '[' && s.charAt(i) == ']' - ) stack.pop(); else stack.add(s.charAt(i)); - } else stack.add(s.charAt(i)); - } + public boolean isValid(String s) { + if (s.length() % 2 != 0) return false; + Stack stack = new Stack<>(); + for (int i = 0; i < s.length(); i++) { + if ( + stack.isEmpty() && + (s.charAt(i) == ')' || s.charAt(i) == '}' || s.charAt(i) == ']') + ) return false; else { + if (!stack.isEmpty()) { + if ( + stack.peek() == '(' && s.charAt(i) == ')' + ) stack.pop(); else if ( + stack.peek() == '{' && s.charAt(i) == '}' + ) stack.pop(); else if ( + stack.peek() == '[' && s.charAt(i) == ']' + ) stack.pop(); else stack.add(s.charAt(i)); + } else stack.add(s.charAt(i)); + } + } + return stack.isEmpty(); } - return stack.isEmpty(); - } } diff --git a/java/200-Number-of-Islands.java b/java/200-Number-of-Islands.java index 72e59c03f..1c48f4e8f 100644 --- a/java/200-Number-of-Islands.java +++ b/java/200-Number-of-Islands.java @@ -1,32 +1,32 @@ class Solution { - public int numIslands(char[][] grid) { - int count = 0; - for (int i = 0; i < grid.length; i++) { - for (int j = 0; j < grid[0].length; j++) { - if (grid[i][j] == '1') { - dfs(grid, i, j); - count++; + public int numIslands(char[][] grid) { + int count = 0; + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (grid[i][j] == '1') { + dfs(grid, i, j); + count++; + } + } } - } + return count; } - return count; - } - public void dfs(char[][] grid, int i, int j) { - if ( - i < 0 || - j < 0 || - i >= grid.length || - j >= grid[0].length || - grid[i][j] == '0' - ) { - return; + public void dfs(char[][] grid, int i, int j) { + if ( + i < 0 || + j < 0 || + i >= grid.length || + j >= grid[0].length || + grid[i][j] == '0' + ) { + return; + } + grid[i][j] = '0'; + dfs(grid, i + 1, j); + dfs(grid, i, j + 1); + dfs(grid, i - 1, j); + dfs(grid, i, j - 1); } - grid[i][j] = '0'; - dfs(grid, i + 1, j); - dfs(grid, i, j + 1); - dfs(grid, i - 1, j); - dfs(grid, i, j - 1); - } } diff --git a/java/202-Happy-Number.java b/java/202-Happy-Number.java index ed3ef318c..8942da63a 100644 --- a/java/202-Happy-Number.java +++ b/java/202-Happy-Number.java @@ -1,34 +1,34 @@ class Solution { - public boolean isHappy(int n) { - if (n == 1 || n == -1) { - return true; - } + public boolean isHappy(int n) { + if (n == 1 || n == -1) { + return true; + } + + Set visit = new HashSet(); - Set visit = new HashSet(); + // compute square until getting duplicate value + while (!visit.contains(n)) { + visit.add(n); + // using helper function to compute the sum of squares + n = sumOfSquare(n); - // compute square until getting duplicate value - while (!visit.contains(n)) { - visit.add(n); - // using helper function to compute the sum of squares - n = sumOfSquare(n); + if (n == 1) return true; + } - if (n == 1) return true; + return false; } - return false; - } + public int sumOfSquare(int n) { + int output = 0; - public int sumOfSquare(int n) { - int output = 0; + while (n != 0) { + int digit = n % 10; + digit = digit * digit; + output += digit; + n = n / 10; + } - while (n != 0) { - int digit = n % 10; - digit = digit * digit; - output += digit; - n = n / 10; + return output; } - - return output; - } } diff --git a/java/206. Reverse Linked List.java b/java/206. Reverse Linked List.java index 3285f7cc9..1a03e7cf5 100644 --- a/java/206. Reverse Linked List.java +++ b/java/206. Reverse Linked List.java @@ -2,31 +2,31 @@ //Iterative version class Solution { - public ListNode reverseList(ListNode head) { - ListNode p = null; - ListNode q = null; - ListNode r = head; - while (r != null) { - p = q; - q = r; - r = r.next; - q.next = p; + public ListNode reverseList(ListNode head) { + ListNode p = null; + ListNode q = null; + ListNode r = head; + while (r != null) { + p = q; + q = r; + r = r.next; + q.next = p; + } + return q; } - return q; - } } //Recursive version class Solution { - public ListNode reverseList(ListNode head) { - return rev(head, null); - } + public ListNode reverseList(ListNode head) { + return rev(head, null); + } - public ListNode rev(ListNode node, ListNode pre) { - if (node == null) return pre; - ListNode temp = node.next; - node.next = pre; - return rev(temp, node); - } + public ListNode rev(ListNode node, ListNode pre) { + if (node == null) return pre; + ListNode temp = node.next; + node.next = pre; + return rev(temp, node); + } } diff --git a/java/207-Course-Schedule.java b/java/207-Course-Schedule.java index b127d72fc..e993e5a39 100644 --- a/java/207-Course-Schedule.java +++ b/java/207-Course-Schedule.java @@ -1,40 +1,40 @@ class Solution { - public boolean canFinish(int numCourses, int[][] prerequisites) { - List> adj = new ArrayList<>(); - for (int i = 0; i < numCourses; i++) { - adj.add(new ArrayList<>()); - } + public boolean canFinish(int numCourses, int[][] prerequisites) { + List> adj = new ArrayList<>(); + for (int i = 0; i < numCourses; i++) { + adj.add(new ArrayList<>()); + } - for (int i = 0; i < prerequisites.length; i++) { - adj.get(prerequisites[i][0]).add(prerequisites[i][1]); - } + for (int i = 0; i < prerequisites.length; i++) { + adj.get(prerequisites[i][0]).add(prerequisites[i][1]); + } - int[] visited = new int[numCourses]; - for (int i = 0; i < numCourses; i++) { - if (visited[i] == 0) { - if (isCyclic(adj, visited, i)) { - return false; + int[] visited = new int[numCourses]; + for (int i = 0; i < numCourses; i++) { + if (visited[i] == 0) { + if (isCyclic(adj, visited, i)) { + return false; + } + } } - } + return true; } - return true; - } - private boolean isCyclic(List> adj, int[] visited, int curr) { - if (visited[curr] == 2) { - return true; - } + private boolean isCyclic(List> adj, int[] visited, int curr) { + if (visited[curr] == 2) { + return true; + } - visited[curr] = 2; - for (int i = 0; i < adj.get(curr).size(); i++) { - if (visited[adj.get(curr).get(i)] != 1) { - if (isCyclic(adj, visited, adj.get(curr).get(i))) { - return true; + visited[curr] = 2; + for (int i = 0; i < adj.get(curr).size(); i++) { + if (visited[adj.get(curr).get(i)] != 1) { + if (isCyclic(adj, visited, adj.get(curr).get(i))) { + return true; + } + } } - } + visited[curr] = 1; + return false; } - visited[curr] = 1; - return false; - } } diff --git a/java/208-Implement-Trie-Prefix-Tree.java b/java/208-Implement-Trie-Prefix-Tree.java index 85c1f41c1..7114aeeaa 100644 --- a/java/208-Implement-Trie-Prefix-Tree.java +++ b/java/208-Implement-Trie-Prefix-Tree.java @@ -1,56 +1,56 @@ class Trie { - Node root; - - public Trie() { - root = new Node('\0'); //dummy node - } - - public void insert(String word) { - Node curr = root; - for (char x : word.toCharArray()) { - if (curr.children[x - 'a'] == null) { - curr.children[x - 'a'] = new Node(x); - } - curr = curr.children[x - 'a']; + Node root; + + public Trie() { + root = new Node('\0'); //dummy node + } + + public void insert(String word) { + Node curr = root; + for (char x : word.toCharArray()) { + if (curr.children[x - 'a'] == null) { + curr.children[x - 'a'] = new Node(x); + } + curr = curr.children[x - 'a']; + } + curr.isWord = true; } - curr.isWord = true; - } - - public boolean search(String word) { - Node res = getLast(word); - return (res != null && res.isWord); - } - - //helper method - public Node getLast(String word) { - Node curr = root; - for (char x : word.toCharArray()) { - if (curr.children[x - 'a'] == null) { - return null; - } - - curr = curr.children[x - 'a']; + + public boolean search(String word) { + Node res = getLast(word); + return (res != null && res.isWord); } - return curr; - } - public boolean startsWith(String prefix) { - Node res = getLast(prefix); - if (res == null) return false; - return true; - } + //helper method + public Node getLast(String word) { + Node curr = root; + for (char x : word.toCharArray()) { + if (curr.children[x - 'a'] == null) { + return null; + } + + curr = curr.children[x - 'a']; + } + return curr; + } + + public boolean startsWith(String prefix) { + Node res = getLast(prefix); + if (res == null) return false; + return true; + } - class Node { + class Node { - private char value; - private boolean isWord; - private Node[] children; + private char value; + private boolean isWord; + private Node[] children; - public Node(char val) { - this.value = val; - this.isWord = false; - this.children = new Node[26]; + public Node(char val) { + this.value = val; + this.isWord = false; + this.children = new Node[26]; + } } - } } diff --git a/java/21-Merge-Two-Sorted-Lists.java b/java/21-Merge-Two-Sorted-Lists.java index 2c3554d3b..d33b2800b 100644 --- a/java/21-Merge-Two-Sorted-Lists.java +++ b/java/21-Merge-Two-Sorted-Lists.java @@ -12,22 +12,22 @@ */ class Solution { - public ListNode mergeTwoLists(ListNode list1, ListNode list2) { - final ListNode root = new ListNode(); - ListNode prev = root; - while (list1 != null && list2 != null) { - if (list1.val < list2.val) { - prev.next = list1; - list1 = list1.next; - } else { - prev.next = list2; - list2 = list2.next; - } - prev = prev.next; + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { + final ListNode root = new ListNode(); + ListNode prev = root; + while (list1 != null && list2 != null) { + if (list1.val < list2.val) { + prev.next = list1; + list1 = list1.next; + } else { + prev.next = list2; + list2 = list2.next; + } + prev = prev.next; + } + prev.next = list1 != null ? list1 : list2; + return root.next; } - prev.next = list1 != null ? list1 : list2; - return root.next; - } } // Solution using Recursion @@ -43,21 +43,21 @@ public ListNode mergeTwoLists(ListNode list1, ListNode list2) { */ class Solution { - public ListNode mergeTwoLists(ListNode list1, ListNode list2) { - ListNode head = new ListNode(0); + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { + ListNode head = new ListNode(0); - if (list1 == null && list2 == null) return null; - if (list1 == null) return list2; - if (list2 == null) return list1; + if (list1 == null && list2 == null) return null; + if (list1 == null) return list2; + if (list2 == null) return list1; - if (list1.val > list2.val) { - head = list2; - list2 = list2.next; - } else { - head = list1; - list1 = list1.next; + if (list1.val > list2.val) { + head = list2; + list2 = list2.next; + } else { + head = list1; + list1 = list1.next; + } + head.next = mergeTwoLists(list1, list2); + return head; } - head.next = mergeTwoLists(list1, list2); - return head; - } } diff --git a/java/210-Course-Schedule-II.java b/java/210-Course-Schedule-II.java index a7aa54a2c..775a14e8d 100644 --- a/java/210-Course-Schedule-II.java +++ b/java/210-Course-Schedule-II.java @@ -1,48 +1,51 @@ class Solution { - public int[] findOrder(int numCourses, int[][] prerequisites) { - Map> adjList = new HashMap>(); - int[] indegree = new int[numCourses]; - int[] topologicalOrder = new int[numCourses]; - - //creating the adjlist - for (int i = 0; i < prerequisites.length; i++) { - int post = prerequisites[i][0]; - int pre = prerequisites[i][1]; - List lst = adjList.getOrDefault(pre, new ArrayList()); - lst.add(post); - adjList.put(pre, lst); - - indegree[post] += 1; - } + public int[] findOrder(int numCourses, int[][] prerequisites) { + Map> adjList = new HashMap>(); + int[] indegree = new int[numCourses]; + int[] topologicalOrder = new int[numCourses]; + + //creating the adjlist + for (int i = 0; i < prerequisites.length; i++) { + int post = prerequisites[i][0]; + int pre = prerequisites[i][1]; + List lst = adjList.getOrDefault( + pre, + new ArrayList() + ); + lst.add(post); + adjList.put(pre, lst); + + indegree[post] += 1; + } - Queue q = new LinkedList(); - for (int i = 0; i < numCourses; i++) { - if (indegree[i] == 0) { - q.add(i); - } - } + Queue q = new LinkedList(); + for (int i = 0; i < numCourses; i++) { + if (indegree[i] == 0) { + q.add(i); + } + } - int i = 0; - while (!q.isEmpty()) { - int node = q.remove(); - topologicalOrder[i++] = node; + int i = 0; + while (!q.isEmpty()) { + int node = q.remove(); + topologicalOrder[i++] = node; - if (adjList.containsKey(node)) { - for (Integer neighbor : adjList.get(node)) { - indegree[neighbor]--; + if (adjList.containsKey(node)) { + for (Integer neighbor : adjList.get(node)) { + indegree[neighbor]--; - if (indegree[neighbor] == 0) { - q.add(neighbor); - } + if (indegree[neighbor] == 0) { + q.add(neighbor); + } + } + } } - } - } - if (i == numCourses) { - return topologicalOrder; - } + if (i == numCourses) { + return topologicalOrder; + } - return new int[0]; - } + return new int[0]; + } } diff --git a/java/213-House-RobberII.java b/java/213-House-RobberII.java index 9f151f32d..cfcb6b42d 100644 --- a/java/213-House-RobberII.java +++ b/java/213-House-RobberII.java @@ -1,23 +1,23 @@ class Solution { - public int rob(int[] nums) { - if (nums.length == 0) return 0; - if (nums.length == 1) return nums[0]; + public int rob(int[] nums) { + if (nums.length == 0) return 0; + if (nums.length == 1) return nums[0]; - return Math.max( - robHelper(nums, 0, nums.length - 2), - robHelper(nums, 1, nums.length - 1) - ); - } + return Math.max( + robHelper(nums, 0, nums.length - 2), + robHelper(nums, 1, nums.length - 1) + ); + } - public int robHelper(int[] nums, int start, int end) { - int rob1 = 0; - int rob2 = 0; - for (int i = start; i <= end; i++) { - int temp = Math.max(rob1 + nums[i], rob2); - rob1 = rob2; - rob2 = temp; + public int robHelper(int[] nums, int start, int end) { + int rob1 = 0; + int rob2 = 0; + for (int i = start; i <= end; i++) { + int temp = Math.max(rob1 + nums[i], rob2); + rob1 = rob2; + rob2 = temp; + } + return rob2; } - return rob2; - } } diff --git a/java/215-Kth-Largest-Element-in-an-Array.java b/java/215-Kth-Largest-Element-in-an-Array.java index a31ee5a3e..474db2879 100644 --- a/java/215-Kth-Largest-Element-in-an-Array.java +++ b/java/215-Kth-Largest-Element-in-an-Array.java @@ -1,20 +1,20 @@ class Solution { - public int findKthLargest(int[] nums, int k) { - //create a min heap - PriorityQueue heap = new PriorityQueue(); + public int findKthLargest(int[] nums, int k) { + //create a min heap + PriorityQueue heap = new PriorityQueue(); - //iterate over the array - for (int n : nums) { - //first add the integer to heap - heap.add(n); - //if size of the heap is greater than k - if (heap.size() > k) { - //remove the root element (lowest of all) - heap.poll(); - } + //iterate over the array + for (int n : nums) { + //first add the integer to heap + heap.add(n); + //if size of the heap is greater than k + if (heap.size() > k) { + //remove the root element (lowest of all) + heap.poll(); + } + } + //finally heap has k largest elements left with root as the kth largest element + return heap.peek(); } - //finally heap has k largest elements left with root as the kth largest element - return heap.peek(); - } } diff --git a/java/217-Contains-Duplicate.java b/java/217-Contains-Duplicate.java index c42099416..6ad8b8bcb 100644 --- a/java/217-Contains-Duplicate.java +++ b/java/217-Contains-Duplicate.java @@ -1,13 +1,13 @@ class Solution { - public boolean containsDuplicate(int[] nums) { - Set uniques = new HashSet<>(); - for (int i = 0; i < nums.length; i++) { - if (uniques.contains(nums[i])) { - return true; - } - uniques.add(nums[i]); + public boolean containsDuplicate(int[] nums) { + Set uniques = new HashSet<>(); + for (int i = 0; i < nums.length; i++) { + if (uniques.contains(nums[i])) { + return true; + } + uniques.add(nums[i]); + } + return false; } - return false; - } } diff --git a/java/22-Generate-Parentheses.java b/java/22-Generate-Parentheses.java index 7793dc831..c9d5f3a49 100644 --- a/java/22-Generate-Parentheses.java +++ b/java/22-Generate-Parentheses.java @@ -7,37 +7,37 @@ public class Solution { - public static void main(String[] args) { - Solution sol = new Solution(); - sol.generateParenthesis(3); - } - - Stack stack = new Stack<>(); - List res = new ArrayList<>(); + public static void main(String[] args) { + Solution sol = new Solution(); + sol.generateParenthesis(3); + } - public List generateParenthesis(int n) { - backtrack(0, 0, n); - return res; - } + Stack stack = new Stack<>(); + List res = new ArrayList<>(); - private void backtrack(int openN, int closedN, int n) { - if (openN == closedN && closedN == n) { - Iterator vale = stack.iterator(); - String temp = ""; - while (vale.hasNext()) { - temp = temp + vale.next(); - } - res.add(temp); + public List generateParenthesis(int n) { + backtrack(0, 0, n); + return res; } - if (openN < n) { - stack.push('('); - backtrack(openN + 1, closedN, n); - stack.pop(); - } - if (closedN < openN) { - stack.push(')'); - backtrack(openN, closedN + 1, n); - stack.pop(); + + private void backtrack(int openN, int closedN, int n) { + if (openN == closedN && closedN == n) { + Iterator vale = stack.iterator(); + String temp = ""; + while (vale.hasNext()) { + temp = temp + vale.next(); + } + res.add(temp); + } + if (openN < n) { + stack.push('('); + backtrack(openN + 1, closedN, n); + stack.pop(); + } + if (closedN < openN) { + stack.push(')'); + backtrack(openN, closedN + 1, n); + stack.pop(); + } } - } } diff --git a/java/226-Invert-Binary-Tree.java b/java/226-Invert-Binary-Tree.java index 8c58dcf8b..b19c9bc6a 100644 --- a/java/226-Invert-Binary-Tree.java +++ b/java/226-Invert-Binary-Tree.java @@ -1,11 +1,11 @@ class Solution { - public TreeNode invertTree(TreeNode root) { - if (root == null) return null; - TreeNode node = new TreeNode(root.val); - node.right = invertTree(root.left); - node.val = root.val; - node.left = invertTree(root.right); - return node; - } + public TreeNode invertTree(TreeNode root) { + if (root == null) return null; + TreeNode node = new TreeNode(root.val); + node.right = invertTree(root.left); + node.val = root.val; + node.left = invertTree(root.right); + return node; + } } diff --git a/java/23-Merge-k-Sorted-Lists.java b/java/23-Merge-k-Sorted-Lists.java index f97fc4ac1..aac816fd0 100644 --- a/java/23-Merge-k-Sorted-Lists.java +++ b/java/23-Merge-k-Sorted-Lists.java @@ -1,24 +1,24 @@ class Solution { - public ListNode mergeKLists(ListNode[] lists) { - Queue minHeap = new PriorityQueue<>(); + public ListNode mergeKLists(ListNode[] lists) { + Queue minHeap = new PriorityQueue<>(); - for (ListNode nodes : lists) { - ListNode current = nodes; - while (current != null) { - minHeap.add(current.val); - current = current.next; - } - } + for (ListNode nodes : lists) { + ListNode current = nodes; + while (current != null) { + minHeap.add(current.val); + current = current.next; + } + } - ListNode dummy = new ListNode(0); - ListNode current = dummy; + ListNode dummy = new ListNode(0); + ListNode current = dummy; - while (!minHeap.isEmpty()) { - current.next = new ListNode(minHeap.poll()); - current = current.next; - } + while (!minHeap.isEmpty()) { + current.next = new ListNode(minHeap.poll()); + current = current.next; + } - return dummy.next; - } + return dummy.next; + } } diff --git a/java/230-Kth-Smallest-Element-in-a-BST.java b/java/230-Kth-Smallest-Element-in-a-BST.java index 4f75e787c..bcb845313 100644 --- a/java/230-Kth-Smallest-Element-in-a-BST.java +++ b/java/230-Kth-Smallest-Element-in-a-BST.java @@ -15,17 +15,17 @@ */ class Solution { - public int kthSmallest(TreeNode root, int k) { - List list = new ArrayList<>(); - inorder(root, list); - return list.get(k - 1); - } + public int kthSmallest(TreeNode root, int k) { + List list = new ArrayList<>(); + inorder(root, list); + return list.get(k - 1); + } - private void inorder(TreeNode root, List list) { - if (root == null) return; + private void inorder(TreeNode root, List list) { + if (root == null) return; - inorder(root.left, list); - list.add(root.val); - inorder(root.right, list); - } + inorder(root.left, list); + list.add(root.val); + inorder(root.right, list); + } } diff --git a/java/2309.-Greatest-English-Letter-in-Upper-and-Lower-Case.java b/java/2309.-Greatest-English-Letter-in-Upper-and-Lower-Case.java index 3ecdb6f5c..1a51362e0 100644 --- a/java/2309.-Greatest-English-Letter-in-Upper-and-Lower-Case.java +++ b/java/2309.-Greatest-English-Letter-in-Upper-and-Lower-Case.java @@ -1,15 +1,16 @@ //Contest 298 brute-force feel free to share any improvements class Solution { - public String greatestLetter(String s) { - HashSet set = new HashSet<>(); - int ans = -1; - for (int i = 0; i < s.length(); i++) { - if ( - set.contains((s.charAt(i) - 32)) || set.contains((s.charAt(i) + 32)) - ) ans = Math.max(ans, (int) Character.toUpperCase(s.charAt(i))); - set.add(0 + s.charAt(i)); + public String greatestLetter(String s) { + HashSet set = new HashSet<>(); + int ans = -1; + for (int i = 0; i < s.length(); i++) { + if ( + set.contains((s.charAt(i) - 32)) || + set.contains((s.charAt(i) + 32)) + ) ans = Math.max(ans, (int) Character.toUpperCase(s.charAt(i))); + set.add(0 + s.charAt(i)); + } + return ans == -1 ? "" : (char) ans + ""; } - return ans == -1 ? "" : (char) ans + ""; - } } diff --git a/java/2310-Sum-of-Numbers-With-Units-Digit-K.java b/java/2310-Sum-of-Numbers-With-Units-Digit-K.java index 62dc66f4e..80400f80e 100644 --- a/java/2310-Sum-of-Numbers-With-Units-Digit-K.java +++ b/java/2310-Sum-of-Numbers-With-Units-Digit-K.java @@ -1,20 +1,20 @@ //Contest 298 problem brute-force. Feel free to update this. class Solution { - public int minimumNumbers(int num, int k) { - if (num == 0) return 0; - if (num % 10 == k) return 1; - if (k == 0 && num % 10 == 0) return 1; else if ( - k == 0 && num % 10 != 0 - ) return -1; - int temp = num; - num -= k; - int len = 1; - while (num > 0) { - len++; - if (num % 10 == k) return len; - num -= k; + public int minimumNumbers(int num, int k) { + if (num == 0) return 0; + if (num % 10 == k) return 1; + if (k == 0 && num % 10 == 0) return 1; else if ( + k == 0 && num % 10 != 0 + ) return -1; + int temp = num; + num -= k; + int len = 1; + while (num > 0) { + len++; + if (num % 10 == k) return len; + num -= k; + } + return num < 0 ? -1 : len; } - return num < 0 ? -1 : len; - } } diff --git a/java/2328-Number-of-Increasing-Paths-in-a-Grid.java b/java/2328-Number-of-Increasing-Paths-in-a-Grid.java index 03a06ceec..0ab6219a7 100644 --- a/java/2328-Number-of-Increasing-Paths-in-a-Grid.java +++ b/java/2328-Number-of-Increasing-Paths-in-a-Grid.java @@ -2,44 +2,46 @@ class Solution { - long mod = (long) Math.pow(10, 9) + 7; + long mod = (long) Math.pow(10, 9) + 7; - public int countPaths(int[][] grid) { - int m = grid.length, n = grid[0].length; - long[][] dp = new long[m][n]; - for (int i = 0; i < grid.length; i++) { - for (int j = 0; j < grid[0].length; j++) { - if (dp[i][j] == 0) { - dfs(grid, dp, i, j, m, n, -1); + public int countPaths(int[][] grid) { + int m = grid.length, n = grid[0].length; + long[][] dp = new long[m][n]; + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (dp[i][j] == 0) { + dfs(grid, dp, i, j, m, n, -1); + } + } } - } - } - long sum = 0; - for (long[] d : dp) { - for (long i : d) { - sum = (sum + i) % mod; - } + long sum = 0; + for (long[] d : dp) { + for (long i : d) { + sum = (sum + i) % mod; + } + } + return (int) sum; } - return (int) sum; - } - public long dfs( - int[][] grid, - long[][] dp, - int i, - int j, - int m, - int n, - int prevValue - ) { - if (i < 0 || j < 0 || i >= m || j >= n || prevValue >= grid[i][j]) return 0; - if (dp[i][j] != 0) return dp[i][j]; - prevValue = grid[i][j]; - long left = dfs(grid, dp, i, j - 1, m, n, prevValue) % mod; - long bottom = dfs(grid, dp, i + 1, j, m, n, prevValue) % mod; - long right = dfs(grid, dp, i, j + 1, m, n, prevValue) % mod; - long top = dfs(grid, dp, i - 1, j, m, n, prevValue) % mod; - dp[i][j] = (1 + left + top + bottom + right) % mod; - return dp[i][j]; - } + public long dfs( + int[][] grid, + long[][] dp, + int i, + int j, + int m, + int n, + int prevValue + ) { + if ( + i < 0 || j < 0 || i >= m || j >= n || prevValue >= grid[i][j] + ) return 0; + if (dp[i][j] != 0) return dp[i][j]; + prevValue = grid[i][j]; + long left = dfs(grid, dp, i, j - 1, m, n, prevValue) % mod; + long bottom = dfs(grid, dp, i + 1, j, m, n, prevValue) % mod; + long right = dfs(grid, dp, i, j + 1, m, n, prevValue) % mod; + long top = dfs(grid, dp, i - 1, j, m, n, prevValue) % mod; + dp[i][j] = (1 + left + top + bottom + right) % mod; + return dp[i][j]; + } } diff --git a/java/234. Palindrome Linked List.java b/java/234. Palindrome Linked List.java index 9fd2dc292..6bddfe778 100644 --- a/java/234. Palindrome Linked List.java +++ b/java/234. Palindrome Linked List.java @@ -4,32 +4,32 @@ class Solution { - public boolean isPalindrome(ListNode head) { - ListNode fast = head; - ListNode slow = head; - while (fast != null && fast.next != null) { - fast = fast.next.next; - slow = slow.next; + public boolean isPalindrome(ListNode head) { + ListNode fast = head; + ListNode slow = head; + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + } + ListNode temp = reverse(slow); + while (temp != null && head != null) { + if (temp.val != head.val) return false; + temp = temp.next; + head = head.next; + } + return true; } - ListNode temp = reverse(slow); - while (temp != null && head != null) { - if (temp.val != head.val) return false; - temp = temp.next; - head = head.next; - } - return true; - } - public ListNode reverse(ListNode head) { - ListNode p = null; - ListNode q = null; - ListNode r = head; - while (r != null) { - p = q; - q = r; - r = r.next; - q.next = p; + public ListNode reverse(ListNode head) { + ListNode p = null; + ListNode q = null; + ListNode r = head; + while (r != null) { + p = q; + q = r; + r = r.next; + q.next = p; + } + return q; } - return q; - } } diff --git a/java/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.java b/java/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.java index 2e6e7d7d6..da7fe525b 100644 --- a/java/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.java +++ b/java/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.java @@ -10,17 +10,21 @@ class Solution { - public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { - if (p.val > root.val && q.val > root.val) return lowestCommonAncestor( - root.right, - p, - q - ); - if (p.val < root.val && q.val < root.val) return lowestCommonAncestor( - root.left, - p, - q - ); - return root; - } + public TreeNode lowestCommonAncestor( + TreeNode root, + TreeNode p, + TreeNode q + ) { + if (p.val > root.val && q.val > root.val) return lowestCommonAncestor( + root.right, + p, + q + ); + if (p.val < root.val && q.val < root.val) return lowestCommonAncestor( + root.left, + p, + q + ); + return root; + } } diff --git a/java/236-Lowest-Common-Ancestor-of-a-Binary-Tree.java b/java/236-Lowest-Common-Ancestor-of-a-Binary-Tree.java index 242714699..57abd0fd1 100644 --- a/java/236-Lowest-Common-Ancestor-of-a-Binary-Tree.java +++ b/java/236-Lowest-Common-Ancestor-of-a-Binary-Tree.java @@ -1,13 +1,17 @@ class Solution { - public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { - if (root == null) return null; - if ((root.val == p.val || root.val == q.val)) return root; - TreeNode left = lowestCommonAncestor(root.left, p, q); - TreeNode right = lowestCommonAncestor(root.right, p, q); + public TreeNode lowestCommonAncestor( + TreeNode root, + TreeNode p, + TreeNode q + ) { + if (root == null) return null; + if ((root.val == p.val || root.val == q.val)) return root; + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p, q); - if (left != null && right != null) { - return root; - } else if (left != null) return left; else return right; - } + if (left != null && right != null) { + return root; + } else if (left != null) return left; else return right; + } } diff --git a/java/238-Product-of-Array-Except-Self.java b/java/238-Product-of-Array-Except-Self.java index 51113d3d2..53d689517 100644 --- a/java/238-Product-of-Array-Except-Self.java +++ b/java/238-Product-of-Array-Except-Self.java @@ -3,22 +3,22 @@ class Solution { - public int[] productExceptSelf(int[] nums) { - int[] arr = new int[nums.length]; - arr[0] = 1; - for (int i = 1; i < nums.length; i++) { - arr[i] = arr[i - 1] * nums[i - 1]; + public int[] productExceptSelf(int[] nums) { + int[] arr = new int[nums.length]; + arr[0] = 1; + for (int i = 1; i < nums.length; i++) { + arr[i] = arr[i - 1] * nums[i - 1]; + } + int prod = nums[nums.length - 1]; + nums[nums.length - 1] = 1; + for (int i = nums.length - 2; i >= 0; i--) { + int store = nums[i]; + nums[i] = nums[i + 1] * prod; + prod = store; + } + for (int i = 0; i < nums.length; i++) { + arr[i] = arr[i] * nums[i]; + } + return arr; } - int prod = nums[nums.length - 1]; - nums[nums.length - 1] = 1; - for (int i = nums.length - 2; i >= 0; i--) { - int store = nums[i]; - nums[i] = nums[i + 1] * prod; - prod = store; - } - for (int i = 0; i < nums.length; i++) { - arr[i] = arr[i] * nums[i]; - } - return arr; - } } diff --git a/java/239-Sliding-Window-Maximum.java b/java/239-Sliding-Window-Maximum.java index dcd9033dd..f4acef438 100644 --- a/java/239-Sliding-Window-Maximum.java +++ b/java/239-Sliding-Window-Maximum.java @@ -1,15 +1,15 @@ class Solution { - public int[] maxSlidingWindow(int[] nums, int k) { - int[] ans = new int[nums.length - k + 1]; - int j = 0; - Deque q = new LinkedList<>(); - for (int i = 0; i < nums.length; i++) { - if (!q.isEmpty() && q.peekFirst() < i - k + 1) q.pollFirst(); - while (!q.isEmpty() && nums[i] > nums[q.peekLast()]) q.pollLast(); - q.offer(i); - if (i >= k - 1) ans[j++] = nums[q.peekFirst()]; + public int[] maxSlidingWindow(int[] nums, int k) { + int[] ans = new int[nums.length - k + 1]; + int j = 0; + Deque q = new LinkedList<>(); + for (int i = 0; i < nums.length; i++) { + if (!q.isEmpty() && q.peekFirst() < i - k + 1) q.pollFirst(); + while (!q.isEmpty() && nums[i] > nums[q.peekLast()]) q.pollLast(); + q.offer(i); + if (i >= k - 1) ans[j++] = nums[q.peekFirst()]; + } + return ans; } - return ans; - } } diff --git a/java/24 Swap Nodes in Pairs.java b/java/24 Swap Nodes in Pairs.java index 1ab78cde8..f3188ee9d 100644 --- a/java/24 Swap Nodes in Pairs.java +++ b/java/24 Swap Nodes in Pairs.java @@ -1,31 +1,31 @@ //Iterative version class Solution { - public ListNode swapPairs(ListNode head) { - if (head == null || head.next == null) return head; - ListNode dummy = new ListNode(0); - dummy.next = head; - ListNode temp = dummy; - while (temp.next != null && temp.next.next != null) { - ListNode first = temp.next; - ListNode second = temp.next.next; - temp.next = second; - first.next = second.next; - second.next = first; - temp = first; + public ListNode swapPairs(ListNode head) { + if (head == null || head.next == null) return head; + ListNode dummy = new ListNode(0); + dummy.next = head; + ListNode temp = dummy; + while (temp.next != null && temp.next.next != null) { + ListNode first = temp.next; + ListNode second = temp.next.next; + temp.next = second; + first.next = second.next; + second.next = first; + temp = first; + } + return dummy.next; } - return dummy.next; - } } //Recursive version class Solution { - public ListNode swapPairs(ListNode head) { - if (head == null || head.next == null) return head; - ListNode p = head.next; - head.next = swapPairs(head.next.next); - p.next = head; - return p; - } + public ListNode swapPairs(ListNode head) { + if (head == null || head.next == null) return head; + ListNode p = head.next; + head.next = swapPairs(head.next.next); + p.next = head; + return p; + } } diff --git a/java/242-Valid-Anagram.java b/java/242-Valid-Anagram.java index fb28f9dbe..381e5c255 100644 --- a/java/242-Valid-Anagram.java +++ b/java/242-Valid-Anagram.java @@ -1,17 +1,17 @@ class Solution { - public boolean isAnagram(String s, String t) { - if (s.length() != t.length()) return false; + public boolean isAnagram(String s, String t) { + if (s.length() != t.length()) return false; - int[] store = new int[26]; + int[] store = new int[26]; - for (int i = 0; i < s.length(); i++) { - store[s.charAt(i) - 'a']++; - store[t.charAt(i) - 'a']--; - } + for (int i = 0; i < s.length(); i++) { + store[s.charAt(i) - 'a']++; + store[t.charAt(i) - 'a']--; + } - for (int n : store) if (n != 0) return false; + for (int n : store) if (n != 0) return false; - return true; - } + return true; + } } diff --git a/java/25-Reverse-Nodes-in-k-Group.java b/java/25-Reverse-Nodes-in-k-Group.java index f3714b974..26d6ab677 100644 --- a/java/25-Reverse-Nodes-in-k-Group.java +++ b/java/25-Reverse-Nodes-in-k-Group.java @@ -2,23 +2,23 @@ class Solution { - public ListNode reverseKGroup(ListNode head, int k) { - ListNode cur = head; - int count = 0; - while (cur != null && count != k) { - cur = cur.next; - count++; + public ListNode reverseKGroup(ListNode head, int k) { + ListNode cur = head; + int count = 0; + while (cur != null && count != k) { + cur = cur.next; + count++; + } + if (count == k) { + cur = reverseKGroup(cur, k); + while (count-- > 0) { + ListNode temp = head.next; + head.next = cur; + cur = head; + head = temp; + } + head = cur; + } + return head; } - if (count == k) { - cur = reverseKGroup(cur, k); - while (count-- > 0) { - ListNode temp = head.next; - head.next = cur; - cur = head; - head = temp; - } - head = cur; - } - return head; - } } diff --git a/java/252-Meeting-Rooms.java b/java/252-Meeting-Rooms.java index 00ecf62ae..653873b00 100644 --- a/java/252-Meeting-Rooms.java +++ b/java/252-Meeting-Rooms.java @@ -11,31 +11,31 @@ public class Solution { - /** - * @param intervals: an array of meeting time intervals - * @return: if a person could attend all meetings - */ - public boolean canAttendMeetings(List intervals) { - int length = intervals.size(); - if (intervals.size() == 0 || length == 1) return true; - // Write your code here + /** + * @param intervals: an array of meeting time intervals + * @return: if a person could attend all meetings + */ + public boolean canAttendMeetings(List intervals) { + int length = intervals.size(); + if (intervals.size() == 0 || length == 1) return true; + // Write your code here - int[] start = new int[length]; - int[] end = new int[length]; - for (int i = 0; i < length; i++) { - start[i] = intervals.get(i).start; - end[i] = intervals.get(i).end; - } + int[] start = new int[length]; + int[] end = new int[length]; + for (int i = 0; i < length; i++) { + start[i] = intervals.get(i).start; + end[i] = intervals.get(i).end; + } - Arrays.sort(start); - Arrays.sort(end); + Arrays.sort(start); + Arrays.sort(end); - int j = 0; - while (j + 1 < length) { - if (end[j] > start[j + 1]) return false; - j++; - } + int j = 0; + while (j + 1 < length) { + if (end[j] > start[j + 1]) return false; + j++; + } - return true; - } + return true; + } } diff --git a/java/253-Meeting-Rooms-ii.java b/java/253-Meeting-Rooms-ii.java index 0ea0f2540..4637f36ac 100644 --- a/java/253-Meeting-Rooms-ii.java +++ b/java/253-Meeting-Rooms-ii.java @@ -11,28 +11,31 @@ public class Solution { - /** - * @param intervals: an array of meeting time intervals - * @return: the minimum number of conference rooms required - */ - public int minMeetingRooms(List intervals) { - if (intervals.isEmpty()) return 0; + /** + * @param intervals: an array of meeting time intervals + * @return: the minimum number of conference rooms required + */ + public int minMeetingRooms(List intervals) { + if (intervals.isEmpty()) return 0; - Collections.sort(intervals, (a, b) -> Integer.compare(a.start, b.start)); + Collections.sort( + intervals, + (a, b) -> Integer.compare(a.start, b.start) + ); - Queue queue = new PriorityQueue<>((a, b) -> - Integer.compare(a.end, b.end) - ); + Queue queue = new PriorityQueue<>((a, b) -> + Integer.compare(a.end, b.end) + ); - int count = 0; - for (Interval interval : intervals) { - while ( - !queue.isEmpty() && interval.start >= queue.peek().end - ) queue.poll(); + int count = 0; + for (Interval interval : intervals) { + while ( + !queue.isEmpty() && interval.start >= queue.peek().end + ) queue.poll(); - queue.offer(interval); - count = Math.max(count, queue.size()); + queue.offer(interval); + count = Math.max(count, queue.size()); + } + return count; } - return count; - } } diff --git a/java/261-Graph-Valid-Tree.java b/java/261-Graph-Valid-Tree.java index fd438c0c6..5c1e8226a 100644 --- a/java/261-Graph-Valid-Tree.java +++ b/java/261-Graph-Valid-Tree.java @@ -1,41 +1,41 @@ public class Solution { - private Map> adjacencyList = new HashMap<>(); + private Map> adjacencyList = new HashMap<>(); - public boolean validTree(int n, int[][] edges) { - if (n == 0 || n == 1) return true; + public boolean validTree(int n, int[][] edges) { + if (n == 0 || n == 1) return true; - if (edges.length == 0) return false; + if (edges.length == 0) return false; - for (var edge : edges) { - var node1 = edge[0]; - var node2 = edge[1]; - adjacencyList.putIfAbsent(node1, new ArrayList<>()); - adjacencyList.putIfAbsent(node2, new ArrayList<>()); - adjacencyList.get(node1).add(node2); - adjacencyList.get(node2).add(node1); - } + for (var edge : edges) { + var node1 = edge[0]; + var node2 = edge[1]; + adjacencyList.putIfAbsent(node1, new ArrayList<>()); + adjacencyList.putIfAbsent(node2, new ArrayList<>()); + adjacencyList.get(node1).add(node2); + adjacencyList.get(node2).add(node1); + } + + Set visited = new HashSet<>(); - Set visited = new HashSet<>(); + return depthFirstSearch(0, -1, visited) && visited.size() == n; + } - return depthFirstSearch(0, -1, visited) && visited.size() == n; - } + private boolean depthFirstSearch( + int node, + int previous, + Set visited + ) { + if (visited.contains(node)) return false; - private boolean depthFirstSearch( - int node, - int previous, - Set visited - ) { - if (visited.contains(node)) return false; + visited.add(node); - visited.add(node); + for (var neighbor : adjacencyList.get(node)) { + if (neighbor == previous) continue; - for (var neighbor : adjacencyList.get(node)) { - if (neighbor == previous) continue; + if (!depthFirstSearch(neighbor, node, visited)) return false; + } - if (!depthFirstSearch(neighbor, node, visited)) return false; + return true; } - - return true; - } } diff --git a/java/268-Missing-Number.java b/java/268-Missing-Number.java index dee14aad4..f9e43df93 100644 --- a/java/268-Missing-Number.java +++ b/java/268-Missing-Number.java @@ -1,11 +1,11 @@ class Solution { - public int missingNumber(int[] nums) { - int sum = 0; - int total = nums.length * (nums.length + 1) / 2; - for (int i = 0; i < nums.length; i++) { - sum += nums[i]; + public int missingNumber(int[] nums) { + int sum = 0; + int total = nums.length * (nums.length + 1) / 2; + for (int i = 0; i < nums.length; i++) { + sum += nums[i]; + } + return total - sum; } - return total - sum; - } } diff --git a/java/27-Remove-Element.java b/java/27-Remove-Element.java index 4d11b6535..52a17d04e 100644 --- a/java/27-Remove-Element.java +++ b/java/27-Remove-Element.java @@ -1,22 +1,22 @@ class Solution { - public void swap(int[] a, int i, int j) { - int temp = a[i]; - a[i] = a[j]; - a[j] = temp; - } + public void swap(int[] a, int i, int j) { + int temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } - public int removeElement(int[] nums, int val) { - int boundary = nums.length - 1; - int i = 0; - while (i <= boundary) { - if (nums[i] == val) { - swap(nums, i, boundary); - boundary -= 1; - } else { - i += 1; - } + public int removeElement(int[] nums, int val) { + int boundary = nums.length - 1; + int i = 0; + while (i <= boundary) { + if (nums[i] == val) { + swap(nums, i, boundary); + boundary -= 1; + } else { + i += 1; + } + } + return i; } - return i; - } } diff --git a/java/271-Encode-and-Decode-Strings.java b/java/271-Encode-and-Decode-Strings.java index ebfbc23ad..1e9a39a55 100644 --- a/java/271-Encode-and-Decode-Strings.java +++ b/java/271-Encode-and-Decode-Strings.java @@ -1,24 +1,24 @@ public class Solution { - public String encode(List strs) { - StringBuilder encodedString = new StringBuilder(); - for (String str : strs) { - encodedString.append(str.length()).append("#").append(str); + public String encode(List strs) { + StringBuilder encodedString = new StringBuilder(); + for (String str : strs) { + encodedString.append(str.length()).append("#").append(str); + } + return encodedString.toString(); } - return encodedString.toString(); - } - public List decode(String str) { - List list = new ArrayList<>(); - int i = 0; - while (i < str.length()) { - int j = i; - while (str.charAt(j) != '#') j++; + public List decode(String str) { + List list = new ArrayList<>(); + int i = 0; + while (i < str.length()) { + int j = i; + while (str.charAt(j) != '#') j++; - int length = Integer.valueOf(str.substring(i, j)); - i = j + 1 + length; - list.add(str.substring(j + 1, i)); + int length = Integer.valueOf(str.substring(i, j)); + i = j + 1 + length; + list.add(str.substring(j + 1, i)); + } + return list; } - return list; - } } diff --git a/java/279-Perfect-Squares.java b/java/279-Perfect-Squares.java index 64ce66421..8f4aca7f5 100644 --- a/java/279-Perfect-Squares.java +++ b/java/279-Perfect-Squares.java @@ -3,26 +3,26 @@ class Solution { - public int numSquares(int n) { - Queue q = new LinkedList<>(); - //add visited array so we don't go to values which we have traversed already (similar to dp) otherwise this will give tle - HashSet visited = new HashSet<>(); - int ans = 0; - q.offer(n); - while (!q.isEmpty()) { - int size = q.size(); - for (int i = 0; i < size; i++) { - int cur = q.poll(); - if (cur == 0) return ans; - for (int j = 1; j <= cur / j; j++) { - if (!visited.contains(cur - j * j)) { - q.offer(cur - j * j); - visited.add(cur - j * j); - } + public int numSquares(int n) { + Queue q = new LinkedList<>(); + //add visited array so we don't go to values which we have traversed already (similar to dp) otherwise this will give tle + HashSet visited = new HashSet<>(); + int ans = 0; + q.offer(n); + while (!q.isEmpty()) { + int size = q.size(); + for (int i = 0; i < size; i++) { + int cur = q.poll(); + if (cur == 0) return ans; + for (int j = 1; j <= cur / j; j++) { + if (!visited.contains(cur - j * j)) { + q.offer(cur - j * j); + visited.add(cur - j * j); + } + } + } + ans++; } - } - ans++; + return -1; } - return -1; - } } diff --git a/java/286-Walls-and-Gates.java b/java/286-Walls-and-Gates.java index 7a9a7eb46..05c2938d7 100644 --- a/java/286-Walls-and-Gates.java +++ b/java/286-Walls-and-Gates.java @@ -3,35 +3,39 @@ class Solution { - public void wallsAndGates(int[][] rooms) { - Queue q = new LinkedList<>(); - int m = rooms.length; - int n = rooms[0].length; - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (rooms[i][j] == 0) q.add(new int[] { i, j }); - } + public void wallsAndGates(int[][] rooms) { + Queue q = new LinkedList<>(); + int m = rooms.length; + int n = rooms[0].length; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (rooms[i][j] == 0) q.add(new int[] { i, j }); + } + } + if (q.size() == 0) return; + int[][] dirs = { { -1, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 } }; + int dis = 0; + while (!q.isEmpty()) { + ++dis; + int[] cur = q.poll(); + int row = cur[0]; + int col = cur[1]; + for (int[] dir : dirs) { + int x = row + dir[0]; + int y = col + dir[1]; + if ( + x >= m || + y >= n || + x < 0 || + y < 0 || + rooms[x][y] != Integer.MAX_VALUE + ) continue; + q.add(new int[] { x, y }); + //since cur is basically the index of door (which is equal to 0) + //So, we can just grab that value (rooms[row][col]) and add 1 to it and change it every time + rooms[x][y] = rooms[row][col] + 1; + //So, one level further from door (value 0) is equal to 1. Now, we do bfs from that position so value will be 2 and so on. + } + } } - if (q.size() == 0) return; - int[][] dirs = { { -1, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 } }; - int dis = 0; - while (!q.isEmpty()) { - ++dis; - int[] cur = q.poll(); - int row = cur[0]; - int col = cur[1]; - for (int[] dir : dirs) { - int x = row + dir[0]; - int y = col + dir[1]; - if ( - x >= m || y >= n || x < 0 || y < 0 || rooms[x][y] != Integer.MAX_VALUE - ) continue; - q.add(new int[] { x, y }); - //since cur is basically the index of door (which is equal to 0) - //So, we can just grab that value (rooms[row][col]) and add 1 to it and change it every time - rooms[x][y] = rooms[row][col] + 1; - //So, one level further from door (value 0) is equal to 1. Now, we do bfs from that position so value will be 2 and so on. - } - } - } } diff --git a/java/287-Find-the-Duplicate-Number.java b/java/287-Find-the-Duplicate-Number.java index 8d6f65467..3b861c38b 100644 --- a/java/287-Find-the-Duplicate-Number.java +++ b/java/287-Find-the-Duplicate-Number.java @@ -4,23 +4,23 @@ class Solution { - public int findDuplicate(int[] nums) { - int fast = nums[0]; - int slow = nums[0]; - boolean first = true; - while (first || fast != slow) { - if (first) first = false; - slow = nums[slow]; - fast = nums[nums[fast]]; - if (fast == slow) break; + public int findDuplicate(int[] nums) { + int fast = nums[0]; + int slow = nums[0]; + boolean first = true; + while (first || fast != slow) { + if (first) first = false; + slow = nums[slow]; + fast = nums[nums[fast]]; + if (fast == slow) break; + } + int slow2 = nums[0]; + while (slow2 != slow) { + if (first) first = false; + slow2 = nums[slow2]; + slow = nums[slow]; + if (slow2 == slow) return slow; + } + return slow; } - int slow2 = nums[0]; - while (slow2 != slow) { - if (first) first = false; - slow2 = nums[slow2]; - slow = nums[slow]; - if (slow2 == slow) return slow; - } - return slow; - } } diff --git a/java/295-Find-Median-from-Data-Stream.java b/java/295-Find-Median-from-Data-Stream.java index e08c83e73..359fc1269 100644 --- a/java/295-Find-Median-from-Data-Stream.java +++ b/java/295-Find-Median-from-Data-Stream.java @@ -1,36 +1,36 @@ class MedianFinder { - private Queue smallHeap; //small elements - maxHeap - private Queue largeHeap; //large elements - minHeap + private Queue smallHeap; //small elements - maxHeap + private Queue largeHeap; //large elements - minHeap - public MedianFinder() { - smallHeap = new PriorityQueue<>((a, b) -> b - a); - largeHeap = new PriorityQueue<>((a, b) -> a - b); - } - - public void addNum(int num) { - smallHeap.add(num); - if ( - smallHeap.size() - largeHeap.size() > 1 || - !largeHeap.isEmpty() && - smallHeap.peek() > largeHeap.peek() - ) { - largeHeap.add(smallHeap.poll()); + public MedianFinder() { + smallHeap = new PriorityQueue<>((a, b) -> b - a); + largeHeap = new PriorityQueue<>((a, b) -> a - b); } - if (largeHeap.size() - smallHeap.size() > 1) { - smallHeap.add(largeHeap.poll()); + + public void addNum(int num) { + smallHeap.add(num); + if ( + smallHeap.size() - largeHeap.size() > 1 || + !largeHeap.isEmpty() && + smallHeap.peek() > largeHeap.peek() + ) { + largeHeap.add(smallHeap.poll()); + } + if (largeHeap.size() - smallHeap.size() > 1) { + smallHeap.add(largeHeap.poll()); + } } - } - public double findMedian() { - if (smallHeap.size() == largeHeap.size()) { - return (double) (largeHeap.peek() + smallHeap.peek()) / 2; - } else if (smallHeap.size() > largeHeap.size()) { - return (double) smallHeap.peek(); - } else { - return (double) largeHeap.peek(); + public double findMedian() { + if (smallHeap.size() == largeHeap.size()) { + return (double) (largeHeap.peek() + smallHeap.peek()) / 2; + } else if (smallHeap.size() > largeHeap.size()) { + return (double) smallHeap.peek(); + } else { + return (double) largeHeap.peek(); + } } - } } /** * Your MedianFinder object will be instantiated and called as such: diff --git a/java/297-Serialize-and-Deserialize-Binary-Tree.java b/java/297-Serialize-and-Deserialize-Binary-Tree.java index 70a3ec865..ed5af6eba 100644 --- a/java/297-Serialize-and-Deserialize-Binary-Tree.java +++ b/java/297-Serialize-and-Deserialize-Binary-Tree.java @@ -9,44 +9,44 @@ */ public class Codec { - private int i; + private int i; - // Encodes a tree to a single string. - public String serialize(TreeNode root) { - List list = new ArrayList<>(); - serializeDFS(root, list); + // Encodes a tree to a single string. + public String serialize(TreeNode root) { + List list = new ArrayList<>(); + serializeDFS(root, list); - return String.join(",", list); - } + return String.join(",", list); + } - private void serializeDFS(TreeNode root, List list) { - if (root == null) { - list.add("N"); - return; + private void serializeDFS(TreeNode root, List list) { + if (root == null) { + list.add("N"); + return; + } + list.add(String.valueOf(root.val)); + serializeDFS(root.left, list); + serializeDFS(root.right, list); } - list.add(String.valueOf(root.val)); - serializeDFS(root.left, list); - serializeDFS(root.right, list); - } - // Decodes your encoded data to tree. - public TreeNode deserialize(String data) { - String[] tokens = data.split(","); - return deserializeDFS(tokens); - } + // Decodes your encoded data to tree. + public TreeNode deserialize(String data) { + String[] tokens = data.split(","); + return deserializeDFS(tokens); + } - private TreeNode deserializeDFS(String[] tokens) { - String token = tokens[this.i]; - if (token.equals("N")) { - this.i++; - return null; + private TreeNode deserializeDFS(String[] tokens) { + String token = tokens[this.i]; + if (token.equals("N")) { + this.i++; + return null; + } + var node = new TreeNode(Integer.parseInt(token)); + this.i++; + node.left = deserializeDFS(tokens); + node.right = deserializeDFS(tokens); + return node; } - var node = new TreeNode(Integer.parseInt(token)); - this.i++; - node.left = deserializeDFS(tokens); - node.right = deserializeDFS(tokens); - return node; - } } // Your Codec object will be instantiated and called as such: // Codec ser = new Codec(); diff --git a/java/3-Longest-Substring-Without-Repeating-Characters.java b/java/3-Longest-Substring-Without-Repeating-Characters.java index d460e5710..8c7c524a4 100644 --- a/java/3-Longest-Substring-Without-Repeating-Characters.java +++ b/java/3-Longest-Substring-Without-Repeating-Characters.java @@ -1,17 +1,17 @@ class Solution { - public int lengthOfLongestSubstring(String s) { - HashSet set = new HashSet<>(); - int left = 0; - int ans = 0; - for (int right = 0; right < s.length(); right++) { - while (set.contains(s.charAt(right))) { - set.remove(s.charAt(left)); - left++; - } - set.add(s.charAt(right)); - ans = Math.max(ans, right - left + 1); + public int lengthOfLongestSubstring(String s) { + HashSet set = new HashSet<>(); + int left = 0; + int ans = 0; + for (int right = 0; right < s.length(); right++) { + while (set.contains(s.charAt(right))) { + set.remove(s.charAt(left)); + left++; + } + set.add(s.charAt(right)); + ans = Math.max(ans, right - left + 1); + } + return ans; } - return ans; - } } diff --git a/java/300-Longest-Increasing-Subsequence.java b/java/300-Longest-Increasing-Subsequence.java index 081a03c0c..7e26b0bbf 100644 --- a/java/300-Longest-Increasing-Subsequence.java +++ b/java/300-Longest-Increasing-Subsequence.java @@ -1,21 +1,21 @@ class Solution { - public int lengthOfLIS(int[] nums) { - //O(n^2) - if (nums.length == 1) return 1; + public int lengthOfLIS(int[] nums) { + //O(n^2) + if (nums.length == 1) return 1; - int[] LIS = new int[nums.length]; - Arrays.fill(LIS, 1); - int maximumSoFar = 1; + int[] LIS = new int[nums.length]; + Arrays.fill(LIS, 1); + int maximumSoFar = 1; - for (int i = nums.length - 1; i >= 0; i--) { - for (int j = i + 1; j < nums.length; j++) { - if (nums[i] < nums[j]) { - LIS[i] = Math.max(1 + LIS[j], LIS[i]); + for (int i = nums.length - 1; i >= 0; i--) { + for (int j = i + 1; j < nums.length; j++) { + if (nums[i] < nums[j]) { + LIS[i] = Math.max(1 + LIS[j], LIS[i]); + } + } + maximumSoFar = Math.max(maximumSoFar, LIS[i]); } - } - maximumSoFar = Math.max(maximumSoFar, LIS[i]); + return maximumSoFar; } - return maximumSoFar; - } } diff --git a/java/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.java b/java/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.java index 0c42e65c5..efa842b32 100644 --- a/java/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.java +++ b/java/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.java @@ -1,35 +1,35 @@ class Solution { - public int maxProfit(int[] prices) { - Map cache = new HashMap<>(); - return dfs(prices, cache, 0, true); - } - - public int dfs( - int[] prices, - Map cache, - int index, - boolean buying - ) { - if (index >= prices.length) { - return 0; + public int maxProfit(int[] prices) { + Map cache = new HashMap<>(); + return dfs(prices, cache, 0, true); } - String key = index + "-" + buying; - if (cache.containsKey(key)) { - return cache.get(key); - } + public int dfs( + int[] prices, + Map cache, + int index, + boolean buying + ) { + if (index >= prices.length) { + return 0; + } + String key = index + "-" + buying; - int cooldown = dfs(prices, cache, index + 1, buying); - int buyOsell = Integer.MIN_VALUE; + if (cache.containsKey(key)) { + return cache.get(key); + } - if (buying) { - buyOsell = dfs(prices, cache, index + 1, !buying) - prices[index]; - } else { - buyOsell = dfs(prices, cache, index + 2, !buying) + prices[index]; - } + int cooldown = dfs(prices, cache, index + 1, buying); + int buyOsell = Integer.MIN_VALUE; - cache.put(key, Math.max(buyOsell, cooldown)); - return cache.get(key); - } + if (buying) { + buyOsell = dfs(prices, cache, index + 1, !buying) - prices[index]; + } else { + buyOsell = dfs(prices, cache, index + 2, !buying) + prices[index]; + } + + cache.put(key, Math.max(buyOsell, cooldown)); + return cache.get(key); + } } diff --git a/java/322-Coin-Change.java b/java/322-Coin-Change.java index a5d4e9f18..8d3a7f786 100644 --- a/java/322-Coin-Change.java +++ b/java/322-Coin-Change.java @@ -2,22 +2,22 @@ class Solution { - public int coinChange(int[] coins, int amount) { - if (amount < 0 || coins.length == 0 || coins == null) { - return 0; - } - int[] dp = new int[amount + 1]; - Arrays.fill(dp, amount + 1); - dp[0] = 0; + public int coinChange(int[] coins, int amount) { + if (amount < 0 || coins.length == 0 || coins == null) { + return 0; + } + int[] dp = new int[amount + 1]; + Arrays.fill(dp, amount + 1); + dp[0] = 0; - for (int i = 1; i <= amount; i++) { - for (int coin : coins) { - if (i - coin >= 0) { - dp[i] = Math.min(dp[i], 1 + dp[i - coin]); + for (int i = 1; i <= amount; i++) { + for (int coin : coins) { + if (i - coin >= 0) { + dp[i] = Math.min(dp[i], 1 + dp[i - coin]); + } + } } - } - } - return dp[amount] != amount + 1 ? dp[amount] : -1; - } + return dp[amount] != amount + 1 ? dp[amount] : -1; + } } diff --git a/java/323-Number-of-Connected-Components-in-an-Undirected-Graph.java b/java/323-Number-of-Connected-Components-in-an-Undirected-Graph.java index 17c8b24fe..ac0e8aeac 100644 --- a/java/323-Number-of-Connected-Components-in-an-Undirected-Graph.java +++ b/java/323-Number-of-Connected-Components-in-an-Undirected-Graph.java @@ -1,54 +1,54 @@ class Solution { - private int[] parent; - private int[] rank; - - public int countComponents(int n, int[][] edges) { - parent = new int[n]; - rank = new int[n]; - - for (int i = 0; i < n; i++) { - parent[i] = i; - rank[i] = 1; - } - - int result = n; - for (int i = 0; i < edges.length; i++) { - if (union(edges[i][0], edges[i][1]) == 1) { - result--; - } + private int[] parent; + private int[] rank; + + public int countComponents(int n, int[][] edges) { + parent = new int[n]; + rank = new int[n]; + + for (int i = 0; i < n; i++) { + parent[i] = i; + rank[i] = 1; + } + + int result = n; + for (int i = 0; i < edges.length; i++) { + if (union(edges[i][0], edges[i][1]) == 1) { + result--; + } + } + + return result; } - return result; - } + private int find(int node) { + int result = node; - private int find(int node) { - int result = node; + while (parent[result] != result) { + parent[result] = parent[parent[result]]; + result = parent[result]; + } - while (parent[result] != result) { - parent[result] = parent[parent[result]]; - result = parent[result]; + return result; } - return result; - } + private int union(int n1, int n2) { + int p1 = this.find(n1); + int p2 = this.find(n2); - private int union(int n1, int n2) { - int p1 = this.find(n1); - int p2 = this.find(n2); + if (p1 == p2) { + return 0; + } - if (p1 == p2) { - return 0; - } + if (rank[p2] > rank[p1]) { + parent[p1] = p2; + rank[p2] += rank[p1]; + } else { + parent[p2] = p1; + rank[p1] += rank[p2]; + } - if (rank[p2] > rank[p1]) { - parent[p1] = p2; - rank[p2] += rank[p1]; - } else { - parent[p2] = p1; - rank[p1] += rank[p2]; + return 1; } - - return 1; - } } diff --git a/java/329-Longest-Increasing-Path-in-a-Matrix.java b/java/329-Longest-Increasing-Path-in-a-Matrix.java index 4eeac8bcc..bab0de730 100644 --- a/java/329-Longest-Increasing-Path-in-a-Matrix.java +++ b/java/329-Longest-Increasing-Path-in-a-Matrix.java @@ -2,40 +2,42 @@ class Solution { - public int longestIncreasingPath(int[][] matrix) { - int m = matrix.length; - int n = matrix[0].length; - int[][] dp = new int[m][n]; - for (int d[] : dp) Arrays.fill(d, -1); - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (dp[i][j] == -1) dfs(matrix, dp, m, n, i, j, -1); - } + public int longestIncreasingPath(int[][] matrix) { + int m = matrix.length; + int n = matrix[0].length; + int[][] dp = new int[m][n]; + for (int d[] : dp) Arrays.fill(d, -1); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (dp[i][j] == -1) dfs(matrix, dp, m, n, i, j, -1); + } + } + int max = Integer.MIN_VALUE; + for (int[] d : dp) { + for (int i : d) max = Math.max(i, max); + } + return max; } - int max = Integer.MIN_VALUE; - for (int[] d : dp) { - for (int i : d) max = Math.max(i, max); - } - return max; - } - public int dfs( - int[][] matrix, - int[][] dp, - int m, - int n, - int i, - int j, - int parent - ) { - if (i >= m || j >= n || i < 0 || j < 0 || matrix[i][j] <= parent) return 0; - parent = matrix[i][j]; - if (dp[i][j] != -1) return dp[i][j]; - int left = dfs(matrix, dp, m, n, i, j - 1, parent); - int right = dfs(matrix, dp, m, n, i, j + 1, parent); - int bottom = dfs(matrix, dp, m, n, i + 1, j, parent); - int top = dfs(matrix, dp, m, n, i - 1, j, parent); - dp[i][j] = 1 + Math.max(Math.max(left, right), Math.max(top, bottom)); - return dp[i][j]; - } + public int dfs( + int[][] matrix, + int[][] dp, + int m, + int n, + int i, + int j, + int parent + ) { + if ( + i >= m || j >= n || i < 0 || j < 0 || matrix[i][j] <= parent + ) return 0; + parent = matrix[i][j]; + if (dp[i][j] != -1) return dp[i][j]; + int left = dfs(matrix, dp, m, n, i, j - 1, parent); + int right = dfs(matrix, dp, m, n, i, j + 1, parent); + int bottom = dfs(matrix, dp, m, n, i + 1, j, parent); + int top = dfs(matrix, dp, m, n, i - 1, j, parent); + dp[i][j] = 1 + Math.max(Math.max(left, right), Math.max(top, bottom)); + return dp[i][j]; + } } diff --git a/java/33-Search-In-Rotated-Sorted-Array.java b/java/33-Search-In-Rotated-Sorted-Array.java index 1b695a98c..c04f2399c 100644 --- a/java/33-Search-In-Rotated-Sorted-Array.java +++ b/java/33-Search-In-Rotated-Sorted-Array.java @@ -1,47 +1,47 @@ class Solution { - public int search(int[] nums, int target) { - int minIndex = minIndex(nums); - int leftSearch = binarySearch(nums, 0, minIndex - 1, target); - int rightSearch = binarySearch(nums, minIndex, nums.length - 1, target); - if (leftSearch != -1) { - return leftSearch; - } else if (rightSearch != -1) { - return rightSearch; - } else { - return -1; + public int search(int[] nums, int target) { + int minIndex = minIndex(nums); + int leftSearch = binarySearch(nums, 0, minIndex - 1, target); + int rightSearch = binarySearch(nums, minIndex, nums.length - 1, target); + if (leftSearch != -1) { + return leftSearch; + } else if (rightSearch != -1) { + return rightSearch; + } else { + return -1; + } } - } - public int minIndex(int[] nums) { - int start = 0; - int end = nums.length - 1; - while (start <= end) { - int mid = start + (end - start) / 2; - int prev = (mid - 1 + nums.length) % nums.length; - int next = (mid + 1) % nums.length; - if (nums[mid] <= nums[prev] && nums[mid] <= nums[next]) { - return mid; - } else if (nums[mid] <= nums[end]) { - end = mid - 1; - } else if (nums[mid] >= nums[start]) { - start = mid + 1; - } + public int minIndex(int[] nums) { + int start = 0; + int end = nums.length - 1; + while (start <= end) { + int mid = start + (end - start) / 2; + int prev = (mid - 1 + nums.length) % nums.length; + int next = (mid + 1) % nums.length; + if (nums[mid] <= nums[prev] && nums[mid] <= nums[next]) { + return mid; + } else if (nums[mid] <= nums[end]) { + end = mid - 1; + } else if (nums[mid] >= nums[start]) { + start = mid + 1; + } + } + return -1; } - return -1; - } - public int binarySearch(int[] nums, int start, int end, int target) { - while (start <= end) { - int mid = start + (end - start) / 2; - if (nums[mid] == target) { - return mid; - } else if (nums[mid] < target) { - start = mid + 1; - } else { - end = mid - 1; - } + public int binarySearch(int[] nums, int start, int end, int target) { + while (start <= end) { + int mid = start + (end - start) / 2; + if (nums[mid] == target) { + return mid; + } else if (nums[mid] < target) { + start = mid + 1; + } else { + end = mid - 1; + } + } + return -1; } - return -1; - } } diff --git a/java/338-Counting-Bits.java b/java/338-Counting-Bits.java index e90045ab2..3d1c13c1c 100644 --- a/java/338-Counting-Bits.java +++ b/java/338-Counting-Bits.java @@ -1,20 +1,20 @@ class Solution { - public int[] countBits(int n) { - int[] ans = new int[n + 1]; + public int[] countBits(int n) { + int[] ans = new int[n + 1]; - for (int i = 0; i <= n; i++) { - ans[i] = count(i); + for (int i = 0; i <= n; i++) { + ans[i] = count(i); + } + return ans; } - return ans; - } - private int count(int x) { - int count = 0; - while (x != 0) { - x &= x - 1; - count++; + private int count(int x) { + int count = 0; + while (x != 0) { + x &= x - 1; + count++; + } + return count; } - return count; - } } diff --git a/java/347-Top-K-Frequent-Elements.java b/java/347-Top-K-Frequent-Elements.java index dfe71a113..6e822ae2f 100644 --- a/java/347-Top-K-Frequent-Elements.java +++ b/java/347-Top-K-Frequent-Elements.java @@ -1,88 +1,91 @@ class Solution1 { - /** - * Time Complexity: O(nlog(k)) - * Space Complexity: O(n) - */ - public int[] topKFrequent(int[] nums, int k) { - int[] arr = new int[k]; - HashMap map = new HashMap<>(); - for (int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); - PriorityQueue> pq = new PriorityQueue<>( - (a, b) -> - a.getValue() - b.getValue() - ); - for (Map.Entry it : map.entrySet()) { - pq.add(it); - if (pq.size() > k) pq.poll(); + /** + * Time Complexity: O(nlog(k)) + * Space Complexity: O(n) + */ + public int[] topKFrequent(int[] nums, int k) { + int[] arr = new int[k]; + HashMap map = new HashMap<>(); + for (int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); + PriorityQueue> pq = new PriorityQueue<>( + (a, b) -> + a.getValue() - b.getValue() + ); + for (Map.Entry it : map.entrySet()) { + pq.add(it); + if (pq.size() > k) pq.poll(); + } + int i = k; + while (!pq.isEmpty()) { + arr[--i] = pq.poll().getKey(); + } + return arr; } - int i = k; - while (!pq.isEmpty()) { - arr[--i] = pq.poll().getKey(); - } - return arr; - } } class Solution2 { - /** - * Time Complexity: O(n) - * Space Complexity: O(n) - */ - public int[] topKFrequent(int[] numbers, int k) { - HashMap map = new HashMap<>(); - for (int number : numbers) map.put(number, map.getOrDefault(number, 0) + 1); + /** + * Time Complexity: O(n) + * Space Complexity: O(n) + */ + public int[] topKFrequent(int[] numbers, int k) { + HashMap map = new HashMap<>(); + for (int number : numbers) map.put( + number, + map.getOrDefault(number, 0) + 1 + ); - int size = map.size(); - int[] keys = new int[size]; - int i = 0; - for (int key : map.keySet()) keys[i++] = key; + int size = map.size(); + int[] keys = new int[size]; + int i = 0; + for (int key : map.keySet()) keys[i++] = key; - select(keys, map, 0, size - 1, size - k); - return Arrays.copyOfRange(keys, size - k, size); - } + select(keys, map, 0, size - 1, size - k); + return Arrays.copyOfRange(keys, size - k, size); + } - // Modified implementation of Hoare's selection algorithm: + // Modified implementation of Hoare's selection algorithm: - private void select( - int[] keys, - Map map, - int left, - int right, - int kSmallest - ) { - while (left != right) { - int pivot = partition(keys, map, left, right, (left + right) / 2); + private void select( + int[] keys, + Map map, + int left, + int right, + int kSmallest + ) { + while (left != right) { + int pivot = partition(keys, map, left, right, (left + right) / 2); - if (kSmallest == pivot) return; + if (kSmallest == pivot) return; - if (kSmallest < pivot) right = pivot - 1; else left = pivot + 1; + if (kSmallest < pivot) right = pivot - 1; else left = pivot + 1; + } } - } - private int partition( - int[] keys, - Map map, - int left, - int right, - int pivot - ) { - int pivotValue = map.get(keys[pivot]); - swap(keys, pivot, right); - int index = left; + private int partition( + int[] keys, + Map map, + int left, + int right, + int pivot + ) { + int pivotValue = map.get(keys[pivot]); + swap(keys, pivot, right); + int index = left; - for (int i = left; i <= right; i++) if (map.get(keys[i]) < pivotValue) { - swap(keys, i, index); - index++; + for (int i = left; i <= right; i++) if (map.get(keys[i]) < pivotValue) { + swap(keys, i, index); + index++; + } + swap(keys, right, index); + return index; } - swap(keys, right, index); - return index; - } - private void swap(int[] array, int i1, int i2) { - int temp = array[i1]; - array[i1] = array[i2]; - array[i2] = temp; - } + private void swap(int[] array, int i1, int i2) { + int temp = array[i1]; + array[i1] = array[i2]; + array[i2] = temp; + } } diff --git a/java/36-valid-sudoku.java b/java/36-valid-sudoku.java index 85c404d61..50ce23bb9 100644 --- a/java/36-valid-sudoku.java +++ b/java/36-valid-sudoku.java @@ -1,30 +1,30 @@ class Solution { - public boolean isValidSudoku(char[][] board) { - HashSet h1 = new HashSet(); + public boolean isValidSudoku(char[][] board) { + HashSet h1 = new HashSet(); - for (int i = 0; i < 9; i++) { - for (int j = 0; j < 9; j++) { - if (board[i][j] != '.') { - //Check whether HashSet contains duplicate elements in row and column - if ( - h1.contains("row" + i + board[i][j]) || - h1.contains("col" + j + board[i][j]) - ) { - return false; - } - h1.add("row" + i + board[i][j]); - h1.add("col" + j + board[i][j]); + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + if (board[i][j] != '.') { + //Check whether HashSet contains duplicate elements in row and column + if ( + h1.contains("row" + i + board[i][j]) || + h1.contains("col" + j + board[i][j]) + ) { + return false; + } + h1.add("row" + i + board[i][j]); + h1.add("col" + j + board[i][j]); - //Check whether Box contains duplicate elements in it - if (h1.contains("box" + (i / 3) + (j / 3) + board[i][j])) { - return false; - } - h1.add("box" + (i / 3) + (j / 3) + board[i][j]); + //Check whether Box contains duplicate elements in it + if (h1.contains("box" + (i / 3) + (j / 3) + board[i][j])) { + return false; + } + h1.add("box" + (i / 3) + (j / 3) + board[i][j]); + } + } } - } - } - return true; - } + return true; + } } diff --git a/java/37-Sudoku-Solver.java b/java/37-Sudoku-Solver.java index 09dda503d..e566b56b8 100644 --- a/java/37-Sudoku-Solver.java +++ b/java/37-Sudoku-Solver.java @@ -3,53 +3,54 @@ class Solution { - public void solveSudoku(char[][] board) { - solve(board); - } + public void solveSudoku(char[][] board) { + solve(board); + } - public boolean solve(char[][] board) { - //traverse the complete sudoku and look for empty value - for (int i = 0; i < 9; i++) { - for (int j = 0; j < 9; j++) { - //look for '.' (empty block) - if (board[i][j] == '.') { - //try filling all values - for (char c = '1'; c <= '9'; c++) { - //check if we can put that value at that place - //we will have a function for this which will check all the - //three conditions for a valid sudoku - if (isValid(board, i, j, c)) { - board[i][j] = c; - //check whether the new board is solvable and just return true if it is - //so, we can just have only one sudoku combination. - //else backtrack, i.e., make it '.' again. - if (solve(board)) return true; else board[i][j] = '.'; + public boolean solve(char[][] board) { + //traverse the complete sudoku and look for empty value + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + //look for '.' (empty block) + if (board[i][j] == '.') { + //try filling all values + for (char c = '1'; c <= '9'; c++) { + //check if we can put that value at that place + //we will have a function for this which will check all the + //three conditions for a valid sudoku + if (isValid(board, i, j, c)) { + board[i][j] = c; + //check whether the new board is solvable and just return true if it is + //so, we can just have only one sudoku combination. + //else backtrack, i.e., make it '.' again. + if (solve(board)) return true; else board[i][j] = + '.'; + } + } + //if the board[i][j] is empty and we checked all values and + //nothing from '0' to '9' can be added then return false + //as this is unsolvable + return false; + } } - } - //if the board[i][j] is empty and we checked all values and - //nothing from '0' to '9' can be added then return false - //as this is unsolvable - return false; } - } + return true; } - return true; - } - public boolean isValid(char[][] board, int row, int col, char c) { - for (int i = 0; i < 9; i++) { - //row check - if (board[row][i] == c) return false; - //col check - if (board[i][col] == c) return false; - //boxes check - //for this draw a sudoku and see by marking boxes and choosing a random postion - //this is hard to explain but try this one - //you'll get to the formula by yourself - if ( - board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c - ) return false; + public boolean isValid(char[][] board, int row, int col, char c) { + for (int i = 0; i < 9; i++) { + //row check + if (board[row][i] == c) return false; + //col check + if (board[i][col] == c) return false; + //boxes check + //for this draw a sudoku and see by marking boxes and choosing a random postion + //this is hard to explain but try this one + //you'll get to the formula by yourself + if ( + board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c + ) return false; + } + return true; } - return true; - } } diff --git a/java/371-Sum-of-Two-Integers.java b/java/371-Sum-of-Two-Integers.java index bac4c5b7d..2961fca14 100644 --- a/java/371-Sum-of-Two-Integers.java +++ b/java/371-Sum-of-Two-Integers.java @@ -1,11 +1,11 @@ class Solution { - public int getSum(int a, int b) { - while (b != 0) { - int tmp = (a & b) << 1; - a = (a ^ b); - b = tmp; + public int getSum(int a, int b) { + while (b != 0) { + int tmp = (a & b) << 1; + a = (a ^ b); + b = tmp; + } + return a; } - return a; - } } diff --git a/java/39-Combination-Sum.java b/java/39-Combination-Sum.java index 52cdf0495..e33fc50e8 100644 --- a/java/39-Combination-Sum.java +++ b/java/39-Combination-Sum.java @@ -1,29 +1,29 @@ class Solution { - public List> combinationSum(int[] candidates, int target) { - List> ans = new ArrayList>(); - List cur = new ArrayList(); - backtrack(candidates, target, ans, cur, 0); - return ans; - } + public List> combinationSum(int[] candidates, int target) { + List> ans = new ArrayList>(); + List cur = new ArrayList(); + backtrack(candidates, target, ans, cur, 0); + return ans; + } - public void backtrack( - int[] candidates, - int target, - List> ans, - List cur, - int index - ) { - if (target == 0) { - ans.add(new ArrayList(cur)); - } else if (target < 0 || index >= candidates.length) { - return; - } else { - cur.add(candidates[index]); - backtrack(candidates, target - candidates[index], ans, cur, index); + public void backtrack( + int[] candidates, + int target, + List> ans, + List cur, + int index + ) { + if (target == 0) { + ans.add(new ArrayList(cur)); + } else if (target < 0 || index >= candidates.length) { + return; + } else { + cur.add(candidates[index]); + backtrack(candidates, target - candidates[index], ans, cur, index); - cur.remove(cur.get(cur.size() - 1)); - backtrack(candidates, target, ans, cur, index + 1); + cur.remove(cur.get(cur.size() - 1)); + backtrack(candidates, target, ans, cur, index + 1); + } } - } } diff --git a/java/4-Median-of-Two-Sorted-Arrays.java b/java/4-Median-of-Two-Sorted-Arrays.java index d7cfeed9d..6ee680c01 100644 --- a/java/4-Median-of-Two-Sorted-Arrays.java +++ b/java/4-Median-of-Two-Sorted-Arrays.java @@ -29,51 +29,53 @@ public double findMedianSortedArrays(int[] nums1, int[] nums2) { class Solution { - public double findMedianSortedArrays(int[] nums1, int[] nums2) { - int m = nums1.length; - int n = nums2.length; + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + int m = nums1.length; + int n = nums2.length; - if (m > n) { - return findMedianSortedArrays(nums2, nums1); - } + if (m > n) { + return findMedianSortedArrays(nums2, nums1); + } - int total = m + n; - int half = (total + 1) / 2; + int total = m + n; + int half = (total + 1) / 2; - int left = 0; - int right = m; + int left = 0; + int right = m; - var result = 0.0; + var result = 0.0; - while (left <= right) { - int i = left + (right - left) / 2; - int j = half - i; + while (left <= right) { + int i = left + (right - left) / 2; + int j = half - i; - // get the four points around possible median - int left1 = (i > 0) ? nums1[i - 1] : Integer.MIN_VALUE; - int right1 = (i < m) ? nums1[i] : Integer.MAX_VALUE; - int left2 = (j > 0) ? nums2[j - 1] : Integer.MIN_VALUE; - int right2 = (j < n) ? nums2[j] : Integer.MAX_VALUE; + // get the four points around possible median + int left1 = (i > 0) ? nums1[i - 1] : Integer.MIN_VALUE; + int right1 = (i < m) ? nums1[i] : Integer.MAX_VALUE; + int left2 = (j > 0) ? nums2[j - 1] : Integer.MIN_VALUE; + int right2 = (j < n) ? nums2[j] : Integer.MAX_VALUE; - // partition is correct - if (left1 <= right2 && left2 <= right1) { - // even - if (total % 2 == 0) { - result = (Math.max(left1, left2) + Math.min(right1, right2)) / 2.0; - // odd - } else { - result = Math.max(left1, left2); + // partition is correct + if (left1 <= right2 && left2 <= right1) { + // even + if (total % 2 == 0) { + result = + (Math.max(left1, left2) + Math.min(right1, right2)) / + 2.0; + // odd + } else { + result = Math.max(left1, left2); + } + break; + } + // partition is wrong (update left/right pointers) + else if (left1 > right2) { + right = i - 1; + } else { + left = i + 1; + } } - break; - } - // partition is wrong (update left/right pointers) - else if (left1 > right2) { - right = i - 1; - } else { - left = i + 1; - } - } - return result; - } + return result; + } } diff --git a/java/40-Combination-Sum-II.java b/java/40-Combination-Sum-II.java index 4c3b4bbf9..c773f67ab 100644 --- a/java/40-Combination-Sum-II.java +++ b/java/40-Combination-Sum-II.java @@ -1,29 +1,29 @@ class Solution { - public List> combinationSum2(int[] candidates, int target) { - Arrays.sort(candidates); - List> ans = new ArrayList>(); - List ls = new ArrayList(); - comb(candidates, target, ans, ls, 0); - return ans; - } + public List> combinationSum2(int[] candidates, int target) { + Arrays.sort(candidates); + List> ans = new ArrayList>(); + List ls = new ArrayList(); + comb(candidates, target, ans, ls, 0); + return ans; + } - public void comb( - int[] candidates, - int target, - List> ans, - List ls, - int index - ) { - if (target == 0) { - ans.add(new ArrayList(ls)); - } else if (target < 0) return; else { - for (int i = index; i < candidates.length; i++) { - if (i > index && candidates[i] == candidates[i - 1]) continue; - ls.add(candidates[i]); - comb(candidates, target - candidates[i], ans, ls, i + 1); - ls.remove(ls.get(ls.size() - 1)); - } + public void comb( + int[] candidates, + int target, + List> ans, + List ls, + int index + ) { + if (target == 0) { + ans.add(new ArrayList(ls)); + } else if (target < 0) return; else { + for (int i = index; i < candidates.length; i++) { + if (i > index && candidates[i] == candidates[i - 1]) continue; + ls.add(candidates[i]); + comb(candidates, target - candidates[i], ans, ls, i + 1); + ls.remove(ls.get(ls.size() - 1)); + } + } } - } } diff --git a/java/416-Partition-Equal-Subset-Sum.java b/java/416-Partition-Equal-Subset-Sum.java index 8aab8deeb..a62dcc850 100644 --- a/java/416-Partition-Equal-Subset-Sum.java +++ b/java/416-Partition-Equal-Subset-Sum.java @@ -1,25 +1,26 @@ class Solution { - public boolean canPartition(int[] nums) { - int sum = 0; - for (int num : nums) { - sum += num; - } - if (sum % 2 != 0) return false; - int target = sum / 2; - boolean[][] dp = new boolean[nums.length + 1][target + 1]; - int n = nums.length; - for (int i = 0; i <= n; i++) { - for (int j = 0; j <= target; j++) { - if (i == 0 || j == 0) { - if (i == 0) dp[i][j] = false; else if (j == 0) dp[i][j] = true; - } else if (j >= nums[i - 1]) { - dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]]; - } else { - dp[i][j] = dp[i - 1][j]; + public boolean canPartition(int[] nums) { + int sum = 0; + for (int num : nums) { + sum += num; + } + if (sum % 2 != 0) return false; + int target = sum / 2; + boolean[][] dp = new boolean[nums.length + 1][target + 1]; + int n = nums.length; + for (int i = 0; i <= n; i++) { + for (int j = 0; j <= target; j++) { + if (i == 0 || j == 0) { + if (i == 0) dp[i][j] = false; else if (j == 0) dp[i][j] = + true; + } else if (j >= nums[i - 1]) { + dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]]; + } else { + dp[i][j] = dp[i - 1][j]; + } + } } - } + return dp[n][target]; } - return dp[n][target]; - } } diff --git a/java/417-Pacific-Atlantic-Water-Flow.java b/java/417-Pacific-Atlantic-Water-Flow.java index cde0f79fe..fd0b1ad41 100644 --- a/java/417-Pacific-Atlantic-Water-Flow.java +++ b/java/417-Pacific-Atlantic-Water-Flow.java @@ -1,41 +1,47 @@ class Solution { - int[][] dir = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } }; + int[][] dir = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } }; - public List> pacificAtlantic(int[][] heights) { - List> res = new ArrayList<>(); + public List> pacificAtlantic(int[][] heights) { + List> res = new ArrayList<>(); - int rows = heights.length, cols = heights[0].length; - boolean[][] pacific = new boolean[rows][cols]; - boolean[][] atlantic = new boolean[rows][cols]; + int rows = heights.length, cols = heights[0].length; + boolean[][] pacific = new boolean[rows][cols]; + boolean[][] atlantic = new boolean[rows][cols]; - for (int i = 0; i < cols; i++) { - dfs(heights, 0, i, Integer.MIN_VALUE, pacific); - dfs(heights, rows - 1, i, Integer.MIN_VALUE, atlantic); - } + for (int i = 0; i < cols; i++) { + dfs(heights, 0, i, Integer.MIN_VALUE, pacific); + dfs(heights, rows - 1, i, Integer.MIN_VALUE, atlantic); + } - for (int i = 0; i < rows; i++) { - dfs(heights, i, 0, Integer.MIN_VALUE, pacific); - dfs(heights, i, cols - 1, Integer.MIN_VALUE, atlantic); - } + for (int i = 0; i < rows; i++) { + dfs(heights, i, 0, Integer.MIN_VALUE, pacific); + dfs(heights, i, cols - 1, Integer.MIN_VALUE, atlantic); + } - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { - if (pacific[i][j] && atlantic[i][j]) { - res.add(Arrays.asList(i, j)); + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (pacific[i][j] && atlantic[i][j]) { + res.add(Arrays.asList(i, j)); + } + } } - } + return res; } - return res; - } - - private void dfs(int[][] heights, int i, int j, int prev, boolean[][] ocean) { - if (i < 0 || i >= ocean.length || j < 0 || j >= ocean[0].length) return; - if (heights[i][j] < prev || ocean[i][j]) return; - ocean[i][j] = true; - for (int[] d : dir) { - dfs(heights, i + d[0], j + d[1], heights[i][j], ocean); + private void dfs( + int[][] heights, + int i, + int j, + int prev, + boolean[][] ocean + ) { + if (i < 0 || i >= ocean.length || j < 0 || j >= ocean[0].length) return; + if (heights[i][j] < prev || ocean[i][j]) return; + + ocean[i][j] = true; + for (int[] d : dir) { + dfs(heights, i + d[0], j + d[1], heights[i][j], ocean); + } } - } } diff --git a/java/42-Trapping-Rain-Water.java b/java/42-Trapping-Rain-Water.java index d010a34a5..443a34897 100644 --- a/java/42-Trapping-Rain-Water.java +++ b/java/42-Trapping-Rain-Water.java @@ -1,23 +1,23 @@ class Solution { - public int trap(int[] heights) { - int left[] = new int[heights.length], right[] = new int[heights.length], max = - heights[0], c = 0; + public int trap(int[] heights) { + int left[] = new int[heights.length], right[] = new int[heights.length], max = + heights[0], c = 0; - for (int i = 0; i < heights.length; i++) { - left[i] = Math.max(heights[i], max); - max = left[i]; - } + for (int i = 0; i < heights.length; i++) { + left[i] = Math.max(heights[i], max); + max = left[i]; + } - max = heights[heights.length - 1]; - for (int i = heights.length - 1; i >= 0; i--) { - right[i] = Math.max(heights[i], max); - max = right[i]; - } - System.out.println(Arrays.toString(right)); - for (int i = 0; i < heights.length; i++) { - c = c + Math.min(left[i], right[i]) - heights[i]; + max = heights[heights.length - 1]; + for (int i = heights.length - 1; i >= 0; i--) { + right[i] = Math.max(heights[i], max); + max = right[i]; + } + System.out.println(Arrays.toString(right)); + for (int i = 0; i < heights.length; i++) { + c = c + Math.min(left[i], right[i]) - heights[i]; + } + return c; } - return c; - } } diff --git a/java/424-Longest-Repeating-Character-Replacement.java b/java/424-Longest-Repeating-Character-Replacement.java index 667f4f21e..1ce9988b4 100644 --- a/java/424-Longest-Repeating-Character-Replacement.java +++ b/java/424-Longest-Repeating-Character-Replacement.java @@ -1,19 +1,19 @@ class Solution { - public int characterReplacement(String s, int k) { - int[] arr = new int[26]; - int ans = 0; - int max = 0; - int i = 0; - for (int j = 0; j < s.length(); j++) { - arr[s.charAt(j) - 'A']++; - max = Math.max(max, arr[s.charAt(j) - 'A']); - if (j - i + 1 - max > k) { - arr[s.charAt(i) - 'A']--; - i++; - } - ans = Math.max(ans, j - i + 1); + public int characterReplacement(String s, int k) { + int[] arr = new int[26]; + int ans = 0; + int max = 0; + int i = 0; + for (int j = 0; j < s.length(); j++) { + arr[s.charAt(j) - 'A']++; + max = Math.max(max, arr[s.charAt(j) - 'A']); + if (j - i + 1 - max > k) { + arr[s.charAt(i) - 'A']--; + i++; + } + ans = Math.max(ans, j - i + 1); + } + return ans; } - return ans; - } } diff --git a/java/435-Non-Overlapping-Intervals.java b/java/435-Non-Overlapping-Intervals.java index dc329e05f..a189ba0a0 100644 --- a/java/435-Non-Overlapping-Intervals.java +++ b/java/435-Non-Overlapping-Intervals.java @@ -1,32 +1,35 @@ public class Solution { - public int eraseOverlapIntervals(int[][] intervals) { - int intervalsRemoved = 0; + public int eraseOverlapIntervals(int[][] intervals) { + int intervalsRemoved = 0; - Arrays.sort(intervals, (arr1, arr2) -> Integer.compare(arr1[0], arr2[0])); + Arrays.sort( + intervals, + (arr1, arr2) -> Integer.compare(arr1[0], arr2[0]) + ); - int[] intervalFirst = intervals[0]; + int[] intervalFirst = intervals[0]; - for (int i = 1; i < intervals.length; i++) { - if (firstIntervalwithinSecond(intervalFirst, intervals[i])) { - //mark first interval to be removed - intervalsRemoved++; - // determine which interval to remove - //remove the interval that ends last - if (intervalFirst[1] > intervals[i][1]) { - intervalFirst = intervals[i]; + for (int i = 1; i < intervals.length; i++) { + if (firstIntervalwithinSecond(intervalFirst, intervals[i])) { + //mark first interval to be removed + intervalsRemoved++; + // determine which interval to remove + //remove the interval that ends last + if (intervalFirst[1] > intervals[i][1]) { + intervalFirst = intervals[i]; + } + } else { + intervalFirst = intervals[i]; + } } - } else { - intervalFirst = intervals[i]; - } + return intervalsRemoved; } - return intervalsRemoved; - } - public boolean firstIntervalwithinSecond( - int[] intervalFirst, - int[] intervalSecond - ) { - return intervalSecond[0] < intervalFirst[1]; - } + public boolean firstIntervalwithinSecond( + int[] intervalFirst, + int[] intervalSecond + ) { + return intervalSecond[0] < intervalFirst[1]; + } } diff --git a/java/448-Find-All-Numbers-Disappeared-in-an-Array.java b/java/448-Find-All-Numbers-Disappeared-in-an-Array.java index 898641f68..536a95b6c 100644 --- a/java/448-Find-All-Numbers-Disappeared-in-an-Array.java +++ b/java/448-Find-All-Numbers-Disappeared-in-an-Array.java @@ -1,20 +1,20 @@ // Since the array has values form 0 to n we can use in-place sorting that's O(N) time and constant space. class Solution { - public List findDisappearedNumbers(int[] nums) { - List list = new ArrayList<>(); - for (int i = 0; i < nums.length; i++) { - int correct = nums[i] - 1; - if (nums[i] != nums[correct] && nums[correct] != nums[i]) { - int temp = nums[i]; - nums[i] = nums[correct]; - nums[correct] = temp; - i--; - } + public List findDisappearedNumbers(int[] nums) { + List list = new ArrayList<>(); + for (int i = 0; i < nums.length; i++) { + int correct = nums[i] - 1; + if (nums[i] != nums[correct] && nums[correct] != nums[i]) { + int temp = nums[i]; + nums[i] = nums[correct]; + nums[correct] = temp; + i--; + } + } + for (int i = 0; i < nums.length; i++) { + if (nums[i] - 1 != i) list.add(i + 1); + } + return list; } - for (int i = 0; i < nums.length; i++) { - if (nums[i] - 1 != i) list.add(i + 1); - } - return list; - } } diff --git a/java/45-Jump-game-II.java b/java/45-Jump-game-II.java index 9c4836e9a..664dfbe7d 100644 --- a/java/45-Jump-game-II.java +++ b/java/45-Jump-game-II.java @@ -1,15 +1,15 @@ class Solution { - public int jump(int[] nums) { - int res = 0, r = 0, l = 0, fur = 0; + public int jump(int[] nums) { + int res = 0, r = 0, l = 0, fur = 0; - while (r < nums.length - 1) { - fur = 0; - for (int i = l; i <= r; i++) fur = Math.max(fur, i + nums[i]); - l = r + 1; - r = fur; - res++; + while (r < nums.length - 1) { + fur = 0; + for (int i = l; i <= r; i++) fur = Math.max(fur, i + nums[i]); + l = r + 1; + r = fur; + res++; + } + return res; } - return res; - } } diff --git a/java/46-Permutations.java b/java/46-Permutations.java index ae502da20..0e5d5e79f 100644 --- a/java/46-Permutations.java +++ b/java/46-Permutations.java @@ -3,30 +3,30 @@ class Solution { - public List> permute(int[] nums) { - List> ans = new ArrayList<>(); - function(ans, nums, 0); - return ans; - } - - public void function(List> ans, int[] arr, int start) { - if (start == arr.length) { - List list = new ArrayList(); - for (int i = 0; i < arr.length; i++) list.add(arr[i]); - ans.add(list); - return; + public List> permute(int[] nums) { + List> ans = new ArrayList<>(); + function(ans, nums, 0); + return ans; } - for (int i = start; i < arr.length; i++) { - swap(arr, start, i); - function(ans, arr, start + 1); - swap(arr, start, i); + public void function(List> ans, int[] arr, int start) { + if (start == arr.length) { + List list = new ArrayList(); + for (int i = 0; i < arr.length; i++) list.add(arr[i]); + ans.add(list); + return; + } + + for (int i = start; i < arr.length; i++) { + swap(arr, start, i); + function(ans, arr, start + 1); + swap(arr, start, i); + } } - } - public void swap(int[] arr, int a, int b) { - int temp = arr[a]; - arr[a] = arr[b]; - arr[b] = temp; - } + public void swap(int[] arr, int a, int b) { + int temp = arr[a]; + arr[a] = arr[b]; + arr[b] = temp; + } } diff --git a/java/48-Rotate-Image.java b/java/48-Rotate-Image.java index 1f9fe8d85..0d038f278 100644 --- a/java/48-Rotate-Image.java +++ b/java/48-Rotate-Image.java @@ -6,30 +6,30 @@ class Solution { - public void rotate(int[][] matrix) { - int N = matrix.length; + public void rotate(int[][] matrix) { + int N = matrix.length; - transpose(matrix, N); - reverse(matrix, N); - } + transpose(matrix, N); + reverse(matrix, N); + } - void transpose(int[][] matrix, int n) { - for (int i = 0; i < n; i++) { - for (int j = i + 1; j < n; j++) { - int temp = matrix[j][i]; - matrix[j][i] = matrix[i][j]; - matrix[i][j] = temp; - } + void transpose(int[][] matrix, int n) { + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + int temp = matrix[j][i]; + matrix[j][i] = matrix[i][j]; + matrix[i][j] = temp; + } + } } - } - void reverse(int[][] matrix, int n) { - for (int i = 0; i < n; i++) { - for (int j = 0; j < n / 2; j++) { - int temp = matrix[i][j]; - matrix[i][j] = matrix[i][n - 1 - j]; - matrix[i][n - 1 - j] = temp; - } + void reverse(int[][] matrix, int n) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n / 2; j++) { + int temp = matrix[i][j]; + matrix[i][j] = matrix[i][n - 1 - j]; + matrix[i][n - 1 - j] = temp; + } + } } - } } diff --git a/java/49-Group-Anagrams.java b/java/49-Group-Anagrams.java index 1ab4a6a89..b8cf68b1f 100644 --- a/java/49-Group-Anagrams.java +++ b/java/49-Group-Anagrams.java @@ -1,19 +1,19 @@ class Solution { - public List> groupAnagrams(String[] strs) { - List> res = new ArrayList<>(); - if (strs.length == 0) return res; - HashMap> map = new HashMap<>(); - for (String s : strs) { - char[] hash = new char[26]; - for (char c : s.toCharArray()) { - hash[c - 'a']++; - } - String key = new String(hash); - map.computeIfAbsent(key, k -> new ArrayList<>()); - map.get(key).add(s); + public List> groupAnagrams(String[] strs) { + List> res = new ArrayList<>(); + if (strs.length == 0) return res; + HashMap> map = new HashMap<>(); + for (String s : strs) { + char[] hash = new char[26]; + for (char c : s.toCharArray()) { + hash[c - 'a']++; + } + String key = new String(hash); + map.computeIfAbsent(key, k -> new ArrayList<>()); + map.get(key).add(s); + } + res.addAll(map.values()); + return res; } - res.addAll(map.values()); - return res; - } } diff --git a/java/494-Target-Sum.java b/java/494-Target-Sum.java index 64598742a..775e7c547 100644 --- a/java/494-Target-Sum.java +++ b/java/494-Target-Sum.java @@ -2,18 +2,18 @@ class Solution { - public int findTargetSumWays(int[] nums, int target) { - return helper(nums, target, nums.length, 0); - } + public int findTargetSumWays(int[] nums, int target) { + return helper(nums, target, nums.length, 0); + } - public int helper(int[] nums, int target, int n, int temp) { - if (n == 0) { - if (target == temp) return 1; else return 0; - } else { - return ( - helper(nums, target - nums[n - 1], n - 1, temp) + - helper(nums, target + nums[n - 1], n - 1, temp) - ); + public int helper(int[] nums, int target, int n, int temp) { + if (n == 0) { + if (target == temp) return 1; else return 0; + } else { + return ( + helper(nums, target - nums[n - 1], n - 1, temp) + + helper(nums, target + nums[n - 1], n - 1, temp) + ); + } } - } } diff --git a/java/5-Longest-Palindromic-Substring.java b/java/5-Longest-Palindromic-Substring.java index 770892a52..7ddbbbace 100644 --- a/java/5-Longest-Palindromic-Substring.java +++ b/java/5-Longest-Palindromic-Substring.java @@ -1,40 +1,40 @@ class Solution { - public String longestPalindrome(String s) { - int strLength = s.length(); + public String longestPalindrome(String s) { + int strLength = s.length(); - if (strLength < 2) { - return s; - } + if (strLength < 2) { + return s; + } - int resultLength = 0; - String result = ""; + int resultLength = 0; + String result = ""; - for (int i = 0; i < s.length(); i++) { - //Odd length - int l = i, r = i; - while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { - if ((r - l + 1) > resultLength) { - result = s.substring(l, r + 1); - resultLength = r - l + 1; - } - l -= 1; - r += 1; - } + for (int i = 0; i < s.length(); i++) { + //Odd length + int l = i, r = i; + while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { + if ((r - l + 1) > resultLength) { + result = s.substring(l, r + 1); + resultLength = r - l + 1; + } + l -= 1; + r += 1; + } - // even length - l = i; - r = i + 1; - while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { - if ((r - l + 1) > resultLength) { - result = s.substring(l, r + 1); - resultLength = r - l + 1; + // even length + l = i; + r = i + 1; + while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { + if ((r - l + 1) > resultLength) { + result = s.substring(l, r + 1); + resultLength = r - l + 1; + } + l -= 1; + r += 1; + } } - l -= 1; - r += 1; - } - } - return result; - } + return result; + } } diff --git a/java/50-Pow(x, n).java b/java/50-Pow(x, n).java index 6b68586e2..987dfaf60 100644 --- a/java/50-Pow(x, n).java +++ b/java/50-Pow(x, n).java @@ -4,28 +4,28 @@ //Asked in Amazon, Meta, Google, Linkedin, Bloomberg class Solution { - public double myPow(double x, int n) { - if (n == 0) { - return 1; + public double myPow(double x, int n) { + if (n == 0) { + return 1; + } + //Make the negative values positive + else if (n < 0) { + //whenever even just divide it by 2 + //this will also include Integer.MIN_VALUE + //We're doing this because if I do -N and N=Integer.MIN_VALUE it'll become a value which is greater than the max value of Integer.MAX_VALUE + if (n % 2 == 0) { + n = n / 2; + n = -n; + x = (1 / x) * (1 / x); + } else { //Odds don't need to be divided as their negative is in the positive limit + n = -n; + x = 1 / x; + } + } + if (n % 2 == 0) { //even + return myPow(x * x, n / 2); + } else { //odd + return x * myPow(x * x, n / 2); + } } - //Make the negative values positive - else if (n < 0) { - //whenever even just divide it by 2 - //this will also include Integer.MIN_VALUE - //We're doing this because if I do -N and N=Integer.MIN_VALUE it'll become a value which is greater than the max value of Integer.MAX_VALUE - if (n % 2 == 0) { - n = n / 2; - n = -n; - x = (1 / x) * (1 / x); - } else { //Odds don't need to be divided as their negative is in the positive limit - n = -n; - x = 1 / x; - } - } - if (n % 2 == 0) { //even - return myPow(x * x, n / 2); - } else { //odd - return x * myPow(x * x, n / 2); - } - } } diff --git a/java/51-N-Queens.java b/java/51-N-Queens.java index 8ee86a023..a2f07dfd0 100644 --- a/java/51-N-Queens.java +++ b/java/51-N-Queens.java @@ -1,57 +1,57 @@ class Solution { - public List> solveNQueens(int n) { - List> ans = new ArrayList>(); - boolean[][] board = new boolean[n][n]; - queens(board, 0, ans); - return ans; - } - - public void queens(boolean[][] board, int row, List> ans2) { - //base case - if (row == board.length) { - ArrayList ans = new ArrayList(); - createAnswer(board, ans); - ans2.add(ans); - return; - } - for (int col = 0; col < board.length; col++) { - if (isSafe(board, row, col)) { - board[row][col] = true; - queens(board, row + 1, ans2); - board[row][col] = false; - } + public List> solveNQueens(int n) { + List> ans = new ArrayList>(); + boolean[][] board = new boolean[n][n]; + queens(board, 0, ans); + return ans; } - } - public void createAnswer(boolean[][] board, ArrayList ans) { - for (int i = 0; i < board.length; i++) { - StringBuilder str = new StringBuilder(); - for (int j = 0; j < board[0].length; j++) { - if (board[i][j]) { - str.append("Q"); - } else str.append("."); - } - ans.add(str.toString()); + public void queens(boolean[][] board, int row, List> ans2) { + //base case + if (row == board.length) { + ArrayList ans = new ArrayList(); + createAnswer(board, ans); + ans2.add(ans); + return; + } + for (int col = 0; col < board.length; col++) { + if (isSafe(board, row, col)) { + board[row][col] = true; + queens(board, row + 1, ans2); + board[row][col] = false; + } + } } - } - public boolean isSafe(boolean[][] board, int row, int col) { - for (int i = 0; i < row; i++) { - if (board[i][col]) { - return false; - } + public void createAnswer(boolean[][] board, ArrayList ans) { + for (int i = 0; i < board.length; i++) { + StringBuilder str = new StringBuilder(); + for (int j = 0; j < board[0].length; j++) { + if (board[i][j]) { + str.append("Q"); + } else str.append("."); + } + ans.add(str.toString()); + } } - int maxLeft = Math.min(row, col); - for (int i = 1; i <= maxLeft; i++) { - if (board[row - i][col - i]) { - return false; - } - } - int maxRight = Math.min(row, board.length - 1 - col); - for (int i = 1; i <= maxRight; i++) { - if (board[row - i][col + i]) return false; + + public boolean isSafe(boolean[][] board, int row, int col) { + for (int i = 0; i < row; i++) { + if (board[i][col]) { + return false; + } + } + int maxLeft = Math.min(row, col); + for (int i = 1; i <= maxLeft; i++) { + if (board[row - i][col - i]) { + return false; + } + } + int maxRight = Math.min(row, board.length - 1 - col); + for (int i = 1; i <= maxRight; i++) { + if (board[row - i][col + i]) return false; + } + return true; } - return true; - } } diff --git a/java/53-Maximum-Subarray.java b/java/53-Maximum-Subarray.java index bacae6905..e9d27b8cc 100644 --- a/java/53-Maximum-Subarray.java +++ b/java/53-Maximum-Subarray.java @@ -1,19 +1,19 @@ class Solution { - public int maxSubArray(int[] nums) { - if (nums.length == 1) return nums[0]; + public int maxSubArray(int[] nums) { + if (nums.length == 1) return nums[0]; - int sum = 0; - int max = Integer.MIN_VALUE; + int sum = 0; + int max = Integer.MIN_VALUE; - for (int n : nums) { - sum += n; - max = Math.max(max, sum); + for (int n : nums) { + sum += n; + max = Math.max(max, sum); - if (sum < 0) { - sum = 0; - } + if (sum < 0) { + sum = 0; + } + } + return max; } - return max; - } } diff --git a/java/54-Spiral-Matrix.java b/java/54-Spiral-Matrix.java index 26c42b8ba..6497eb804 100644 --- a/java/54-Spiral-Matrix.java +++ b/java/54-Spiral-Matrix.java @@ -1,38 +1,38 @@ class Solution { - public List spiralOrder(int[][] matrix) { - List list = new ArrayList<>(); - int rb = 0; - int re = matrix.length - 1; - int cb = 0; - int ce = matrix[0].length - 1; + public List spiralOrder(int[][] matrix) { + List list = new ArrayList<>(); + int rb = 0; + int re = matrix.length - 1; + int cb = 0; + int ce = matrix[0].length - 1; - while (rb <= re && cb <= ce) { - for (int j = cb; j <= ce; j++) { - list.add(matrix[rb][j]); - } - rb++; + while (rb <= re && cb <= ce) { + for (int j = cb; j <= ce; j++) { + list.add(matrix[rb][j]); + } + rb++; - for (int i = rb; i <= re; i++) { - list.add(matrix[i][ce]); - } - ce--; + for (int i = rb; i <= re; i++) { + list.add(matrix[i][ce]); + } + ce--; - if (rb <= re) { - for (int j = ce; j >= cb; j--) { - list.add(matrix[re][j]); - } - } - re--; + if (rb <= re) { + for (int j = ce; j >= cb; j--) { + list.add(matrix[re][j]); + } + } + re--; - if (cb <= ce) { - for (int i = re; i >= rb; i--) { - list.add(matrix[i][cb]); + if (cb <= ce) { + for (int i = re; i >= rb; i--) { + list.add(matrix[i][cb]); + } + } + cb++; } - } - cb++; - } - return list; - } + return list; + } } diff --git a/java/543-Diameter-of-Binary-Tree.java b/java/543-Diameter-of-Binary-Tree.java index ecf2df0eb..007071e61 100644 --- a/java/543-Diameter-of-Binary-Tree.java +++ b/java/543-Diameter-of-Binary-Tree.java @@ -1,19 +1,19 @@ class Solution { - int result = -1; + int result = -1; - public int diameterOfBinaryTree(TreeNode root) { - dfs(root); - return result; - } + public int diameterOfBinaryTree(TreeNode root) { + dfs(root); + return result; + } - private int dfs(TreeNode current) { - if (current == null) { - return -1; + private int dfs(TreeNode current) { + if (current == null) { + return -1; + } + int left = 1 + dfs(current.left); + int right = 1 + dfs(current.right); + result = Math.max(result, (left + right)); + return Math.max(left, right); } - int left = 1 + dfs(current.left); - int right = 1 + dfs(current.right); - result = Math.max(result, (left + right)); - return Math.max(left, right); - } } diff --git a/java/55-Jump-Game.java b/java/55-Jump-Game.java index 5b0c88d7b..f19449bf4 100644 --- a/java/55-Jump-Game.java +++ b/java/55-Jump-Game.java @@ -1,12 +1,12 @@ class Solution { - public boolean canJump(int[] nums) { - int goal = nums.length - 1; - for (int i = nums.length - 2; i >= 0; i--) { - if (nums[i] + i >= goal) { - goal = i; - } + public boolean canJump(int[] nums) { + int goal = nums.length - 1; + for (int i = nums.length - 2; i >= 0; i--) { + if (nums[i] + i >= goal) { + goal = i; + } + } + return goal == 0; } - return goal == 0; - } } diff --git a/java/56-Merge-Intervals.java b/java/56-Merge-Intervals.java index 1f97c0197..e811fdb6d 100644 --- a/java/56-Merge-Intervals.java +++ b/java/56-Merge-Intervals.java @@ -1,23 +1,23 @@ class Solution { - public int[][] merge(int[][] intervals) { - ArrayList ans = new ArrayList<>(); - Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); - ans.add(intervals[0]); - for (int i = 1; i < intervals.length; i++) { - int prevStart = ans.get(ans.size() - 1)[0]; - //comparing the values of prevEnd and curEnd - int curStart = intervals[i][0]; - if (curStart <= ans.get(ans.size() - 1)[1]) { - //do the merging - ans.get(ans.size() - 1)[1] = - Math.max(ans.get(ans.size() - 1)[1], intervals[i][1]); - } else { - ans.add(intervals[i]); - } + public int[][] merge(int[][] intervals) { + ArrayList ans = new ArrayList<>(); + Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); + ans.add(intervals[0]); + for (int i = 1; i < intervals.length; i++) { + int prevStart = ans.get(ans.size() - 1)[0]; + //comparing the values of prevEnd and curEnd + int curStart = intervals[i][0]; + if (curStart <= ans.get(ans.size() - 1)[1]) { + //do the merging + ans.get(ans.size() - 1)[1] = + Math.max(ans.get(ans.size() - 1)[1], intervals[i][1]); + } else { + ans.add(intervals[i]); + } + } + int[][] res = new int[ans.size()][2]; + ans.toArray(res); + return res; } - int[][] res = new int[ans.size()][2]; - ans.toArray(res); - return res; - } } diff --git a/java/567-Permutation-in-String.java b/java/567-Permutation-in-String.java index 89a88a9fd..dfa08f917 100644 --- a/java/567-Permutation-in-String.java +++ b/java/567-Permutation-in-String.java @@ -1,34 +1,34 @@ class Solution { - public boolean checkInclusion(String s1, String s2) { - if (s2.length() < s1.length()) return false; - int[] arr = new int[26]; - //add the values to the hash array - for (int i = 0; i < s1.length(); i++) { - arr[s1.charAt(i) - 'a']++; + public boolean checkInclusion(String s1, String s2) { + if (s2.length() < s1.length()) return false; + int[] arr = new int[26]; + //add the values to the hash array + for (int i = 0; i < s1.length(); i++) { + arr[s1.charAt(i) - 'a']++; + } + int i = 0; + int j = 0; + //point j to it's position + for (; j < s1.length(); j++) { + arr[s2.charAt(j) - 'a']--; + } + j--; + if (isEmpty(arr)) return true; + while (j < s2.length()) { + arr[s2.charAt(i) - 'a']++; + i++; + j++; + if (j < s2.length()) arr[s2.charAt(j) - 'a']--; + if (isEmpty(arr)) return true; + } + return isEmpty(arr); } - int i = 0; - int j = 0; - //point j to it's position - for (; j < s1.length(); j++) { - arr[s2.charAt(j) - 'a']--; - } - j--; - if (isEmpty(arr)) return true; - while (j < s2.length()) { - arr[s2.charAt(i) - 'a']++; - i++; - j++; - if (j < s2.length()) arr[s2.charAt(j) - 'a']--; - if (isEmpty(arr)) return true; - } - return isEmpty(arr); - } - public boolean isEmpty(int[] arr) { - for (int i = 0; i < arr.length; i++) { - if (arr[i] != 0) return false; + public boolean isEmpty(int[] arr) { + for (int i = 0; i < arr.length; i++) { + if (arr[i] != 0) return false; + } + return true; } - return true; - } } diff --git a/java/57-Insert-Interval.java b/java/57-Insert-Interval.java index 16c84ca9f..1920b3e2e 100644 --- a/java/57-Insert-Interval.java +++ b/java/57-Insert-Interval.java @@ -1,20 +1,20 @@ class Solution { - public int[][] insert(int[][] intervals, int[] newInterval) { - List res = new ArrayList<>(); - for (int[] interval : intervals) { - if (newInterval == null || interval[1] < newInterval[0]) res.add( - interval - ); else if (interval[0] > newInterval[1]) { - res.add(newInterval); - res.add(interval); - newInterval = null; - } else { - newInterval[0] = Math.min(interval[0], newInterval[0]); - newInterval[1] = Math.max(interval[1], newInterval[1]); - } + public int[][] insert(int[][] intervals, int[] newInterval) { + List res = new ArrayList<>(); + for (int[] interval : intervals) { + if (newInterval == null || interval[1] < newInterval[0]) res.add( + interval + ); else if (interval[0] > newInterval[1]) { + res.add(newInterval); + res.add(interval); + newInterval = null; + } else { + newInterval[0] = Math.min(interval[0], newInterval[0]); + newInterval[1] = Math.max(interval[1], newInterval[1]); + } + } + if (newInterval != null) res.add(newInterval); + return res.toArray(new int[res.size()][]); } - if (newInterval != null) res.add(newInterval); - return res.toArray(new int[res.size()][]); - } } diff --git a/java/572-Subtree-of-Another-Tree.java b/java/572-Subtree-of-Another-Tree.java index a7ac1e08b..6b5604665 100644 --- a/java/572-Subtree-of-Another-Tree.java +++ b/java/572-Subtree-of-Another-Tree.java @@ -1,15 +1,17 @@ class Solution { - public boolean isSubtree(TreeNode root, TreeNode subRoot) { - if (root == null && subRoot == null) return true; - if (root == null || subRoot == null) return false; - if (root.val == subRoot.val) { - return ( - isSubtree(root.left, subRoot.left) && - isSubtree(root.right, subRoot.right) - ); - } else { - return (isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot)); + public boolean isSubtree(TreeNode root, TreeNode subRoot) { + if (root == null && subRoot == null) return true; + if (root == null || subRoot == null) return false; + if (root.val == subRoot.val) { + return ( + isSubtree(root.left, subRoot.left) && + isSubtree(root.right, subRoot.right) + ); + } else { + return ( + isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot) + ); + } } - } } diff --git a/java/6-Zigzag-Conversion.java b/java/6-Zigzag-Conversion.java index 7e7c72314..f8c3368f8 100644 --- a/java/6-Zigzag-Conversion.java +++ b/java/6-Zigzag-Conversion.java @@ -2,31 +2,31 @@ class Solution { - public String convert(String s, int row) { - if (row == 1) return s; - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < row; i++) { - int j = i; - if (i == 0 || i == row - 1) { - while (j < s.length()) { - sb.append(s.charAt(j)); - j += 2 * (row - 1); + public String convert(String s, int row) { + if (row == 1) return s; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < row; i++) { + int j = i; + if (i == 0 || i == row - 1) { + while (j < s.length()) { + sb.append(s.charAt(j)); + j += 2 * (row - 1); + } + } else { + boolean diagonal = false; + while (j < s.length()) { + if (!diagonal) { + sb.append(s.charAt(j)); + j += 2 * (row - i - 1); + diagonal = true; + } else { + sb.append(s.charAt(j)); + j += 2 * i; + diagonal = false; + } + } + } } - } else { - boolean diagonal = false; - while (j < s.length()) { - if (!diagonal) { - sb.append(s.charAt(j)); - j += 2 * (row - i - 1); - diagonal = true; - } else { - sb.append(s.charAt(j)); - j += 2 * i; - diagonal = false; - } - } - } + return sb.toString(); } - return sb.toString(); - } } diff --git a/java/60-Permutation-Sequence.java b/java/60-Permutation-Sequence.java index 81cc7f5c9..daf664f7a 100644 --- a/java/60-Permutation-Sequence.java +++ b/java/60-Permutation-Sequence.java @@ -3,80 +3,80 @@ class Solution { - //Time complexity O(N^2) becuase of remove method - public String getPermutation(int n, int k) { - StringBuilder kthPerm = new StringBuilder(); - int fact = 1; - //this list will contain all the values from 1 to n for reference - ArrayList list = new ArrayList<>(); - for (int i = 1; i < n; i++) { - fact = fact * i; - list.add(i); + //Time complexity O(N^2) becuase of remove method + public String getPermutation(int n, int k) { + StringBuilder kthPerm = new StringBuilder(); + int fact = 1; + //this list will contain all the values from 1 to n for reference + ArrayList list = new ArrayList<>(); + for (int i = 1; i < n; i++) { + fact = fact * i; + list.add(i); + } + list.add(n); + k--; + while (true) { + kthPerm.append(list.get(k / fact)); + list.remove(k / fact); + if (list.size() == 0) break; + k = k % fact; + fact = fact / (list.size()); + } + return kthPerm.toString(); } - list.add(n); - k--; - while (true) { - kthPerm.append(list.get(k / fact)); - list.remove(k / fact); - if (list.size() == 0) break; - k = k % fact; - fact = fact / (list.size()); - } - return kthPerm.toString(); - } - { - //Bruteforce solution (gives TLE) similar to Next Permutation problem no.31 + { + //Bruteforce solution (gives TLE) similar to Next Permutation problem no.31 - // public String getPermutation(int n, int k) { - // int[] num = new int[n]; - // for (int i = 1; i<=n; i++) { - // num[i-1] = i; - // } - // for (int i = 1; i0 && nums[pivot]0 && nums[j]0 && nums[pivot]0 && nums[j]= 0; i--) { - for (int j = n - 2; j >= 0; j--) { - dp[i][j] = dp[i][j + 1] + dp[i + 1][j]; - } + for (int i = m - 2; i >= 0; i--) { + for (int j = n - 2; j >= 0; j--) { + dp[i][j] = dp[i][j + 1] + dp[i + 1][j]; + } + } + return dp[0][0]; } - return dp[0][0]; - } } diff --git a/java/621-Task-Scheduler.java b/java/621-Task-Scheduler.java index fa6f074eb..d0afa0caa 100644 --- a/java/621-Task-Scheduler.java +++ b/java/621-Task-Scheduler.java @@ -1,26 +1,26 @@ class Solution { - public int leastInterval(char[] tasks, int n) { - if (n == 0) return tasks.length; - PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); - Queue> q = new LinkedList<>(); - int[] arr = new int[26]; - for (char c : tasks) arr[c - 'A']++; - for (int val : arr) if (val > 0) pq.add(val); - int time = 0; - // System.out.println(pq); - // System.out.println(q); - while ((!pq.isEmpty() || !q.isEmpty())) { - if (pq.isEmpty()) { - time = Math.max(q.peek().getValue(), time); - pq.add(q.poll().getKey()); - } - int val = pq.poll(); - val--; - time++; - if (val > 0) q.add(new Pair(val, time + n)); - // System.out.println(q + " "+ time); + public int leastInterval(char[] tasks, int n) { + if (n == 0) return tasks.length; + PriorityQueue pq = new PriorityQueue<>((a, b) -> b - a); + Queue> q = new LinkedList<>(); + int[] arr = new int[26]; + for (char c : tasks) arr[c - 'A']++; + for (int val : arr) if (val > 0) pq.add(val); + int time = 0; + // System.out.println(pq); + // System.out.println(q); + while ((!pq.isEmpty() || !q.isEmpty())) { + if (pq.isEmpty()) { + time = Math.max(q.peek().getValue(), time); + pq.add(q.poll().getKey()); + } + int val = pq.poll(); + val--; + time++; + if (val > 0) q.add(new Pair(val, time + n)); + // System.out.println(q + " "+ time); + } + return time; } - return time; - } } diff --git a/java/63-Unique-Paths-II.java b/java/63-Unique-Paths-II.java index 979640393..907fd7220 100644 --- a/java/63-Unique-Paths-II.java +++ b/java/63-Unique-Paths-II.java @@ -2,29 +2,29 @@ class Solution { - public int uniquePathsWithObstacles(int[][] grid) { - return dfs( - grid, - 0, - 0, - grid.length, - grid[0].length, - new int[grid.length][grid[0].length] - ); - } - - public int dfs(int[][] grid, int i, int j, int m, int n, int[][] dp) { - if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 1) { - return 0; + public int uniquePathsWithObstacles(int[][] grid) { + return dfs( + grid, + 0, + 0, + grid.length, + grid[0].length, + new int[grid.length][grid[0].length] + ); } - if (i == m - 1 && j == n - 1) { - dp[i][j] = 1; - return dp[i][j]; + + public int dfs(int[][] grid, int i, int j, int m, int n, int[][] dp) { + if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 1) { + return 0; + } + if (i == m - 1 && j == n - 1) { + dp[i][j] = 1; + return dp[i][j]; + } + if (dp[i][j] != 0) return dp[i][j]; + int right = dfs(grid, i, j + 1, m, n, dp); + int left = dfs(grid, i + 1, j, m, n, dp); + dp[i][j] = right + left; + return dp[i][j]; } - if (dp[i][j] != 0) return dp[i][j]; - int right = dfs(grid, i, j + 1, m, n, dp); - int left = dfs(grid, i + 1, j, m, n, dp); - dp[i][j] = right + left; - return dp[i][j]; - } } diff --git a/java/637-Average-of-Levels-in-Binary-Tree.java b/java/637-Average-of-Levels-in-Binary-Tree.java index 3554c8d5c..99da71eee 100644 --- a/java/637-Average-of-Levels-in-Binary-Tree.java +++ b/java/637-Average-of-Levels-in-Binary-Tree.java @@ -2,21 +2,21 @@ //Asked in Amazon and Meta class Solution { - public List averageOfLevels(TreeNode root) { - List ans = new ArrayList<>(); - Queue q = new LinkedList(); - q.offer(root); - while (!q.isEmpty()) { - int queue_size = q.size(); - double avg = 0; - for (int i = 0; i < queue_size; i++) { - TreeNode cur = q.poll(); - avg += cur.val; - if (cur.left != null) q.offer(cur.left); - if (cur.right != null) q.offer(cur.right); - } - ans.add(avg / queue_size); + public List averageOfLevels(TreeNode root) { + List ans = new ArrayList<>(); + Queue q = new LinkedList(); + q.offer(root); + while (!q.isEmpty()) { + int queue_size = q.size(); + double avg = 0; + for (int i = 0; i < queue_size; i++) { + TreeNode cur = q.poll(); + avg += cur.val; + if (cur.left != null) q.offer(cur.left); + if (cur.right != null) q.offer(cur.right); + } + ans.add(avg / queue_size); + } + return ans; } - return ans; - } } diff --git a/java/64-Minimum-Path-Sum.java b/java/64-Minimum-Path-Sum.java index 30020dad3..f98a6b92c 100644 --- a/java/64-Minimum-Path-Sum.java +++ b/java/64-Minimum-Path-Sum.java @@ -1,29 +1,29 @@ class Solution { - public int minPathSum(int[][] grid) { - int m = grid.length - 1; - int n = grid[0].length - 1; - int[][] dp = new int[m + 1][n + 1]; - for (int[] arr : dp) { - Arrays.fill(arr, -1); + public int minPathSum(int[][] grid) { + int m = grid.length - 1; + int n = grid[0].length - 1; + int[][] dp = new int[m + 1][n + 1]; + for (int[] arr : dp) { + Arrays.fill(arr, -1); + } + return helper(grid, m, n, dp); } - return helper(grid, m, n, dp); - } - public int helper(int[][] grid, int m, int n, int[][] dp) { - if (m == 0 && n == 0) return grid[0][0]; - if (m == 0) { - dp[m][n] = grid[m][n] + helper(grid, m, n - 1, dp); - return dp[m][n]; + public int helper(int[][] grid, int m, int n, int[][] dp) { + if (m == 0 && n == 0) return grid[0][0]; + if (m == 0) { + dp[m][n] = grid[m][n] + helper(grid, m, n - 1, dp); + return dp[m][n]; + } + if (n == 0) { + dp[m][n] = grid[m][n] + helper(grid, m - 1, n, dp); + return dp[m][n]; + } + if (dp[m][n] != -1) return dp[m][n]; + dp[m][n] = + grid[m][n] + + Math.min(helper(grid, m, n - 1, dp), helper(grid, m - 1, n, dp)); + return dp[m][n]; } - if (n == 0) { - dp[m][n] = grid[m][n] + helper(grid, m - 1, n, dp); - return dp[m][n]; - } - if (dp[m][n] != -1) return dp[m][n]; - dp[m][n] = - grid[m][n] + - Math.min(helper(grid, m, n - 1, dp), helper(grid, m - 1, n, dp)); - return dp[m][n]; - } } diff --git a/java/647-Palindromic-Substrings.java b/java/647-Palindromic-Substrings.java index 943eb2600..e05bc1ef3 100644 --- a/java/647-Palindromic-Substrings.java +++ b/java/647-Palindromic-Substrings.java @@ -1,31 +1,35 @@ class Solution { - public int countSubstrings(String s) { - if (s.length() < 2) { - return s.length(); + public int countSubstrings(String s) { + if (s.length() < 2) { + return s.length(); + } + int result = 0; + for (int i = 0; i < s.length(); i++) { + // Odd Length + int left = i, right = i; + while ( + left >= 0 && + right < s.length() && + s.charAt(left) == s.charAt(right) + ) { + result++; + left--; + right++; + } + // Even Length + left = i; + right = i + 1; + while ( + left >= 0 && + right < s.length() && + s.charAt(left) == s.charAt(right) + ) { + result++; + left--; + right++; + } + } + return result; } - int result = 0; - for (int i = 0; i < s.length(); i++) { - // Odd Length - int left = i, right = i; - while ( - left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right) - ) { - result++; - left--; - right++; - } - // Even Length - left = i; - right = i + 1; - while ( - left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right) - ) { - result++; - left--; - right++; - } - } - return result; - } } diff --git a/java/66-Plus-One.java b/java/66-Plus-One.java index a7eca484b..7170b6f2c 100644 --- a/java/66-Plus-One.java +++ b/java/66-Plus-One.java @@ -1,29 +1,29 @@ class Solution { - public int[] plusOne(int[] digits) { - final int len = digits.length; - int[] newDigits = new int[len + 1]; - int carry = 1; - int currSum = 0; - for (int i = len - 1; i >= 0; i--) { - currSum = digits[i] + carry; - if (currSum > 9) { - digits[i] = currSum % 10; - newDigits[i + 1] = digits[i]; - carry = 1; - } else { - digits[i] = currSum; - newDigits[i + 1] = digits[i]; - carry = 0; - break; - } - } + public int[] plusOne(int[] digits) { + final int len = digits.length; + int[] newDigits = new int[len + 1]; + int carry = 1; + int currSum = 0; + for (int i = len - 1; i >= 0; i--) { + currSum = digits[i] + carry; + if (currSum > 9) { + digits[i] = currSum % 10; + newDigits[i + 1] = digits[i]; + carry = 1; + } else { + digits[i] = currSum; + newDigits[i + 1] = digits[i]; + carry = 0; + break; + } + } - if (carry == 1) { - newDigits[0] = 1; - return newDigits; - } + if (carry == 1) { + newDigits[0] = 1; + return newDigits; + } - return digits; - } + return digits; + } } diff --git a/java/662-Maximum-Width-of-Binary-Tree.java b/java/662-Maximum-Width-of-Binary-Tree.java index 92fcd377b..933767a2b 100644 --- a/java/662-Maximum-Width-of-Binary-Tree.java +++ b/java/662-Maximum-Width-of-Binary-Tree.java @@ -3,22 +3,22 @@ class Solution { - public int widthOfBinaryTree(TreeNode root) { - Queue> q = new LinkedList<>(); - int maxWidth = 0; - q.offer(new Pair(root, 1)); - while (!q.isEmpty()) { - int l = q.peek().getValue(); - int r = l; - int size = q.size(); - for (int i = 0; i < size; i++) { - TreeNode cur = q.peek().getKey(); - r = q.poll().getValue(); - if (cur.left != null) q.offer(new Pair(cur.left, 2 * r)); - if (cur.right != null) q.offer(new Pair(cur.right, 2 * r + 1)); - } - maxWidth = Math.max(maxWidth, r - l + 1); + public int widthOfBinaryTree(TreeNode root) { + Queue> q = new LinkedList<>(); + int maxWidth = 0; + q.offer(new Pair(root, 1)); + while (!q.isEmpty()) { + int l = q.peek().getValue(); + int r = l; + int size = q.size(); + for (int i = 0; i < size; i++) { + TreeNode cur = q.peek().getKey(); + r = q.poll().getValue(); + if (cur.left != null) q.offer(new Pair(cur.left, 2 * r)); + if (cur.right != null) q.offer(new Pair(cur.right, 2 * r + 1)); + } + maxWidth = Math.max(maxWidth, r - l + 1); + } + return maxWidth; } - return maxWidth; - } } diff --git a/java/695-Max-Area-of-Island.java b/java/695-Max-Area-of-Island.java index f7ffa6d30..c0c9c3aab 100644 --- a/java/695-Max-Area-of-Island.java +++ b/java/695-Max-Area-of-Island.java @@ -1,26 +1,28 @@ class Solution { - public int maxAreaOfIsland(int[][] grid) { - int ans = 0; - int m = grid.length; - int n = grid[0].length; - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (grid[i][j] == 1) ans = - Math.max(dfs(grid, i, j, m, n, new int[] { 0 }), ans); - } + public int maxAreaOfIsland(int[][] grid) { + int ans = 0; + int m = grid.length; + int n = grid[0].length; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) ans = + Math.max(dfs(grid, i, j, m, n, new int[] { 0 }), ans); + } + } + return ans; } - return ans; - } - public int dfs(int[][] grid, int i, int j, int m, int n, int[] count) { - if (i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 0) return count[0]; - count[0]++; - grid[i][j] = 0; - dfs(grid, i - 1, j, m, n, count); - dfs(grid, i + 1, j, m, n, count); - dfs(grid, i, j - 1, m, n, count); - dfs(grid, i, j + 1, m, n, count); - return count[0]; - } + public int dfs(int[][] grid, int i, int j, int m, int n, int[] count) { + if ( + i < 0 || j < 0 || i >= m || j >= n || grid[i][j] == 0 + ) return count[0]; + count[0]++; + grid[i][j] = 0; + dfs(grid, i - 1, j, m, n, count); + dfs(grid, i + 1, j, m, n, count); + dfs(grid, i, j - 1, m, n, count); + dfs(grid, i, j + 1, m, n, count); + return count[0]; + } } diff --git a/java/7-Reverse-Integer.java b/java/7-Reverse-Integer.java index 6f9da3d75..d891cb18b 100644 --- a/java/7-Reverse-Integer.java +++ b/java/7-Reverse-Integer.java @@ -1,21 +1,25 @@ class Solution { - public int reverse(int x) { - int min = Integer.MIN_VALUE; - int max = Integer.MAX_VALUE; + public int reverse(int x) { + int min = Integer.MIN_VALUE; + int max = Integer.MAX_VALUE; - int res = 0; - while (x != 0) { - int digit = x % 10; - x = x / 10; + int res = 0; + while (x != 0) { + int digit = x % 10; + x = x / 10; - if ((res > max / 10) || (res == max / 10 && digit >= max % 10)) return 0; + if ( + (res > max / 10) || (res == max / 10 && digit >= max % 10) + ) return 0; - if ((res < min / 10) || (res == min / 10 && digit <= min % 10)) return 0; + if ( + (res < min / 10) || (res == min / 10 && digit <= min % 10) + ) return 0; - res = (res * 10) + digit; - } + res = (res * 10) + digit; + } - return res; - } + return res; + } } diff --git a/java/70-Climbing-Stairs.java b/java/70-Climbing-Stairs.java index 592211859..4df6c202d 100644 --- a/java/70-Climbing-Stairs.java +++ b/java/70-Climbing-Stairs.java @@ -1,54 +1,54 @@ //optimal class Solution { - public int climbStairs(int n) { - int a = 1; - int b = 1; - int c; - - for (int i = 0; i < n - 1; i++) { - c = a + b; - a = b; - b = c; + public int climbStairs(int n) { + int a = 1; + int b = 1; + int c; + + for (int i = 0; i < n - 1; i++) { + c = a + b; + a = b; + b = c; + } + return b; } - return b; - } } //bottom up class Solution { - public int climbStairs(int n) { - int[] dp = new int[n + 1]; - dp[0] = 1; - dp[1] = 1; + public int climbStairs(int n) { + int[] dp = new int[n + 1]; + dp[0] = 1; + dp[1] = 1; - for (int i = 2; i < n + 1; i++) { - dp[i] = dp[i - 1] + dp[i - 2]; + for (int i = 2; i < n + 1; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + return dp[n]; } - return dp[n]; - } } //top down with memo[] class Solution { - public int climbStairs(int n) { - int[] memo = new int[n + 1]; - Arrays.fill(memo, -1); + public int climbStairs(int n) { + int[] memo = new int[n + 1]; + Arrays.fill(memo, -1); - return climbStairs(n - 1, memo) + climbStairs(n - 2, memo); - } - - private int climbStairs(int n, int[] memo) { - if (n < 0) return 0; - if (n == 0 || n == 1) { - memo[n] = 1; - return memo[n]; + return climbStairs(n - 1, memo) + climbStairs(n - 2, memo); } - if (memo[n] != -1) return memo[n]; - memo[n] = climbStairs(n - 1, memo) + climbStairs(n - 2, memo); - return memo[n]; - } + private int climbStairs(int n, int[] memo) { + if (n < 0) return 0; + if (n == 0 || n == 1) { + memo[n] = 1; + return memo[n]; + } + if (memo[n] != -1) return memo[n]; + + memo[n] = climbStairs(n - 1, memo) + climbStairs(n - 2, memo); + return memo[n]; + } } diff --git a/java/703-Kth-Largest-Element-in-a-Stream.java b/java/703-Kth-Largest-Element-in-a-Stream.java index 4ca5455b0..e8b5655b5 100644 --- a/java/703-Kth-Largest-Element-in-a-Stream.java +++ b/java/703-Kth-Largest-Element-in-a-Stream.java @@ -1,19 +1,19 @@ class KthLargest { - final PriorityQueue heap = new PriorityQueue<>(); - final int k; + final PriorityQueue heap = new PriorityQueue<>(); + final int k; - public KthLargest(int k, int[] nums) { - this.k = k; - for (int n : nums) add(n); - } + public KthLargest(int k, int[] nums) { + this.k = k; + for (int n : nums) add(n); + } - public int add(int val) { - if (heap.size() < k) heap.offer(val); //for adding the values of the array - else if (val > heap.peek()) { - heap.poll(); //remove the top element - heap.add(val); //add the new element + public int add(int val) { + if (heap.size() < k) heap.offer(val); //for adding the values of the array + else if (val > heap.peek()) { + heap.poll(); //remove the top element + heap.add(val); //add the new element + } + return heap.peek(); } - return heap.peek(); - } } diff --git a/java/704-Binary-Search.java b/java/704-Binary-Search.java index 6ed527186..0414b1be0 100644 --- a/java/704-Binary-Search.java +++ b/java/704-Binary-Search.java @@ -1,16 +1,17 @@ class Solution { - public int search(int[] nums, int target) { - int i = 0; - int j = nums.length - 1; + public int search(int[] nums, int target) { + int i = 0; + int j = nums.length - 1; - while (i <= j) { - int mid = (i + j) / 2; + while (i <= j) { + int mid = (i + j) / 2; - if (nums[mid] == target) return mid; else if (nums[mid] < target) i = - mid + 1; else j = mid - 1; - } + if (nums[mid] == target) return mid; else if ( + nums[mid] < target + ) i = mid + 1; else j = mid - 1; + } - return -1; - } + return -1; + } } diff --git a/java/713-Subarray-Product-Less-Than-K.java b/java/713-Subarray-Product-Less-Than-K.java index 8ab37b99d..4b2fa9066 100644 --- a/java/713-Subarray-Product-Less-Than-K.java +++ b/java/713-Subarray-Product-Less-Than-K.java @@ -8,16 +8,16 @@ //Similarly you can see this pattern further (try it yourself or see the linked comment for more details) class Solution { - public int numSubarrayProductLessThanK(int[] nums, int k) { - if (k <= 1) return 0; - int left = 0; - int product = 1; - int ans = 0; - for (int right = 0; right < nums.length; right++) { - product *= nums[right]; - while (product >= k) product /= nums[left++]; - ans += right - left + 1; + public int numSubarrayProductLessThanK(int[] nums, int k) { + if (k <= 1) return 0; + int left = 0; + int product = 1; + int ans = 0; + for (int right = 0; right < nums.length; right++) { + product *= nums[right]; + while (product >= k) product /= nums[left++]; + ans += right - left + 1; + } + return ans; } - return ans; - } } diff --git a/java/72-Edit-Distance.java b/java/72-Edit-Distance.java index 835209355..de7f66e7a 100644 --- a/java/72-Edit-Distance.java +++ b/java/72-Edit-Distance.java @@ -4,40 +4,40 @@ class Solution { - public int minDistance(String word1, String word2) { - int m = word1.length() - 1; - int n = word2.length() - 1; - int[][] dp = new int[m + 2][n + 2]; - for (int[] d : dp) { - Arrays.fill(d, -1); + public int minDistance(String word1, String word2) { + int m = word1.length() - 1; + int n = word2.length() - 1; + int[][] dp = new int[m + 2][n + 2]; + for (int[] d : dp) { + Arrays.fill(d, -1); + } + return helper(word1, word2, m, n, dp); } - return helper(word1, word2, m, n, dp); - } - public int helper(String word1, String word2, int m, int n, int[][] dp) { - //the strings are null - if (m + 1 == 0 && n + 1 == 0) { - return 0; + public int helper(String word1, String word2, int m, int n, int[][] dp) { + //the strings are null + if (m + 1 == 0 && n + 1 == 0) { + return 0; + } + //one of the strings are null + if (m + 1 == 0 || n + 1 == 0) { + return Math.max(m + 1, n + 1); + } + //both values at the index are equal + if (dp[m][n] != -1) return dp[m][n]; + if (word1.charAt(m) == word2.charAt(n)) { + dp[m][n] = helper(word1, word2, m - 1, n - 1, dp); + return dp[m][n]; + } else { + //try deletion + int delete = 1 + helper(word1, word2, m - 1, n, dp); + //try insertion + int insert = 1 + helper(word1, word2, m, n - 1, dp); + //try replacing + int replace = 1 + helper(word1, word2, m - 1, n - 1, dp); + //now we'll choose the minimum out of these 3 and add 1 for the operation cost + dp[m][n] = Math.min(Math.min(delete, insert), replace); + return dp[m][n]; + } } - //one of the strings are null - if (m + 1 == 0 || n + 1 == 0) { - return Math.max(m + 1, n + 1); - } - //both values at the index are equal - if (dp[m][n] != -1) return dp[m][n]; - if (word1.charAt(m) == word2.charAt(n)) { - dp[m][n] = helper(word1, word2, m - 1, n - 1, dp); - return dp[m][n]; - } else { - //try deletion - int delete = 1 + helper(word1, word2, m - 1, n, dp); - //try insertion - int insert = 1 + helper(word1, word2, m, n - 1, dp); - //try replacing - int replace = 1 + helper(word1, word2, m - 1, n - 1, dp); - //now we'll choose the minimum out of these 3 and add 1 for the operation cost - dp[m][n] = Math.min(Math.min(delete, insert), replace); - return dp[m][n]; - } - } } diff --git a/java/73-Set-Matrix-Zeroes.java b/java/73-Set-Matrix-Zeroes.java index 894253318..1c9a6aaf9 100644 --- a/java/73-Set-Matrix-Zeroes.java +++ b/java/73-Set-Matrix-Zeroes.java @@ -1,41 +1,41 @@ class Solution { - public void setZeroes(int[][] matrix) { - int rows = matrix.length; - int cols = matrix[0].length; - boolean firstRow = false; + public void setZeroes(int[][] matrix) { + int rows = matrix.length; + int cols = matrix[0].length; + boolean firstRow = false; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { - if (matrix[i][j] == 0) { - matrix[0][j] = 0; - if (i == 0) { - firstRow = true; - } else { - matrix[i][0] = 0; - } + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (matrix[i][j] == 0) { + matrix[0][j] = 0; + if (i == 0) { + firstRow = true; + } else { + matrix[i][0] = 0; + } + } + } } - } - } - for (int i = 1; i < rows; i++) { - for (int j = 1; j < cols; j++) { - if (matrix[0][j] == 0 || matrix[i][0] == 0) { - matrix[i][j] = 0; + for (int i = 1; i < rows; i++) { + for (int j = 1; j < cols; j++) { + if (matrix[0][j] == 0 || matrix[i][0] == 0) { + matrix[i][j] = 0; + } + } } - } - } - if (matrix[0][0] == 0) { - for (int i = 0; i < rows; i++) { - matrix[i][0] = 0; - } - } + if (matrix[0][0] == 0) { + for (int i = 0; i < rows; i++) { + matrix[i][0] = 0; + } + } - if (firstRow) { - for (int j = 0; j < cols; j++) { - matrix[0][j] = 0; - } + if (firstRow) { + for (int j = 0; j < cols; j++) { + matrix[0][j] = 0; + } + } } - } } diff --git a/java/739-Daily-Temperatures.java b/java/739-Daily-Temperatures.java index 737cebba6..d03cbd7aa 100644 --- a/java/739-Daily-Temperatures.java +++ b/java/739-Daily-Temperatures.java @@ -1,17 +1,18 @@ class Solution { - public int[] dailyTemperatures(int[] temperatures) { - int[] ans = new int[temperatures.length]; - Stack stack = new Stack<>(); - for (int currDay = 0; currDay < temperatures.length; currDay++) { - while ( - !stack.isEmpty() && temperatures[currDay] > temperatures[stack.peek()] - ) { - int prevDay = stack.pop(); - ans[prevDay] = currDay - prevDay; - } - stack.add(currDay); + public int[] dailyTemperatures(int[] temperatures) { + int[] ans = new int[temperatures.length]; + Stack stack = new Stack<>(); + for (int currDay = 0; currDay < temperatures.length; currDay++) { + while ( + !stack.isEmpty() && + temperatures[currDay] > temperatures[stack.peek()] + ) { + int prevDay = stack.pop(); + ans[prevDay] = currDay - prevDay; + } + stack.add(currDay); + } + return ans; } - return ans; - } } diff --git a/java/74-Search-A-2D-Matrix.java b/java/74-Search-A-2D-Matrix.java index f7690cd00..7ea9995bd 100644 --- a/java/74-Search-A-2D-Matrix.java +++ b/java/74-Search-A-2D-Matrix.java @@ -1,19 +1,19 @@ class Solution { - public boolean searchMatrix(int[][] matrix, int target) { - int lrow = 0; - int rrow = matrix.length - 1; - int n = 0; + public boolean searchMatrix(int[][] matrix, int target) { + int lrow = 0; + int rrow = matrix.length - 1; + int n = 0; - while (lrow < rrow) { - n = (lrow + rrow) / 2; - if (matrix[n][0] > target) rrow = n; else if ( - matrix[n][matrix[0].length - 1] < target - ) lrow = n + 1; else break; - } + while (lrow < rrow) { + n = (lrow + rrow) / 2; + if (matrix[n][0] > target) rrow = n; else if ( + matrix[n][matrix[0].length - 1] < target + ) lrow = n + 1; else break; + } - if ( - Arrays.binarySearch(matrix[(lrow + rrow) / 2], target) >= 0 - ) return true; else return false; - } + if ( + Arrays.binarySearch(matrix[(lrow + rrow) / 2], target) >= 0 + ) return true; else return false; + } } diff --git a/java/746-Min-Cost-Climbing-Stairs.java b/java/746-Min-Cost-Climbing-Stairs.java index 9a5ef4632..f61fb8b51 100644 --- a/java/746-Min-Cost-Climbing-Stairs.java +++ b/java/746-Min-Cost-Climbing-Stairs.java @@ -1,15 +1,17 @@ class Solution { - public int minCostClimbingStairs(int[] cost) { - int[] res = new int[cost.length + 1]; - res[cost.length] = 0; - res[cost.length - 1] = cost[cost.length - 1]; + public int minCostClimbingStairs(int[] cost) { + int[] res = new int[cost.length + 1]; + res[cost.length] = 0; + res[cost.length - 1] = cost[cost.length - 1]; - for (int i = cost.length - 2; i >= 0; i--) { - res[i] = - (res[i + 1] < res[i + 2]) ? res[i + 1] + cost[i] : res[i + 2] + cost[i]; - } + for (int i = cost.length - 2; i >= 0; i--) { + res[i] = + (res[i + 1] < res[i + 2]) + ? res[i + 1] + cost[i] + : res[i + 2] + cost[i]; + } - return Math.min(res[0], res[1]); - } + return Math.min(res[0], res[1]); + } } diff --git a/java/75-Sort-Colors.java b/java/75-Sort-Colors.java index dde074d6d..aa59a42bb 100644 --- a/java/75-Sort-Colors.java +++ b/java/75-Sort-Colors.java @@ -1,20 +1,20 @@ class Solution { - public void sortColors(int[] nums) { - int left = 0, mid = 0, right = nums.length - 1; - while (mid <= right) { - System.out.println(nums[mid]); - if (nums[mid] == 1) mid++; else if (nums[mid] == 0) { - swap(nums, mid++, left++); - } else if (nums[mid] == 2) { - swap(nums, mid, right--); - } + public void sortColors(int[] nums) { + int left = 0, mid = 0, right = nums.length - 1; + while (mid <= right) { + System.out.println(nums[mid]); + if (nums[mid] == 1) mid++; else if (nums[mid] == 0) { + swap(nums, mid++, left++); + } else if (nums[mid] == 2) { + swap(nums, mid, right--); + } + } } - } - public void swap(int[] nums, int i, int j) { - int temp = nums[i]; - nums[i] = nums[j]; - nums[j] = temp; - } + public void swap(int[] nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } } diff --git a/java/752-Open-the-lock.java b/java/752-Open-the-lock.java index c505f0583..730777d80 100644 --- a/java/752-Open-the-lock.java +++ b/java/752-Open-the-lock.java @@ -2,47 +2,47 @@ class Solution { - public int openLock(String[] deadends, String target) { - String start = "0000"; - int ans = 0; - Queue q = new LinkedList<>(); - HashSet visited = new HashSet<>(); - //Add all the deadends in the visited set so we can ignore them and visited values altogether. - for (String s : deadends) visited.add(s); - q.offer(start); - while (!q.isEmpty()) { - int size = q.size(); - for (int j = 0; j < size; j++) { - String str = q.poll(); - StringBuilder cur = new StringBuilder(str); - if (str.equals(target)) return ans; - if (!visited.contains(cur.toString())) { - for (int i = 0; i < start.length(); i++) { - //edge case for 0 - if (cur.charAt(i) == '0') { - cur.setCharAt(i, '1'); - q.offer(cur.toString()); - cur.setCharAt(i, '9'); - q.offer(cur.toString()); - } else if (cur.charAt(i) == '9') { //edge case for 9 - cur.setCharAt(i, '0'); - q.offer(cur.toString()); - cur.setCharAt(i, '8'); - q.offer(cur.toString()); - } else { - cur.setCharAt(i, ((char) (cur.charAt(i) + 1))); - q.offer(cur.toString()); - cur.setCharAt(i, ((char) (cur.charAt(i) - 2))); - q.offer(cur.toString()); + public int openLock(String[] deadends, String target) { + String start = "0000"; + int ans = 0; + Queue q = new LinkedList<>(); + HashSet visited = new HashSet<>(); + //Add all the deadends in the visited set so we can ignore them and visited values altogether. + for (String s : deadends) visited.add(s); + q.offer(start); + while (!q.isEmpty()) { + int size = q.size(); + for (int j = 0; j < size; j++) { + String str = q.poll(); + StringBuilder cur = new StringBuilder(str); + if (str.equals(target)) return ans; + if (!visited.contains(cur.toString())) { + for (int i = 0; i < start.length(); i++) { + //edge case for 0 + if (cur.charAt(i) == '0') { + cur.setCharAt(i, '1'); + q.offer(cur.toString()); + cur.setCharAt(i, '9'); + q.offer(cur.toString()); + } else if (cur.charAt(i) == '9') { //edge case for 9 + cur.setCharAt(i, '0'); + q.offer(cur.toString()); + cur.setCharAt(i, '8'); + q.offer(cur.toString()); + } else { + cur.setCharAt(i, ((char) (cur.charAt(i) + 1))); + q.offer(cur.toString()); + cur.setCharAt(i, ((char) (cur.charAt(i) - 2))); + q.offer(cur.toString()); + } + visited.add(str); + cur.setLength(0); + cur.append(str); + } + } } - visited.add(str); - cur.setLength(0); - cur.append(str); - } + ans++; } - } - ans++; + return -1; } - return -1; - } } diff --git a/java/76-Minimum-Window-Substring.java b/java/76-Minimum-Window-Substring.java index b530f6309..6f951f81d 100644 --- a/java/76-Minimum-Window-Substring.java +++ b/java/76-Minimum-Window-Substring.java @@ -1,36 +1,36 @@ class Solution { - //sliding window - public String minWindow(String s, String t) { - HashMap map = new HashMap<>(); + //sliding window + public String minWindow(String s, String t) { + HashMap map = new HashMap<>(); - for (char x : t.toCharArray()) { - map.put(x, map.getOrDefault(x, 0) + 1); - } + for (char x : t.toCharArray()) { + map.put(x, map.getOrDefault(x, 0) + 1); + } - int matched = 0; - int start = 0; - int minLen = s.length() + 1; - int subStr = 0; - for (int endWindow = 0; endWindow < s.length(); endWindow++) { - char right = s.charAt(endWindow); - if (map.containsKey(right)) { - map.put(right, map.get(right) - 1); - if (map.get(right) == 0) matched++; - } + int matched = 0; + int start = 0; + int minLen = s.length() + 1; + int subStr = 0; + for (int endWindow = 0; endWindow < s.length(); endWindow++) { + char right = s.charAt(endWindow); + if (map.containsKey(right)) { + map.put(right, map.get(right) - 1); + if (map.get(right) == 0) matched++; + } - while (matched == map.size()) { - if (minLen > endWindow - start + 1) { - minLen = endWindow - start + 1; - subStr = start; - } - char deleted = s.charAt(start++); - if (map.containsKey(deleted)) { - if (map.get(deleted) == 0) matched--; - map.put(deleted, map.get(deleted) + 1); + while (matched == map.size()) { + if (minLen > endWindow - start + 1) { + minLen = endWindow - start + 1; + subStr = start; + } + char deleted = s.charAt(start++); + if (map.containsKey(deleted)) { + if (map.get(deleted) == 0) matched--; + map.put(deleted, map.get(deleted) + 1); + } + } } - } + return minLen > s.length() ? "" : s.substring(subStr, subStr + minLen); } - return minLen > s.length() ? "" : s.substring(subStr, subStr + minLen); - } } diff --git a/java/763-Partition-Labels.java b/java/763-Partition-Labels.java index c19561683..7df1a5eeb 100644 --- a/java/763-Partition-Labels.java +++ b/java/763-Partition-Labels.java @@ -1,23 +1,23 @@ class Solution { - public List partitionLabels(String s) { - List list = new ArrayList<>(); - HashMap map = new HashMap<>(); - for (int i = 0; i < s.length(); i++) { - map.put(s.charAt(i), i); + public List partitionLabels(String s) { + List list = new ArrayList<>(); + HashMap map = new HashMap<>(); + for (int i = 0; i < s.length(); i++) { + map.put(s.charAt(i), i); + } + int j = 0; + int i = 0; + while (i < s.length()) { + int count = 0; + j = Math.max(j, map.get(s.charAt(i))); + while (i <= j) { + j = Math.max(j, map.get(s.charAt(i))); + i++; + count++; + } + list.add(count); + } + return list; } - int j = 0; - int i = 0; - while (i < s.length()) { - int count = 0; - j = Math.max(j, map.get(s.charAt(i))); - while (i <= j) { - j = Math.max(j, map.get(s.charAt(i))); - i++; - count++; - } - list.add(count); - } - return list; - } } diff --git a/java/767-Reorganize-String.java b/java/767-Reorganize-String.java index c64ab812b..5bb07b31a 100644 --- a/java/767-Reorganize-String.java +++ b/java/767-Reorganize-String.java @@ -2,40 +2,42 @@ class Solution { - public String reorganizeString(String s) { - HashMap map = new HashMap<>(); - for (int i = 0; i < s.length(); i++) { - map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1); - } - PriorityQueue> pq = new PriorityQueue<>( - (a, b) -> - b.getValue() - a.getValue() - ); - pq.addAll(map.entrySet()); + public String reorganizeString(String s) { + HashMap map = new HashMap<>(); + for (int i = 0; i < s.length(); i++) { + map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1); + } + PriorityQueue> pq = new PriorityQueue<>( + (a, b) -> + b.getValue() - a.getValue() + ); + pq.addAll(map.entrySet()); - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); - while (!pq.isEmpty()) { - Map.Entry temp1 = pq.poll(); - //if the character at sb's end is different from the max frequency character or the string is empty - if (sb.length() == 0 || sb.charAt(sb.length() - 1) != temp1.getKey()) { - sb.append(temp1.getKey()); - //update the value - temp1.setValue(temp1.getValue() - 1); - } else { //the character is same - //hold the current character and look for the 2nd most frequent character - Map.Entry temp2 = pq.poll(); - //if there is no temp2 i.e. the temp1 was the only character in the heap then there is no way to avoid adjacent duplicate values - if (temp2 == null) return ""; - //else do the same thing as above - sb.append(temp2.getKey()); - //update the value - temp2.setValue(temp2.getValue() - 1); - //if still has some value left add again to the heap - if (temp2.getValue() != 0) pq.offer(temp2); - } - if (temp1.getValue() != 0) pq.offer(temp1); + while (!pq.isEmpty()) { + Map.Entry temp1 = pq.poll(); + //if the character at sb's end is different from the max frequency character or the string is empty + if ( + sb.length() == 0 || sb.charAt(sb.length() - 1) != temp1.getKey() + ) { + sb.append(temp1.getKey()); + //update the value + temp1.setValue(temp1.getValue() - 1); + } else { //the character is same + //hold the current character and look for the 2nd most frequent character + Map.Entry temp2 = pq.poll(); + //if there is no temp2 i.e. the temp1 was the only character in the heap then there is no way to avoid adjacent duplicate values + if (temp2 == null) return ""; + //else do the same thing as above + sb.append(temp2.getKey()); + //update the value + temp2.setValue(temp2.getValue() - 1); + //if still has some value left add again to the heap + if (temp2.getValue() != 0) pq.offer(temp2); + } + if (temp1.getValue() != 0) pq.offer(temp1); + } + return sb.toString(); } - return sb.toString(); - } } diff --git a/java/779-K-th-Symbol-in-Grammar.java b/java/779-K-th-Symbol-in-Grammar.java index 9a4cec623..ffbbcc542 100644 --- a/java/779-K-th-Symbol-in-Grammar.java +++ b/java/779-K-th-Symbol-in-Grammar.java @@ -3,13 +3,13 @@ class Solution { - public int kthGrammar(int n, int k) { - if (n == 1 || k == 1) return 0; - int prevK = (int) Math.pow(2, n - 2); - if (k <= prevK) return kthGrammar(n - 1, k); else { - int presK = k % prevK; - int val = kthGrammar(n - 1, presK == 0 ? k / 2 : k % prevK); - return val == 1 ? 0 : 1; + public int kthGrammar(int n, int k) { + if (n == 1 || k == 1) return 0; + int prevK = (int) Math.pow(2, n - 2); + if (k <= prevK) return kthGrammar(n - 1, k); else { + int presK = k % prevK; + int val = kthGrammar(n - 1, presK == 0 ? k / 2 : k % prevK); + return val == 1 ? 0 : 1; + } } - } } diff --git a/java/78-Subsets.java b/java/78-Subsets.java index f5de07d2e..efb5e5e3c 100644 --- a/java/78-Subsets.java +++ b/java/78-Subsets.java @@ -2,28 +2,28 @@ //This video was good for code explanation. https://www.youtube.com/watch?v=6BPurabdAl4&t=508s&ab_channel=Fraz class Solution { - public List> subsets(int[] nums) { - List> ans = new ArrayList<>(); - List list = new ArrayList<>(); - helper(ans, 0, nums, list); - return ans; - } + public List> subsets(int[] nums) { + List> ans = new ArrayList<>(); + List list = new ArrayList<>(); + helper(ans, 0, nums, list); + return ans; + } - public void helper( - List> ans, - int start, - int[] nums, - List list - ) { - if (start >= nums.length) { - ans.add(new ArrayList<>(list)); //In java, we will have to add like this otherwise it'll give null as it'll just have the reference instead of actual values. - } else { - //add the element and start the recursive call - list.add(nums[start]); - helper(ans, start + 1, nums, list); - //remove the element and do the backtracking call. - list.remove(list.size() - 1); - helper(ans, start + 1, nums, list); + public void helper( + List> ans, + int start, + int[] nums, + List list + ) { + if (start >= nums.length) { + ans.add(new ArrayList<>(list)); //In java, we will have to add like this otherwise it'll give null as it'll just have the reference instead of actual values. + } else { + //add the element and start the recursive call + list.add(nums[start]); + helper(ans, start + 1, nums, list); + //remove the element and do the backtracking call. + list.remove(list.size() - 1); + helper(ans, start + 1, nums, list); + } } - } } diff --git a/java/79-Word-Search.java b/java/79-Word-Search.java index f3a14308e..ce391f2a9 100644 --- a/java/79-Word-Search.java +++ b/java/79-Word-Search.java @@ -4,42 +4,46 @@ class Solution { - public boolean exist(char[][] board, String word) { - int m = board.length; - int n = board[0].length; - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (check(board, word, i, j, m, n, 0)) { - return true; + public boolean exist(char[][] board, String word) { + int m = board.length; + int n = board[0].length; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (check(board, word, i, j, m, n, 0)) { + return true; + } + } } - } + return false; } - return false; - } - public boolean check( - char[][] board, - String word, - int i, - int j, - int m, - int n, - int cur - ) { - if (cur >= word.length()) return true; - if ( - i < 0 || j < 0 || i >= m || j >= n || board[i][j] != word.charAt(cur) - ) return false; - boolean exist = false; - if (board[i][j] == word.charAt(cur)) { - board[i][j] += 100; - exist = - check(board, word, i + 1, j, m, n, cur + 1) || - check(board, word, i, j + 1, m, n, cur + 1) || - check(board, word, i - 1, j, m, n, cur + 1) || - check(board, word, i, j - 1, m, n, cur + 1); - board[i][j] -= 100; + public boolean check( + char[][] board, + String word, + int i, + int j, + int m, + int n, + int cur + ) { + if (cur >= word.length()) return true; + if ( + i < 0 || + j < 0 || + i >= m || + j >= n || + board[i][j] != word.charAt(cur) + ) return false; + boolean exist = false; + if (board[i][j] == word.charAt(cur)) { + board[i][j] += 100; + exist = + check(board, word, i + 1, j, m, n, cur + 1) || + check(board, word, i, j + 1, m, n, cur + 1) || + check(board, word, i - 1, j, m, n, cur + 1) || + check(board, word, i, j - 1, m, n, cur + 1); + board[i][j] -= 100; + } + return exist; } - return exist; - } } diff --git a/java/797-All-Paths-From-Source-to-Target.java b/java/797-All-Paths-From-Source-to-Target.java index 84d020b12..bdc55f33d 100644 --- a/java/797-All-Paths-From-Source-to-Target.java +++ b/java/797-All-Paths-From-Source-to-Target.java @@ -1,27 +1,27 @@ class Solution { - public List> allPathsSourceTarget(int[][] graph) { - List> ans = new ArrayList<>(); - List list = new ArrayList<>(); - list.add(0); - dfs(ans, graph, list, 0); - return ans; - } - - public void dfs( - List> ans, - int[][] graph, - List list, - int i - ) { - if (i == graph.length - 1) { - ans.add(new ArrayList(list)); - return; + public List> allPathsSourceTarget(int[][] graph) { + List> ans = new ArrayList<>(); + List list = new ArrayList<>(); + list.add(0); + dfs(ans, graph, list, 0); + return ans; } - for (int val : graph[i]) { - list.add(val); - dfs(ans, graph, list, val); - list.remove(list.size() - 1); + + public void dfs( + List> ans, + int[][] graph, + List list, + int i + ) { + if (i == graph.length - 1) { + ans.add(new ArrayList(list)); + return; + } + for (int val : graph[i]) { + list.add(val); + dfs(ans, graph, list, val); + list.remove(list.size() - 1); + } } - } } diff --git a/java/83. Remove Duplicates from Sorted List.java b/java/83. Remove Duplicates from Sorted List.java index d23e6bec6..d84bb3ac9 100644 --- a/java/83. Remove Duplicates from Sorted List.java +++ b/java/83. Remove Duplicates from Sorted List.java @@ -2,20 +2,20 @@ class Solution { - public ListNode deleteDuplicates(ListNode head) { - ListNode p = null; - ListNode q = null; - ListNode r = head; - while (r != null) { - if (q != null && q.val == r.val) { - r = r.next; - q.next = r; - } else { - p = q; - q = r; - r = r.next; - } + public ListNode deleteDuplicates(ListNode head) { + ListNode p = null; + ListNode q = null; + ListNode r = head; + while (r != null) { + if (q != null && q.val == r.val) { + r = r.next; + q.next = r; + } else { + p = q; + q = r; + r = r.next; + } + } + return head; } - return head; - } } diff --git a/java/84-Largest-Rectangle-in-Histogram.java b/java/84-Largest-Rectangle-in-Histogram.java index 937a61d68..1fb2d1b98 100644 --- a/java/84-Largest-Rectangle-in-Histogram.java +++ b/java/84-Largest-Rectangle-in-Histogram.java @@ -1,40 +1,40 @@ class Solution { - public int largestRectangleArea(int[] heights) { - int n = heights.length; - int[] leftMin = new int[n]; - Stack left = new Stack<>(); - Arrays.fill(leftMin, -1); - for (int i = heights.length - 1; i >= 0; i--) { - if (left.isEmpty() || heights[i] >= heights[left.peek()]) { - left.add(i); - } else { - while (!left.isEmpty() && heights[left.peek()] > heights[i]) { - leftMin[left.peek()] = i; - left.pop(); + public int largestRectangleArea(int[] heights) { + int n = heights.length; + int[] leftMin = new int[n]; + Stack left = new Stack<>(); + Arrays.fill(leftMin, -1); + for (int i = heights.length - 1; i >= 0; i--) { + if (left.isEmpty() || heights[i] >= heights[left.peek()]) { + left.add(i); + } else { + while (!left.isEmpty() && heights[left.peek()] > heights[i]) { + leftMin[left.peek()] = i; + left.pop(); + } + left.add(i); + } } - left.add(i); - } - } - int[] rightMin = new int[n]; - Stack right = new Stack<>(); - Arrays.fill(rightMin, heights.length); - for (int i = 0; i < heights.length; i++) { - if (right.isEmpty() || heights[i] >= heights[right.peek()]) { - right.add(i); - } else { - while (!right.isEmpty() && heights[right.peek()] > heights[i]) { - rightMin[right.peek()] = i; - right.pop(); + int[] rightMin = new int[n]; + Stack right = new Stack<>(); + Arrays.fill(rightMin, heights.length); + for (int i = 0; i < heights.length; i++) { + if (right.isEmpty() || heights[i] >= heights[right.peek()]) { + right.add(i); + } else { + while (!right.isEmpty() && heights[right.peek()] > heights[i]) { + rightMin[right.peek()] = i; + right.pop(); + } + right.add(i); + } } - right.add(i); - } - } - // System.out.println() - int area = Integer.MIN_VALUE; - for (int i = 0; i < heights.length; i++) { - area = Math.max(area, heights[i] * (rightMin[i] - leftMin[i] - 1)); + // System.out.println() + int area = Integer.MIN_VALUE; + for (int i = 0; i < heights.length; i++) { + area = Math.max(area, heights[i] * (rightMin[i] - leftMin[i] - 1)); + } + return area; } - return area; - } } diff --git a/java/852. Peak Index in a Mountain Array.java b/java/852. Peak Index in a Mountain Array.java index 69772559d..ed82dbf5d 100644 --- a/java/852. Peak Index in a Mountain Array.java +++ b/java/852. Peak Index in a Mountain Array.java @@ -1,20 +1,23 @@ //Use binary search class Solution { - public int peakIndexInMountainArray(int[] arr) { - int start = 0; - int end = arr.length; - int n = arr.length; - while (start <= end) { - int mid = start + (end - start) / 2; - if ( - mid != 0 && - mid != n - 1 && - arr[mid - 1] < arr[mid] && - arr[mid + 1] < arr[mid] - ) return mid; else if (mid != n - 1 && arr[mid + 1] > arr[mid]) start = - mid + 1; else if (mid != 0 && arr[mid - 1] > arr[mid]) end = mid - 1; + public int peakIndexInMountainArray(int[] arr) { + int start = 0; + int end = arr.length; + int n = arr.length; + while (start <= end) { + int mid = start + (end - start) / 2; + if ( + mid != 0 && + mid != n - 1 && + arr[mid - 1] < arr[mid] && + arr[mid + 1] < arr[mid] + ) return mid; else if ( + mid != n - 1 && arr[mid + 1] > arr[mid] + ) start = mid + 1; else if ( + mid != 0 && arr[mid - 1] > arr[mid] + ) end = mid - 1; + } + return end; } - return end; - } } diff --git a/java/853-Car Fleet.java b/java/853-Car Fleet.java index 1070ee822..f6e636eb7 100644 --- a/java/853-Car Fleet.java +++ b/java/853-Car Fleet.java @@ -1,23 +1,24 @@ class Solution { - public int carFleet(int target, int[] position, int[] speed) { - if (position.length == 1) return 1; - Stack stack = new Stack<>(); - int[][] combine = new int[position.length][2]; - for (int i = 0; i < position.length; i++) { - combine[i][0] = position[i]; - combine[i][1] = speed[i]; - } + public int carFleet(int target, int[] position, int[] speed) { + if (position.length == 1) return 1; + Stack stack = new Stack<>(); + int[][] combine = new int[position.length][2]; + for (int i = 0; i < position.length; i++) { + combine[i][0] = position[i]; + combine[i][1] = speed[i]; + } - Arrays.sort(combine, java.util.Comparator.comparingInt(o -> o[0])); - for (int i = combine.length - 1; i >= 0; i--) { - double currentTime = (double) (target - combine[i][0]) / combine[i][1]; - if (!stack.isEmpty() && currentTime <= stack.peek()) { - continue; - } else { - stack.push(currentTime); - } + Arrays.sort(combine, java.util.Comparator.comparingInt(o -> o[0])); + for (int i = combine.length - 1; i >= 0; i--) { + double currentTime = (double) (target - combine[i][0]) / + combine[i][1]; + if (!stack.isEmpty() && currentTime <= stack.peek()) { + continue; + } else { + stack.push(currentTime); + } + } + return stack.size(); } - return stack.size(); - } } diff --git a/java/863-All-Nodes-Distance-K-in-Binary-Tree.java b/java/863-All-Nodes-Distance-K-in-Binary-Tree.java index 42c19bf9c..1e3070165 100644 --- a/java/863-All-Nodes-Distance-K-in-Binary-Tree.java +++ b/java/863-All-Nodes-Distance-K-in-Binary-Tree.java @@ -2,48 +2,48 @@ class Solution { - public List distanceK(TreeNode root, TreeNode target, int k) { - HashMap map = new HashMap<>(); - //First bfs to make a mapping to the parent nodes - Queue q1 = new LinkedList<>(); - q1.offer(root); - while (!q1.isEmpty()) { - int size = q1.size(); - for (int i = 0; i < size; i++) { - TreeNode cur = q1.poll(); - if (cur.left != null) { - q1.offer(cur.left); - map.put(cur.left, cur); + public List distanceK(TreeNode root, TreeNode target, int k) { + HashMap map = new HashMap<>(); + //First bfs to make a mapping to the parent nodes + Queue q1 = new LinkedList<>(); + q1.offer(root); + while (!q1.isEmpty()) { + int size = q1.size(); + for (int i = 0; i < size; i++) { + TreeNode cur = q1.poll(); + if (cur.left != null) { + q1.offer(cur.left); + map.put(cur.left, cur); + } + if (cur.right != null) { + q1.offer(cur.right); + map.put(cur.right, cur); + } + } } - if (cur.right != null) { - q1.offer(cur.right); - map.put(cur.right, cur); + //Now do the bfs + //Same as we do in graphs with a visited set + Queue q2 = new LinkedList<>(); + HashSet vis = new HashSet<>(); + List ans = new ArrayList<>(); + int dis = 0; + q2.offer(target); + while (!q2.isEmpty()) { + int size = q2.size(); + for (int i = 0; i < size; i++) { + TreeNode cur = q2.poll(); + if (!vis.contains(cur)) { + if (cur.left != null) q2.offer(cur.left); + if (cur.right != null) q2.offer(cur.right); + if (map.get(cur) != null) q2.offer(map.get(cur)); + if (dis == k) { + ans.add(cur.val); + } + } + vis.add(cur); + } + dis++; } - } + return ans; } - //Now do the bfs - //Same as we do in graphs with a visited set - Queue q2 = new LinkedList<>(); - HashSet vis = new HashSet<>(); - List ans = new ArrayList<>(); - int dis = 0; - q2.offer(target); - while (!q2.isEmpty()) { - int size = q2.size(); - for (int i = 0; i < size; i++) { - TreeNode cur = q2.poll(); - if (!vis.contains(cur)) { - if (cur.left != null) q2.offer(cur.left); - if (cur.right != null) q2.offer(cur.right); - if (map.get(cur) != null) q2.offer(map.get(cur)); - if (dis == k) { - ans.add(cur.val); - } - } - vis.add(cur); - } - dis++; - } - return ans; - } } diff --git a/java/875-Koko-Eating-Bananas.java b/java/875-Koko-Eating-Bananas.java index a2f25089c..2d54eaf8c 100644 --- a/java/875-Koko-Eating-Bananas.java +++ b/java/875-Koko-Eating-Bananas.java @@ -1,34 +1,34 @@ class Solution { - public int minEatingSpeed(int[] piles, int h) { - // Initalize the left and right boundaries - int left = 1, right = 1; - for (int pile : piles) { - right = Math.max(right, pile); - } + public int minEatingSpeed(int[] piles, int h) { + // Initalize the left and right boundaries + int left = 1, right = 1; + for (int pile : piles) { + right = Math.max(right, pile); + } - while (left < right) { - // Get the middle index between left and right boundary indexes. - // hourSpent stands for the total hour Koko spends. - int middle = (left + right) / 2; - int hourSpent = 0; + while (left < right) { + // Get the middle index between left and right boundary indexes. + // hourSpent stands for the total hour Koko spends. + int middle = (left + right) / 2; + int hourSpent = 0; - // Iterate over the piles and calculate hourSpent. - // We increase the hourSpent by ceil(pile / middle) - for (int pile : piles) { - hourSpent += Math.ceil((double) pile / middle); - } + // Iterate over the piles and calculate hourSpent. + // We increase the hourSpent by ceil(pile / middle) + for (int pile : piles) { + hourSpent += Math.ceil((double) pile / middle); + } - // Check if middle is a workable speed, and cut the search space by half. - if (hourSpent <= h) { - right = middle; - } else { - left = middle + 1; - } - } + // Check if middle is a workable speed, and cut the search space by half. + if (hourSpent <= h) { + right = middle; + } else { + left = middle + 1; + } + } - // Once the left and right boundaries coincide, we find the target value, - // that is, the minimum workable eating speed. - return right; - } + // Once the left and right boundaries coincide, we find the target value, + // that is, the minimum workable eating speed. + return right; + } } diff --git a/java/876. Middle of the Linked List.java b/java/876. Middle of the Linked List.java index e0afb7456..ec3da64a9 100644 --- a/java/876. Middle of the Linked List.java +++ b/java/876. Middle of the Linked List.java @@ -1,13 +1,13 @@ //fast and slow pointer class Solution { - public ListNode middleNode(ListNode head) { - ListNode slow = head; - ListNode fast = head; - while (fast != null && fast.next != null) { - fast = fast.next.next; - slow = slow.next; + public ListNode middleNode(ListNode head) { + ListNode slow = head; + ListNode fast = head; + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + } + return slow; } - return slow; - } } diff --git a/java/90-Subsets-II.java b/java/90-Subsets-II.java index 73685784a..3b44ac1c0 100644 --- a/java/90-Subsets-II.java +++ b/java/90-Subsets-II.java @@ -2,30 +2,30 @@ //This video was helpful https://www.youtube.com/watch?v=mcg4qKbAmmY&t=316s&ab_channel=Fraz class Solution { - public List> subsetsWithDup(int[] nums) { - Arrays.sort(nums); - List> ans = new ArrayList<>(); - ArrayList list = new ArrayList<>(); - helper(ans, 0, nums, list, false); - return ans; - } + public List> subsetsWithDup(int[] nums) { + Arrays.sort(nums); + List> ans = new ArrayList<>(); + ArrayList list = new ArrayList<>(); + helper(ans, 0, nums, list, false); + return ans; + } - public void helper( - List> ans, - int start, - int[] nums, - List list, - boolean ignored - ) { - if (start >= nums.length) { - ans.add(new ArrayList<>(list)); - } else { - helper(ans, start + 1, nums, list, true); - //if we've ignored the value earlier then we must ignore all the values after that too - if (start > 0 && nums[start - 1] == nums[start] && ignored) return; - list.add(nums[start]); - helper(ans, start + 1, nums, list, false); - list.remove(list.size() - 1); + public void helper( + List> ans, + int start, + int[] nums, + List list, + boolean ignored + ) { + if (start >= nums.length) { + ans.add(new ArrayList<>(list)); + } else { + helper(ans, start + 1, nums, list, true); + //if we've ignored the value earlier then we must ignore all the values after that too + if (start > 0 && nums[start - 1] == nums[start] && ignored) return; + list.add(nums[start]); + helper(ans, start + 1, nums, list, false); + list.remove(list.size() - 1); + } } - } } diff --git a/java/97-Interleaving-String.java b/java/97-Interleaving-String.java index dfac8f6af..1538cbaac 100644 --- a/java/97-Interleaving-String.java +++ b/java/97-Interleaving-String.java @@ -1,26 +1,34 @@ class Solution { - public boolean isInterleave(String s1, String s2, String s3) { - if (s1.length() + s2.length() != s3.length()) { - return false; - } + public boolean isInterleave(String s1, String s2, String s3) { + if (s1.length() + s2.length() != s3.length()) { + return false; + } - boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1]; - dp[s1.length()][s2.length()] = true; + boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1]; + dp[s1.length()][s2.length()] = true; - for (int i = dp.length - 1; i >= 0; i--) for ( - int j = dp[0].length - 1; - j >= 0; - j-- - ) { - if (i < s1.length() && s1.charAt(i) == s3.charAt(i + j) && dp[i + 1][j]) { - dp[i][j] = true; - } - if (j < s2.length() && s2.charAt(j) == s3.charAt(i + j) && dp[i][j + 1]) { - dp[i][j] = true; - } - } + for (int i = dp.length - 1; i >= 0; i--) for ( + int j = dp[0].length - 1; + j >= 0; + j-- + ) { + if ( + i < s1.length() && + s1.charAt(i) == s3.charAt(i + j) && + dp[i + 1][j] + ) { + dp[i][j] = true; + } + if ( + j < s2.length() && + s2.charAt(j) == s3.charAt(i + j) && + dp[i][j + 1] + ) { + dp[i][j] = true; + } + } - return dp[0][0]; - } + return dp[0][0]; + } } diff --git a/java/973-K-Closest-Points-to-Origin.java b/java/973-K-Closest-Points-to-Origin.java index ada0807a1..6026098ed 100644 --- a/java/973-K-Closest-Points-to-Origin.java +++ b/java/973-K-Closest-Points-to-Origin.java @@ -3,28 +3,32 @@ class Solution { - public int[][] kClosest(int[][] points, int k) { - HashMap map = new HashMap<>(); - PriorityQueue> pq = new PriorityQueue<>((a, b) -> - Double.compare(a.getValue(), b.getValue()) - ); - for (int i = 0; i < points.length; i++) { - map.put( - points[i], - Math.pow((Math.pow(points[i][0], 2) + Math.pow(points[i][1], 2)), 0.5) - ); //We can also ignore this rooting as I did in the next solution + public int[][] kClosest(int[][] points, int k) { + HashMap map = new HashMap<>(); + PriorityQueue> pq = new PriorityQueue<>( + (a, b) -> + Double.compare(a.getValue(), b.getValue()) + ); + for (int i = 0; i < points.length; i++) { + map.put( + points[i], + Math.pow( + (Math.pow(points[i][0], 2) + Math.pow(points[i][1], 2)), + 0.5 + ) + ); //We can also ignore this rooting as I did in the next solution + } + for (Map.Entry set : map.entrySet()) { + pq.add(set); + } + int[][] ans = new int[k][2]; + for (int i = 0; i < k; i++) { + int[] temp = pq.poll().getKey(); + ans[i][0] = temp[0]; + ans[i][1] = temp[1]; + } + return ans; } - for (Map.Entry set : map.entrySet()) { - pq.add(set); - } - int[][] ans = new int[k][2]; - for (int i = 0; i < k; i++) { - int[] temp = pq.poll().getKey(); - ans[i][0] = temp[0]; - ans[i][1] = temp[1]; - } - return ans; - } } //Since, we need to find the minimum, it doens't matter if we square root them. As the minimum will remain the same after square rooting also. @@ -32,26 +36,27 @@ public int[][] kClosest(int[][] points, int k) { class Solution { - public int[][] kClosest(int[][] points, int k) { - HashMap map = new HashMap<>(); - PriorityQueue> pq = new PriorityQueue<>((a, b) -> - a.getValue() - b.getValue() - ); - for (int i = 0; i < points.length; i++) { - map.put( - points[i], - (int) (Math.pow(points[i][0], 2) + Math.pow(points[i][1], 2)) - ); - } - for (Map.Entry set : map.entrySet()) { - pq.add(set); - } - int[][] ans = new int[k][2]; - for (int i = 0; i < k; i++) { - int[] temp = pq.poll().getKey(); - ans[i][0] = temp[0]; - ans[i][1] = temp[1]; + public int[][] kClosest(int[][] points, int k) { + HashMap map = new HashMap<>(); + PriorityQueue> pq = new PriorityQueue<>( + (a, b) -> + a.getValue() - b.getValue() + ); + for (int i = 0; i < points.length; i++) { + map.put( + points[i], + (int) (Math.pow(points[i][0], 2) + Math.pow(points[i][1], 2)) + ); + } + for (Map.Entry set : map.entrySet()) { + pq.add(set); + } + int[][] ans = new int[k][2]; + for (int i = 0; i < k; i++) { + int[] temp = pq.poll().getKey(); + ans[i][0] = temp[0]; + ans[i][1] = temp[1]; + } + return ans; } - return ans; - } } diff --git a/java/98-Validate-Binary-Search-Tree.java b/java/98-Validate-Binary-Search-Tree.java index d7765d834..e178d564b 100644 --- a/java/98-Validate-Binary-Search-Tree.java +++ b/java/98-Validate-Binary-Search-Tree.java @@ -15,18 +15,20 @@ */ class Solution { - public boolean isValidBST(TreeNode root) { - if (root == null) return true; - return dfs(root, null, null); - } + public boolean isValidBST(TreeNode root) { + if (root == null) return true; + return dfs(root, null, null); + } - private boolean dfs(TreeNode root, Integer min, Integer max) { - if (root == null) return true; + private boolean dfs(TreeNode root, Integer min, Integer max) { + if (root == null) return true; - if ((min != null && root.val <= min) || max != null && root.val >= max) { - return false; - } + if ( + (min != null && root.val <= min) || max != null && root.val >= max + ) { + return false; + } - return dfs(root.left, min, root.val) && dfs(root.right, root.val, max); - } + return dfs(root.left, min, root.val) && dfs(root.right, root.val, max); + } } diff --git a/java/981-Time-Based-Key-Value-Store.java b/java/981-Time-Based-Key-Value-Store.java index cf5c9e44c..e8c059052 100644 --- a/java/981-Time-Based-Key-Value-Store.java +++ b/java/981-Time-Based-Key-Value-Store.java @@ -1,32 +1,32 @@ class TimeMap { - HashMap>> map; + HashMap>> map; - public TimeMap() { - map = new HashMap<>(); - } + public TimeMap() { + map = new HashMap<>(); + } - public void set(String key, String value, int timestamp) { - if (!map.containsKey(key)) map.put(key, new ArrayList<>()); - map.get(key).add(new Pair(value, timestamp)); - } + public void set(String key, String value, int timestamp) { + if (!map.containsKey(key)) map.put(key, new ArrayList<>()); + map.get(key).add(new Pair(value, timestamp)); + } - public String get(String key, int timestamp) { - if (!map.containsKey(key)) return ""; - List> list = map.get(key); - return search(list, timestamp); - } + public String get(String key, int timestamp) { + if (!map.containsKey(key)) return ""; + List> list = map.get(key); + return search(list, timestamp); + } - public String search(List> list, int timestamp) { - int start = 0; - int end = list.size() - 1; - while (start < end) { - int mid = start + (end - start + 1) / 2; - if (list.get(mid).getValue() <= timestamp) start = mid; else end = - mid - 1; + public String search(List> list, int timestamp) { + int start = 0; + int end = list.size() - 1; + while (start < end) { + int mid = start + (end - start + 1) / 2; + if (list.get(mid).getValue() <= timestamp) start = mid; else end = + mid - 1; + } + return list.get(start).getValue() <= timestamp + ? list.get(start).getKey() + : ""; } - return list.get(start).getValue() <= timestamp - ? list.get(start).getKey() - : ""; - } } diff --git a/java/986-Interval-List-Intersections.java b/java/986-Interval-List-Intersections.java index 645bde4ad..010ab563a 100644 --- a/java/986-Interval-List-Intersections.java +++ b/java/986-Interval-List-Intersections.java @@ -3,22 +3,22 @@ class Solution { - public int[][] intervalIntersection(int[][] A, int[][] B) { - List ans = new ArrayList(); - int i = 0, j = 0; + public int[][] intervalIntersection(int[][] A, int[][] B) { + List ans = new ArrayList(); + int i = 0, j = 0; - while (i < A.length && j < B.length) { - // Let's check if A[i] intersects B[j]. - // lo - the startpoint of the intersection - // hi - the endpoint of the intersection - int lo = Math.max(A[i][0], B[j][0]); - int hi = Math.min(A[i][1], B[j][1]); - if (lo <= hi) ans.add(new int[] { lo, hi }); + while (i < A.length && j < B.length) { + // Let's check if A[i] intersects B[j]. + // lo - the startpoint of the intersection + // hi - the endpoint of the intersection + int lo = Math.max(A[i][0], B[j][0]); + int hi = Math.min(A[i][1], B[j][1]); + if (lo <= hi) ans.add(new int[] { lo, hi }); - // Remove the interval with the smallest endpoint - if (A[i][1] < B[j][1]) i++; else j++; - } + // Remove the interval with the smallest endpoint + if (A[i][1] < B[j][1]) i++; else j++; + } - return ans.toArray(new int[ans.size()][]); - } + return ans.toArray(new int[ans.size()][]); + } } diff --git a/java/994-Rotting-Oranges.java b/java/994-Rotting-Oranges.java index 39a778b2c..940316996 100644 --- a/java/994-Rotting-Oranges.java +++ b/java/994-Rotting-Oranges.java @@ -1,36 +1,36 @@ class Solution { - public int orangesRotting(int[][] grid) { - int m = grid.length, n = grid[0].length; - Queue queue = new LinkedList<>(); - int fresh = 0; + public int orangesRotting(int[][] grid) { + int m = grid.length, n = grid[0].length; + Queue queue = new LinkedList<>(); + int fresh = 0; - for (int i = 0; i < m; i += 1) { - for (int j = 0; j < n; j += 1) { - if (grid[i][j] == 2) queue.offer(new int[] { i, j }); else if ( - grid[i][j] == 1 - ) fresh += 1; - } - } + for (int i = 0; i < m; i += 1) { + for (int j = 0; j < n; j += 1) { + if (grid[i][j] == 2) queue.offer(new int[] { i, j }); else if ( + grid[i][j] == 1 + ) fresh += 1; + } + } - int count = 0; - int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } }; - while (!queue.isEmpty() && fresh != 0) { - count += 1; - int sz = queue.size(); - for (int i = 0; i < sz; i += 1) { - int[] rotten = queue.poll(); - int r = rotten[0], c = rotten[1]; - for (int[] dir : dirs) { - int x = r + dir[0], y = c + dir[1]; - if (0 <= x && x < m && 0 <= y && y < n && grid[x][y] == 1) { - grid[x][y] = 2; - queue.offer(new int[] { x, y }); - fresh -= 1; - } + int count = 0; + int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } }; + while (!queue.isEmpty() && fresh != 0) { + count += 1; + int sz = queue.size(); + for (int i = 0; i < sz; i += 1) { + int[] rotten = queue.poll(); + int r = rotten[0], c = rotten[1]; + for (int[] dir : dirs) { + int x = r + dir[0], y = c + dir[1]; + if (0 <= x && x < m && 0 <= y && y < n && grid[x][y] == 1) { + grid[x][y] = 2; + queue.offer(new int[] { x, y }); + fresh -= 1; + } + } + } } - } + return fresh == 0 ? count : -1; } - return fresh == 0 ? count : -1; - } } diff --git a/javascript/1-Two-Sum.js b/javascript/1-Two-Sum.js index a40f78506..1f5456c03 100644 --- a/javascript/1-Two-Sum.js +++ b/javascript/1-Two-Sum.js @@ -4,12 +4,12 @@ * @return {number[]} */ var twoSum = function (nums, target) { - let map = {}; - for (let i = 0; i < nums.length; i++) { - if (target - nums[i] in map) { - return [map[target - nums[i]], i]; - } else { - map[nums[i]] = i; + let map = {}; + for (let i = 0; i < nums.length; i++) { + if (target - nums[i] in map) { + return [map[target - nums[i]], i]; + } else { + map[nums[i]] = i; + } } - } }; diff --git a/javascript/100-Same-Tree.js b/javascript/100-Same-Tree.js index e129eeb95..d313fcda0 100644 --- a/javascript/100-Same-Tree.js +++ b/javascript/100-Same-Tree.js @@ -12,7 +12,7 @@ * @return {boolean} */ var isSameTree = function (p, q) { - if (!p && !q) return true; - if (!p || !q || p.val !== q.val) return false; - return isSameTree(p.right, q.right) && isSameTree(p.left, q.left); + if (!p && !q) return true; + if (!p || !q || p.val !== q.val) return false; + return isSameTree(p.right, q.right) && isSameTree(p.left, q.left); }; diff --git a/javascript/102-Binary-Tree-Level-Order-Traversal.js b/javascript/102-Binary-Tree-Level-Order-Traversal.js index cb8dabd72..82749f618 100644 --- a/javascript/102-Binary-Tree-Level-Order-Traversal.js +++ b/javascript/102-Binary-Tree-Level-Order-Traversal.js @@ -11,22 +11,22 @@ * @return {number[][]} */ var levelOrder = function (root) { - if (!root) return []; + if (!root) return []; - const result = []; - const queue = [root]; + const result = []; + const queue = [root]; - while (queue.length) { - const numNodes = queue.length; - const temp = []; - for (let i = 0; i < numNodes; i++) { - const subtree = queue.shift(); - temp.push(subtree.val); - if (subtree.left !== null) queue.push(subtree.left); - if (subtree.right !== null) queue.push(subtree.right); + while (queue.length) { + const numNodes = queue.length; + const temp = []; + for (let i = 0; i < numNodes; i++) { + const subtree = queue.shift(); + temp.push(subtree.val); + if (subtree.left !== null) queue.push(subtree.left); + if (subtree.right !== null) queue.push(subtree.right); + } + result.push(temp); } - result.push(temp); - } - return result; + return result; }; diff --git a/javascript/104-Maximum-Depth-of-Binary-Tree.js b/javascript/104-Maximum-Depth-of-Binary-Tree.js index ab6008f57..276b51048 100644 --- a/javascript/104-Maximum-Depth-of-Binary-Tree.js +++ b/javascript/104-Maximum-Depth-of-Binary-Tree.js @@ -11,13 +11,13 @@ * @return {number} */ var maxDepth = (root) => { - let maxDepth = 0; - let DFS = (node, depth) => { - if (!node) return maxDepth; - if (depth > maxDepth) maxDepth = depth; - DFS(node.right, depth + 1); - DFS(node.left, depth + 1); - }; - DFS(root, 1); - return maxDepth; + let maxDepth = 0; + let DFS = (node, depth) => { + if (!node) return maxDepth; + if (depth > maxDepth) maxDepth = depth; + DFS(node.right, depth + 1); + DFS(node.left, depth + 1); + }; + DFS(root, 1); + return maxDepth; }; diff --git a/javascript/1046-Last-Stone-Weight.js b/javascript/1046-Last-Stone-Weight.js index 5c8e3ff69..fb3c12cc9 100644 --- a/javascript/1046-Last-Stone-Weight.js +++ b/javascript/1046-Last-Stone-Weight.js @@ -1,73 +1,73 @@ class Heap { - constructor(stones) { - this.heap = stones; - this.size = stones.length; - this.heapify(0); - } - right(pos) { - return 2 * pos + 2; - } - left(pos) { - return 2 * pos + 1; - } - isleaf(pos) { - if (2 * pos + 1 >= this.size) return true; - return false; - } - swap(a, b) { - let temp = this.heap[a]; - this.heap[a] = this.heap[b]; - this.heap[b] = temp; - } - fix(pos) { - if (this.isleaf(pos)) return; - let left = this.left(pos); - let right = this.right(pos); - let bigger = left; - if (right < this.size) - bigger = this.heap[left] > this.heap[right] ? left : right; - if (this.heap[pos] < this.heap[bigger]) { - this.swap(pos, bigger); - this.fix(bigger); + constructor(stones) { + this.heap = stones; + this.size = stones.length; + this.heapify(0); + } + right(pos) { + return 2 * pos + 2; + } + left(pos) { + return 2 * pos + 1; + } + isleaf(pos) { + if (2 * pos + 1 >= this.size) return true; + return false; + } + swap(a, b) { + let temp = this.heap[a]; + this.heap[a] = this.heap[b]; + this.heap[b] = temp; + } + fix(pos) { + if (this.isleaf(pos)) return; + let left = this.left(pos); + let right = this.right(pos); + let bigger = left; + if (right < this.size) + bigger = this.heap[left] > this.heap[right] ? left : right; + if (this.heap[pos] < this.heap[bigger]) { + this.swap(pos, bigger); + this.fix(bigger); + } + } + heapify(pos) { + if (this.isleaf(pos)) return; + this.heapify(this.left(pos)); + this.heapify(this.right(pos)); + this.fix(pos); + } + delete() { + this.swap(0, --this.size); + this.fix(0); + return this.heap[0]; + } + insert(val) { + this.size++; + this.heap[this.size - 1] = val; + this.heapify(0); + } + peek() { + return this.heap[0]; } - } - heapify(pos) { - if (this.isleaf(pos)) return; - this.heapify(this.left(pos)); - this.heapify(this.right(pos)); - this.fix(pos); - } - delete() { - this.swap(0, --this.size); - this.fix(0); - return this.heap[0]; - } - insert(val) { - this.size++; - this.heap[this.size - 1] = val; - this.heapify(0); - } - peek() { - return this.heap[0]; - } } /** * @param {number[]} stones * @return {number} */ var lastStoneWeight = function (stones) { - //use a max heap to pop off the top 2 stones at each time - //if result is 0 we can do nothing - //if the result is a new weight we can push it back to the heap - const heap = new Heap(stones); - while (heap.size > 1) { - let x = heap.peek(); - heap.delete(); - let y = heap.peek(); - heap.delete(); - const res = x - y; - if (res > 0) heap.insert(res); - } - if (heap.size) return heap.peek(); - return 0; + //use a max heap to pop off the top 2 stones at each time + //if result is 0 we can do nothing + //if the result is a new weight we can push it back to the heap + const heap = new Heap(stones); + while (heap.size > 1) { + let x = heap.peek(); + heap.delete(); + let y = heap.peek(); + heap.delete(); + const res = x - y; + if (res > 0) heap.insert(res); + } + if (heap.size) return heap.peek(); + return 0; }; diff --git a/javascript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js b/javascript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js index 39865660f..e37b0639b 100644 --- a/javascript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js +++ b/javascript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js @@ -1,10 +1,10 @@ function buildTree(preorder, inorder) { - if (!preorder.length || !inorder.length) return null; + if (!preorder.length || !inorder.length) return null; - let root = new TreeNode(preorder[0]); - let mid = inorder.indexOf(preorder[0]); + let root = new TreeNode(preorder[0]); + let mid = inorder.indexOf(preorder[0]); - root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid)); - root.right = buildTree(preorder.slice(mid + 1), inorder.slice(mid + 1)); - return root; + root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid)); + root.right = buildTree(preorder.slice(mid + 1), inorder.slice(mid + 1)); + return root; } diff --git a/javascript/11-Container-With-Most-Water.js b/javascript/11-Container-With-Most-Water.js index 99c9fd507..a40cc43e6 100644 --- a/javascript/11-Container-With-Most-Water.js +++ b/javascript/11-Container-With-Most-Water.js @@ -3,18 +3,18 @@ * @return {number} */ var maxArea = function (height) { - let max = 0; - let i = 0; - let j = height.length - 1; + let max = 0; + let i = 0; + let j = height.length - 1; - while (i < j) { - const curr = (j - i) * Math.min(height[i], height[j]); - max = Math.max(curr, max); - if (height[i] > height[j]) { - j--; - } else { - i++; + while (i < j) { + const curr = (j - i) * Math.min(height[i], height[j]); + max = Math.max(curr, max); + if (height[i] > height[j]) { + j--; + } else { + i++; + } } - } - return max; + return max; }; diff --git a/javascript/110-Balanced-Binary-Tree.js b/javascript/110-Balanced-Binary-Tree.js index 0e7058857..1cefe4183 100644 --- a/javascript/110-Balanced-Binary-Tree.js +++ b/javascript/110-Balanced-Binary-Tree.js @@ -11,19 +11,21 @@ * @return {boolean} */ var isBalanced = function (root) { - const getHeight = (root) => { - if (!root) return [-1, true]; + const getHeight = (root) => { + if (!root) return [-1, true]; - const [leftHeight, leftBalanced] = getHeight(root.left); - const [rightHeight, rightBalanced] = getHeight(root.right); + const [leftHeight, leftBalanced] = getHeight(root.left); + const [rightHeight, rightBalanced] = getHeight(root.right); - const balanced = - leftBalanced && rightBalanced && Math.abs(leftHeight - rightHeight) < 2; + const balanced = + leftBalanced && + rightBalanced && + Math.abs(leftHeight - rightHeight) < 2; - return [1 + Math.max(leftHeight, rightHeight), balanced]; - }; + return [1 + Math.max(leftHeight, rightHeight), balanced]; + }; - const balanced = getHeight(root)[1]; + const balanced = getHeight(root)[1]; - return balanced; + return balanced; }; diff --git a/javascript/1143-Longest-Common-Subsequence.js b/javascript/1143-Longest-Common-Subsequence.js index 0a417ef46..a651aebea 100644 --- a/javascript/1143-Longest-Common-Subsequence.js +++ b/javascript/1143-Longest-Common-Subsequence.js @@ -1,16 +1,16 @@ var longestCommonSubsequence = function (text1, text2) { - let m = text1.length, - n = text2.length, - DP = new Array(m + 1).fill(0).map((_) => new Array(n + 1).fill(0)); + let m = text1.length, + n = text2.length, + DP = new Array(m + 1).fill(0).map((_) => new Array(n + 1).fill(0)); - for (let x = m - 1; x >= 0; x--) - for (let y = n - 1; y >= 0; y--) { - if (text1[x] === text2[y]) { - DP[x][y] = 1 + DP[x + 1][y + 1]; - } else { - DP[x][y] = Math.max(DP[x + 1][y], DP[x][y + 1]); - } - } + for (let x = m - 1; x >= 0; x--) + for (let y = n - 1; y >= 0; y--) { + if (text1[x] === text2[y]) { + DP[x][y] = 1 + DP[x + 1][y + 1]; + } else { + DP[x][y] = Math.max(DP[x + 1][y], DP[x][y + 1]); + } + } - return DP[0][0]; + return DP[0][0]; }; diff --git a/javascript/115-Distinct-Subsequences.js b/javascript/115-Distinct-Subsequences.js index bdbfda31e..8a23d796f 100644 --- a/javascript/115-Distinct-Subsequences.js +++ b/javascript/115-Distinct-Subsequences.js @@ -10,27 +10,27 @@ * @return {number} */ function numDistinct(s, t) { - const sLen = s.length; - const tLen = t.length; - - if (sLen < tLen) { - return 0; - } - - const cache = new Array(tLen).fill(0); - - for (let r = sLen - 1; r >= 0; --r) { - let prev = 1; - for (let c = tLen - 1; c >= 0; --c) { - const curr = cache[c]; - if (s[r] === t[c]) { - cache[c] += prev; - } - prev = curr; + const sLen = s.length; + const tLen = t.length; + + if (sLen < tLen) { + return 0; + } + + const cache = new Array(tLen).fill(0); + + for (let r = sLen - 1; r >= 0; --r) { + let prev = 1; + for (let c = tLen - 1; c >= 0; --c) { + const curr = cache[c]; + if (s[r] === t[c]) { + cache[c] += prev; + } + prev = curr; + } } - } - return cache[0]; + return cache[0]; } ////////////////////////////////////////////////////////////////////////////// @@ -45,27 +45,28 @@ function numDistinct(s, t) { * @return {number} */ function numDistinct(s, t) { - const sLen = s.length; - const tLen = t.length; + const sLen = s.length; + const tLen = t.length; - if (sLen < tLen) { - return 0; - } + if (sLen < tLen) { + return 0; + } - const cache = new Array(sLen + 1).fill().map(() => new Array(tLen + 1)); + const cache = new Array(sLen + 1).fill().map(() => new Array(tLen + 1)); - cache[sLen].fill(0); - for (let r = 0; r <= sLen; ++r) { - cache[r][tLen] = 1; - } + cache[sLen].fill(0); + for (let r = 0; r <= sLen; ++r) { + cache[r][tLen] = 1; + } - for (let r = sLen - 1; r >= 0; --r) { - for (let c = tLen - 1; c >= 0; --c) { - cache[r][c] = cache[r + 1][c] + (s[r] === t[c] ? cache[r + 1][c + 1] : 0); + for (let r = sLen - 1; r >= 0; --r) { + for (let c = tLen - 1; c >= 0; --c) { + cache[r][c] = + cache[r + 1][c] + (s[r] === t[c] ? cache[r + 1][c + 1] : 0); + } } - } - return cache[0][0]; + return cache[0][0]; } ////////////////////////////////////////////////////////////////////////////// @@ -80,31 +81,31 @@ function numDistinct(s, t) { * @return {number} */ function numDistinct(s, t) { - const sLen = s.length; - const tLen = t.length; - - if (sLen < tLen) { - return 0; - } - - const cache = new Array(sLen).fill().map(() => new Array(tLen)); - - return countDistincts(); - - /** - * @param {number=} i = `0` - * @param {number=} j = `0` - * @return {number} - */ - function countDistincts(i = 0, j = 0) { - return j === tLen - ? 1 - : i === sLen - ? 0 - : cache[i][j] !== undefined - ? cache[i][j] - : (cache[i][j] = - countDistincts(i + 1, j) + - (s[i] === t[j] ? countDistincts(i + 1, j + 1) : 0)); - } + const sLen = s.length; + const tLen = t.length; + + if (sLen < tLen) { + return 0; + } + + const cache = new Array(sLen).fill().map(() => new Array(tLen)); + + return countDistincts(); + + /** + * @param {number=} i = `0` + * @param {number=} j = `0` + * @return {number} + */ + function countDistincts(i = 0, j = 0) { + return j === tLen + ? 1 + : i === sLen + ? 0 + : cache[i][j] !== undefined + ? cache[i][j] + : (cache[i][j] = + countDistincts(i + 1, j) + + (s[i] === t[j] ? countDistincts(i + 1, j + 1) : 0)); + } } diff --git a/javascript/1209-Remove-All-Adjacent-Duplicates-in-String-II.js b/javascript/1209-Remove-All-Adjacent-Duplicates-in-String-II.js index 92d350707..00d0cefb7 100644 --- a/javascript/1209-Remove-All-Adjacent-Duplicates-in-String-II.js +++ b/javascript/1209-Remove-All-Adjacent-Duplicates-in-String-II.js @@ -4,19 +4,19 @@ * @return {string} */ var removeDuplicates = function (s, k) { - const stack = []; // [char, count]; + const stack = []; // [char, count]; - for (const c of s) { - if (stack.length !== 0 && stack[stack.length - 1][0] === c) { - stack[stack.length - 1][1]++; - } else { - stack.push([c, 1]); - } + for (const c of s) { + if (stack.length !== 0 && stack[stack.length - 1][0] === c) { + stack[stack.length - 1][1]++; + } else { + stack.push([c, 1]); + } - if (stack[stack.length - 1][1] === k) { - stack.pop(); + if (stack[stack.length - 1][1] === k) { + stack.pop(); + } } - } - return stack.reduce((res, el) => (res += el[0].repeat(el[1])), ''); + return stack.reduce((res, el) => (res += el[0].repeat(el[1])), ''); }; diff --git a/javascript/121-Best-Time-to-Buy-and-Sell-Stock.js b/javascript/121-Best-Time-to-Buy-and-Sell-Stock.js index a42e3331b..176acde87 100644 --- a/javascript/121-Best-Time-to-Buy-and-Sell-Stock.js +++ b/javascript/121-Best-Time-to-Buy-and-Sell-Stock.js @@ -3,14 +3,14 @@ * @return {number} */ var maxProfit = function (prices) { - let buy = prices[0]; - let profit = 0; - for (let i = 0; i < prices.length; i++) { - if (prices[i] < buy) { - buy = prices[i]; - } else { - profit = Math.max(prices[i] - buy, profit); + let buy = prices[0]; + let profit = 0; + for (let i = 0; i < prices.length; i++) { + if (prices[i] < buy) { + buy = prices[i]; + } else { + profit = Math.max(prices[i] - buy, profit); + } } - } - return profit; + return profit; }; diff --git a/javascript/124-Binary-Tree-Maximum-Path-Sum.js b/javascript/124-Binary-Tree-Maximum-Path-Sum.js index 284ac6755..75346df77 100644 --- a/javascript/124-Binary-Tree-Maximum-Path-Sum.js +++ b/javascript/124-Binary-Tree-Maximum-Path-Sum.js @@ -11,25 +11,25 @@ * @return {number} */ var maxPathSum = function (root) { - const res = [root.val]; + const res = [root.val]; - // return max path sum without split - function dfs(root) { - if (!root) { - return 0; - } + // return max path sum without split + function dfs(root) { + if (!root) { + return 0; + } - let leftMax = dfs(root.left); - let rightMax = dfs(root.right); - leftMax = Math.max(leftMax, 0); - rightMax = Math.max(rightMax, 0); + let leftMax = dfs(root.left); + let rightMax = dfs(root.right); + leftMax = Math.max(leftMax, 0); + rightMax = Math.max(rightMax, 0); - // compute max path sum WITH split - res[0] = Math.max(res[0], root.val + leftMax + rightMax); + // compute max path sum WITH split + res[0] = Math.max(res[0], root.val + leftMax + rightMax); - return root.val + Math.max(leftMax, rightMax); - } + return root.val + Math.max(leftMax, rightMax); + } - dfs(root); - return res[0]; + dfs(root); + return res[0]; }; diff --git a/javascript/125-Valid-Palindrome.js b/javascript/125-Valid-Palindrome.js index ee2094687..45913dc19 100644 --- a/javascript/125-Valid-Palindrome.js +++ b/javascript/125-Valid-Palindrome.js @@ -1,24 +1,24 @@ const ALPHA_NUM = /^[a-zA-Z0-9]$/; function isPalindrome(s) { - let l = 0; - let r = s.length - 1; + let l = 0; + let r = s.length - 1; - while (l < r) { - while (l < r && !ALPHA_NUM.test(s[l])) { - l++; - } - while (l < r && !ALPHA_NUM.test(s[r])) { - r--; - } + while (l < r) { + while (l < r && !ALPHA_NUM.test(s[l])) { + l++; + } + while (l < r && !ALPHA_NUM.test(s[r])) { + r--; + } - if (s[l].toLowerCase() !== s[r].toLowerCase()) { - return false; - } + if (s[l].toLowerCase() !== s[r].toLowerCase()) { + return false; + } - l++; - r--; - } + l++; + r--; + } - return true; + return true; } diff --git a/javascript/127-Word-Ladder.js b/javascript/127-Word-Ladder.js index 1228fcd38..996238259 100644 --- a/javascript/127-Word-Ladder.js +++ b/javascript/127-Word-Ladder.js @@ -1,34 +1,34 @@ var ladderLength = function (beginWord, endWord, wordList) { - if (!wordList.includes(endWord)) return 0; - let patternMap = {}; - wordList.push(beginWord); + if (!wordList.includes(endWord)) return 0; + let patternMap = {}; + wordList.push(beginWord); - for (let word of wordList) { - for (let x = 0; x < word.length; x++) { - const pattern = word.slice(0, x) + '*' + word.slice(x + 1); - patternMap[pattern] = patternMap[pattern] || []; - patternMap[pattern].push(word); + for (let word of wordList) { + for (let x = 0; x < word.length; x++) { + const pattern = word.slice(0, x) + '*' + word.slice(x + 1); + patternMap[pattern] = patternMap[pattern] || []; + patternMap[pattern].push(word); + } } - } - let wordCount = 1, - queue = [beginWord], - visited = [beginWord]; - while (queue.length) { - const levelSize = queue.length; - for (let x = 0; x < levelSize; x++) { - const word = queue.shift(); - if (word === endWord) return wordCount; - for (let x = 0; x < word.length; x++) { - const pattern = word.slice(0, x) + '*' + word.slice(x + 1); - for (let nei of patternMap[pattern]) { - if (nei in visited) continue; - visited[nei] = true; - queue.push(nei); + let wordCount = 1, + queue = [beginWord], + visited = [beginWord]; + while (queue.length) { + const levelSize = queue.length; + for (let x = 0; x < levelSize; x++) { + const word = queue.shift(); + if (word === endWord) return wordCount; + for (let x = 0; x < word.length; x++) { + const pattern = word.slice(0, x) + '*' + word.slice(x + 1); + for (let nei of patternMap[pattern]) { + if (nei in visited) continue; + visited[nei] = true; + queue.push(nei); + } + } } - } + wordCount += 1; } - wordCount += 1; - } - return 0; + return 0; }; diff --git a/javascript/128-Longest-consecutive-sequence.js b/javascript/128-Longest-consecutive-sequence.js index 10c47ad1d..7fb5cdc20 100644 --- a/javascript/128-Longest-consecutive-sequence.js +++ b/javascript/128-Longest-consecutive-sequence.js @@ -11,40 +11,40 @@ * @return {number} */ function longestConsecutive(nums) { - if (!nums.length) { - return 0; - } + if (!nums.length) { + return 0; + } - const map = Object.create(null); - let max = 0; + const map = Object.create(null); + let max = 0; - for (const num of nums) { - if (num in map) { - continue; - } + for (const num of nums) { + if (num in map) { + continue; + } - const prev = num - 1; - const next = num + 1; - let len = 1; + const prev = num - 1; + const next = num + 1; + let len = 1; - if (prev in map) { - if (next in map) { - len += map[prev] + map[next]; - map[prev - map[prev] + 1] = len; - map[next + map[next] - 1] = len; - } else { - len += map[prev]; - ++map[prev - map[prev] + 1]; - } - } else if (next in map) { - len += map[next]; - ++map[next + map[next] - 1]; + if (prev in map) { + if (next in map) { + len += map[prev] + map[next]; + map[prev - map[prev] + 1] = len; + map[next + map[next] - 1] = len; + } else { + len += map[prev]; + ++map[prev - map[prev] + 1]; + } + } else if (next in map) { + len += map[next]; + ++map[next + map[next] - 1]; + } + map[num] = len; + max = Math.max(max, len); } - map[num] = len; - max = Math.max(max, len); - } - return max; + return max; } ////////////////////////////////////////////////////////////////////////////// @@ -63,25 +63,25 @@ function longestConsecutive(nums) { * @return {number} */ function longestConsecutive(nums) { - const set = new Set(nums); - let max = 0; + const set = new Set(nums); + let max = 0; - for (let i = 0; i < nums.length; i++) { - const num = nums[i]; + for (let i = 0; i < nums.length; i++) { + const num = nums[i]; - if (set.has(num - 1)) { - continue; - } + if (set.has(num - 1)) { + continue; + } - let currentMax = 1; - while (set.has(num + currentMax)) { - currentMax++; - } + let currentMax = 1; + while (set.has(num + currentMax)) { + currentMax++; + } - if (currentMax > max) { - max = currentMax; + if (currentMax > max) { + max = currentMax; + } } - } - return max; + return max; } diff --git a/javascript/13-Roman-to-Integer.js b/javascript/13-Roman-to-Integer.js index a16bc3ee2..2ff8162c9 100644 --- a/javascript/13-Roman-to-Integer.js +++ b/javascript/13-Roman-to-Integer.js @@ -3,62 +3,62 @@ * @return {number} */ var romanToInt = function (s) { - let romans = { - I: 1, - V: 5, - X: 10, - L: 50, - C: 100, - D: 500, - M: 1000, - }; + let romans = { + I: 1, + V: 5, + X: 10, + L: 50, + C: 100, + D: 500, + M: 1000, + }; - let arr = s.split(''); + let arr = s.split(''); - let sum = 0; + let sum = 0; - for (let i = arr.length - 1; i >= 0; i--) { - // IV : 4 - if (romans[arr[i]] === romans['V']) { - if (romans[arr[i - 1]] === romans['I']) { - sum -= 1 * 2; - } - } - // IX : 4 - if (romans[arr[i]] === romans['X']) { - if (romans[arr[i - 1]] === romans['I']) { - sum -= 1 * 2; - } - } - // XL : 40 - if (romans[arr[i]] === romans['L']) { - if (romans[arr[i - 1]] === romans['X']) { - sum -= 10 * 2; - } - } - // XC : 90 - if (romans[arr[i]] === romans['C']) { - if (romans[arr[i - 1]] === romans['X']) { - sum -= 10 * 2; - } - } - // CD : 400 - if (romans[arr[i]] === romans['D']) { - if (romans[arr[i - 1]] === romans['C']) { - sum -= 100 * 2; - } - } - // CM : 900 - if (romans[arr[i]] === romans['M']) { - if (romans[arr[i - 1]] === romans['C']) { - sum -= 100 * 2; - } - } + for (let i = arr.length - 1; i >= 0; i--) { + // IV : 4 + if (romans[arr[i]] === romans['V']) { + if (romans[arr[i - 1]] === romans['I']) { + sum -= 1 * 2; + } + } + // IX : 4 + if (romans[arr[i]] === romans['X']) { + if (romans[arr[i - 1]] === romans['I']) { + sum -= 1 * 2; + } + } + // XL : 40 + if (romans[arr[i]] === romans['L']) { + if (romans[arr[i - 1]] === romans['X']) { + sum -= 10 * 2; + } + } + // XC : 90 + if (romans[arr[i]] === romans['C']) { + if (romans[arr[i - 1]] === romans['X']) { + sum -= 10 * 2; + } + } + // CD : 400 + if (romans[arr[i]] === romans['D']) { + if (romans[arr[i - 1]] === romans['C']) { + sum -= 100 * 2; + } + } + // CM : 900 + if (romans[arr[i]] === romans['M']) { + if (romans[arr[i - 1]] === romans['C']) { + sum -= 100 * 2; + } + } - sum += romans[arr[i]]; - } + sum += romans[arr[i]]; + } - return sum; + return sum; }; // Runtime: 148 ms, faster than 80.16% of JavaScript online submissions for Roman to Integer. diff --git a/javascript/130-Surrounded-Regions.js b/javascript/130-Surrounded-Regions.js index 07af00cf3..420cfe91a 100644 --- a/javascript/130-Surrounded-Regions.js +++ b/javascript/130-Surrounded-Regions.js @@ -12,57 +12,57 @@ * @return {void} Do not return anything, modify board in-place instead. */ function solve(board) { - const rowLen = board.length; - const colLen = board[0].length; - const lastRow = rowLen - 1; - const lastCol = colLen - 1; + const rowLen = board.length; + const colLen = board[0].length; + const lastRow = rowLen - 1; + const lastCol = colLen - 1; - for (let r = 0; r < rowLen; ++r) { - markSeen(r, 0); - markSeen(r, lastCol); - } - for (let c = 1; c < lastCol; ++c) { - markSeen(0, c); - markSeen(lastRow, c); - } - - for (let r = 0; r < rowLen; ++r) { - for (let c = 0; c < colLen; ++c) { - switch (board[r][c]) { - case 'O': - board[r][c] = 'X'; - break; - case 'A': - board[r][c] = 'O'; - break; - } + for (let r = 0; r < rowLen; ++r) { + markSeen(r, 0); + markSeen(r, lastCol); + } + for (let c = 1; c < lastCol; ++c) { + markSeen(0, c); + markSeen(lastRow, c); } - } - /** - * @param {number} r - * @param {number} c - * @return {void} - */ - function markSeen(r, c) { - if (!inBounds(r, c) || board[r][c] !== 'O') { - return; + for (let r = 0; r < rowLen; ++r) { + for (let c = 0; c < colLen; ++c) { + switch (board[r][c]) { + case 'O': + board[r][c] = 'X'; + break; + case 'A': + board[r][c] = 'O'; + break; + } + } } - board[r][c] = 'A'; + /** + * @param {number} r + * @param {number} c + * @return {void} + */ + function markSeen(r, c) { + if (!inBounds(r, c) || board[r][c] !== 'O') { + return; + } - markSeen(r - 1, c); - markSeen(r + 1, c); - markSeen(r, c - 1); - markSeen(r, c + 1); - } + board[r][c] = 'A'; - /** - * @param {number} r - * @param {number} c - * @return {boolean} - */ - function inBounds(r, c) { - return r >= 0 && c >= 0 && r < rowLen && c < colLen; - } + markSeen(r - 1, c); + markSeen(r + 1, c); + markSeen(r, c - 1); + markSeen(r, c + 1); + } + + /** + * @param {number} r + * @param {number} c + * @return {boolean} + */ + function inBounds(r, c) { + return r >= 0 && c >= 0 && r < rowLen && c < colLen; + } } diff --git a/javascript/131-Palindrome-Partitioning.js b/javascript/131-Palindrome-Partitioning.js index 514eec049..2509aa42f 100644 --- a/javascript/131-Palindrome-Partitioning.js +++ b/javascript/131-Palindrome-Partitioning.js @@ -1,33 +1,33 @@ function partition(s) { - let res = []; - let part = []; + let res = []; + let part = []; - function dfs(i) { - if (i >= s.length) { - res.push(part.slice()); - return; - } + function dfs(i) { + if (i >= s.length) { + res.push(part.slice()); + return; + } - for (let j = i; j < s.length; j++) { - if (isPali(s, i, j)) { - part.push(s.slice(i, j + 1)); - dfs(j + 1); - part.pop(); - } + for (let j = i; j < s.length; j++) { + if (isPali(s, i, j)) { + part.push(s.slice(i, j + 1)); + dfs(j + 1); + part.pop(); + } + } } - } - dfs(0); - return res; + dfs(0); + return res; - function isPali(s, l, r) { - while (l < r) { - if (s[l] != s[r]) { - return false; - } - l = l + 1; - r = r - 1; + function isPali(s, l, r) { + while (l < r) { + if (s[l] != s[r]) { + return false; + } + l = l + 1; + r = r - 1; + } + return true; } - return true; - } } diff --git a/javascript/133-Clone-Graph.js b/javascript/133-Clone-Graph.js index ad48ee387..817f76df0 100644 --- a/javascript/133-Clone-Graph.js +++ b/javascript/133-Clone-Graph.js @@ -11,27 +11,27 @@ * @return {Node} */ var cloneGraph = function (node) { - let visited = {}; + let visited = {}; - let dfs = (node) => { - if (!node) { - return node; - } + let dfs = (node) => { + if (!node) { + return node; + } - if (visited[node.val]) { - return visited[node.val]; - } + if (visited[node.val]) { + return visited[node.val]; + } - let copy = new Node(node.val); + let copy = new Node(node.val); - visited[node.val] = copy; + visited[node.val] = copy; - node.neighbors.forEach((n) => { - copy.neighbors.push(dfs(n)); - }); + node.neighbors.forEach((n) => { + copy.neighbors.push(dfs(n)); + }); - return copy; - }; + return copy; + }; - return dfs(node); + return dfs(node); }; diff --git a/javascript/136-Single-Number.js b/javascript/136-Single-Number.js index ae902b535..13635bcca 100644 --- a/javascript/136-Single-Number.js +++ b/javascript/136-Single-Number.js @@ -3,9 +3,9 @@ * @return {number} */ var singleNumber = function (nums) { - let xor_final = 0; - for (num of nums) { - xor_final = xor_final ^ num; - } - return xor_final; + let xor_final = 0; + for (num of nums) { + xor_final = xor_final ^ num; + } + return xor_final; }; diff --git a/javascript/138-Copy-List-with-Random-Pointer.js b/javascript/138-Copy-List-with-Random-Pointer.js index dc6e30b17..103ef9661 100644 --- a/javascript/138-Copy-List-with-Random-Pointer.js +++ b/javascript/138-Copy-List-with-Random-Pointer.js @@ -3,18 +3,18 @@ * @return {Node} */ var copyRandomList = function (head) { - let map = new Map(); - let ptr = head; + let map = new Map(); + let ptr = head; - while (ptr) { - // map old - new - map.set(ptr, new Node(ptr.val, null, null)); - ptr = ptr.next; - } + while (ptr) { + // map old - new + map.set(ptr, new Node(ptr.val, null, null)); + ptr = ptr.next; + } - for (const [oldptr, newptr] of map) { - newptr.next = oldptr.next && map.get(oldptr.next); - newptr.random = oldptr.random && map.get(oldptr.random); - } - return map.get(head); + for (const [oldptr, newptr] of map) { + newptr.next = oldptr.next && map.get(oldptr.next); + newptr.random = oldptr.random && map.get(oldptr.random); + } + return map.get(head); }; diff --git a/javascript/139-Word-Break.js b/javascript/139-Word-Break.js index fa5be4fcd..dc7589d9b 100644 --- a/javascript/139-Word-Break.js +++ b/javascript/139-Word-Break.js @@ -1,19 +1,19 @@ let wordBreak = function (s, wordDict) { - let dp = new Array(s.length + 1); - dp.fill(false); - dp[s.length] = true; + let dp = new Array(s.length + 1); + dp.fill(false); + dp[s.length] = true; - let word = ''; - for (let i = s.length - 1; i >= 0; i--) { - word = s[i] + word; + let word = ''; + for (let i = s.length - 1; i >= 0; i--) { + word = s[i] + word; - if (wordDict.includes(word) && i + word.length < dp.length) { - dp[i] = dp[i + word.length]; - word = ''; - } else { - dp[i] = false; + if (wordDict.includes(word) && i + word.length < dp.length) { + dp[i] = dp[i + word.length]; + word = ''; + } else { + dp[i] = false; + } } - } - return dp[0]; + return dp[0]; }; diff --git a/javascript/141-Linked-List-Cycle.js b/javascript/141-Linked-List-Cycle.js index 419f7b704..eb4649349 100644 --- a/javascript/141-Linked-List-Cycle.js +++ b/javascript/141-Linked-List-Cycle.js @@ -11,15 +11,15 @@ * @return {boolean} */ var hasCycle = function (head) { - let set = new Set(); - while (head) { - if (set.has(head)) { - return true; - } else { - set.add(head); - head = head.next; + let set = new Set(); + while (head) { + if (set.has(head)) { + return true; + } else { + set.add(head); + head = head.next; + } } - } - return false; + return false; }; diff --git a/javascript/143-Reorder-List.js b/javascript/143-Reorder-List.js index b7aee4677..e7caa42a1 100644 --- a/javascript/143-Reorder-List.js +++ b/javascript/143-Reorder-List.js @@ -10,40 +10,40 @@ * @return {void} Do not return anything, modify head in-place instead. */ var reorderList = function (head) { - if (!head) { - return; - } + if (!head) { + return; + } - let slow = head; - let fast = head; + let slow = head; + let fast = head; - // finding the middle of the linked list using 2 pters - while (fast && fast.next) { - slow = slow.next; - fast = fast.next.next; - } + // finding the middle of the linked list using 2 pters + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } - // reverse the second part of the list starting at slow - let prev = null; - let curr = slow; - while (curr) { - let next = curr.next; - curr.next = prev; - prev = curr; - curr = next; - } // here prev is the head + // reverse the second part of the list starting at slow + let prev = null; + let curr = slow; + while (curr) { + let next = curr.next; + curr.next = prev; + prev = curr; + curr = next; + } // here prev is the head - // merge two sorted lists (first one starts at head, second at prev) - let first = head; - let second = prev; + // merge two sorted lists (first one starts at head, second at prev) + let first = head; + let second = prev; - while (second.next) { - temp = first.next; - first.next = second; - first = temp; + while (second.next) { + temp = first.next; + first.next = second; + first = temp; - temp = second.next; - second.next = first; - second = temp; - } + temp = second.next; + second.next = first; + second = temp; + } }; diff --git a/javascript/1448-Count-Good-Nodes-in-Binary-Tree.js b/javascript/1448-Count-Good-Nodes-in-Binary-Tree.js index fb11fbe32..990f08607 100644 --- a/javascript/1448-Count-Good-Nodes-in-Binary-Tree.js +++ b/javascript/1448-Count-Good-Nodes-in-Binary-Tree.js @@ -1,20 +1,20 @@ function goodNodes(root) { - let total = 0; + let total = 0; - function traverse(node, prev) { - if (!node) return; + function traverse(node, prev) { + if (!node) return; - if (node.left || node.right) { - traverse(node.left, Math.max(node.val, prev)); - traverse(node.right, Math.max(node.val, prev)); - } + if (node.left || node.right) { + traverse(node.left, Math.max(node.val, prev)); + traverse(node.right, Math.max(node.val, prev)); + } - if (node.val >= prev) { - total += 1; + if (node.val >= prev) { + total += 1; + } } - } - traverse(root, root.val); + traverse(root, root.val); - return total; + return total; } diff --git a/javascript/146-LRU-Cache.js b/javascript/146-LRU-Cache.js index ea4e09d6c..0e74544ed 100644 --- a/javascript/146-LRU-Cache.js +++ b/javascript/146-LRU-Cache.js @@ -9,8 +9,8 @@ * @param {number} capacity */ function LRUCache(capacity) { - this.capacity = capacity; - this.cacheMap = new Map(); + this.capacity = capacity; + this.cacheMap = new Map(); } /** @@ -18,13 +18,13 @@ function LRUCache(capacity) { * @return {number} */ LRUCache.prototype.get = function (key) { - if (!this.cacheMap.has(key)) { - return -1; - } - const value = this.cacheMap.get(key); - this.cacheMap.delete(key); - this.cacheMap.set(key, value); - return value; + if (!this.cacheMap.has(key)) { + return -1; + } + const value = this.cacheMap.get(key); + this.cacheMap.delete(key); + this.cacheMap.set(key, value); + return value; }; /** @@ -33,13 +33,13 @@ LRUCache.prototype.get = function (key) { * @return {void} */ LRUCache.prototype.put = function (key, value) { - if (this.cacheMap.has(key)) { - this.cacheMap.delete(key); - } else if (this.cacheMap.size === this.capacity) { - const leastRecentlyUsedKey = this.cacheMap.keys().next().value; - this.cacheMap.delete(leastRecentlyUsedKey); - } - this.cacheMap.set(key, value); + if (this.cacheMap.has(key)) { + this.cacheMap.delete(key); + } else if (this.cacheMap.size === this.capacity) { + const leastRecentlyUsedKey = this.cacheMap.keys().next().value; + this.cacheMap.delete(leastRecentlyUsedKey); + } + this.cacheMap.set(key, value); }; ////////////////////////////////////////////////////////////////////////////// @@ -50,106 +50,106 @@ LRUCache.prototype.put = function (key, value) { ////////////////////////////////////////////////////////////////////////////// class LRUNode { - /** - * @param {number} key - * @param {number} val - * @param {LRUNode=} next = `null` - * @constructor - */ - constructor(key, val, next = null) { - this.key = key; - this.val = val; - this.prev = null; - this.next = next; - } + /** + * @param {number} key + * @param {number} val + * @param {LRUNode=} next = `null` + * @constructor + */ + constructor(key, val, next = null) { + this.key = key; + this.val = val; + this.prev = null; + this.next = next; + } } class LRUCache { - /** - * @param {number} capacity - * @constructor - */ - constructor(capacity) { - this.head = null; - this.tail = null; - this.map = Object.create(null); - this.length = 0; - this.capacity = capacity; - } - - /** - * @param {number} key - * @return {number} - */ - get(key) { - if (!(key in this.map)) { - return -1; - } - this.makeMostRecent(key); - return this.map[key].val; - } - - /** - * @param {number} key - * @param {number} val - * @return {void} - */ - put(key, val) { - if (key in this.map) { - this.map[key].val = val; - this.makeMostRecent(key); - return; - } - - if (this.length === this.capacity) { - delete this.map[this.tail.key]; - if (this.head === this.tail) { + /** + * @param {number} capacity + * @constructor + */ + constructor(capacity) { this.head = null; this.tail = null; - } else { - this.tail = this.tail.prev; - this.tail.next = null; - } - } else { - ++this.length; + this.map = Object.create(null); + this.length = 0; + this.capacity = capacity; } - const node = new LRUNode(key, val, this.head); - - if (this.head) { - this.head.prev = node; - } else { - this.tail = node; + /** + * @param {number} key + * @return {number} + */ + get(key) { + if (!(key in this.map)) { + return -1; + } + this.makeMostRecent(key); + return this.map[key].val; } - this.head = node; - - this.map[key] = node; - } - /** - * @param {number} key - * @return {void} - */ - makeMostRecent(key) { - const node = this.map[key]; - - if (node === this.head) { - return node.val; + /** + * @param {number} key + * @param {number} val + * @return {void} + */ + put(key, val) { + if (key in this.map) { + this.map[key].val = val; + this.makeMostRecent(key); + return; + } + + if (this.length === this.capacity) { + delete this.map[this.tail.key]; + if (this.head === this.tail) { + this.head = null; + this.tail = null; + } else { + this.tail = this.tail.prev; + this.tail.next = null; + } + } else { + ++this.length; + } + + const node = new LRUNode(key, val, this.head); + + if (this.head) { + this.head.prev = node; + } else { + this.tail = node; + } + this.head = node; + + this.map[key] = node; } - if (node.prev) { - node.prev.next = node.next; - } - if (node.next) { - node.next.prev = node.prev; + /** + * @param {number} key + * @return {void} + */ + makeMostRecent(key) { + const node = this.map[key]; + + if (node === this.head) { + return node.val; + } + + if (node.prev) { + node.prev.next = node.next; + } + if (node.next) { + node.next.prev = node.prev; + } + if (node === this.tail) { + this.tail = node.prev; + } + + node.prev = null; + node.next = this.head; + this.head.prev = node; + this.head = node; } - if (node === this.tail) { - this.tail = node.prev; - } - - node.prev = null; - node.next = this.head; - this.head.prev = node; - this.head = node; - } } diff --git a/javascript/15-3Sum.js b/javascript/15-3Sum.js index 1d3efff58..a2657556c 100644 --- a/javascript/15-3Sum.js +++ b/javascript/15-3Sum.js @@ -3,41 +3,41 @@ * @return {number[][]} */ var threeSum = function (nums) { - let res = []; - let left = 0; - let right = nums.length - 1; - nums.sort((a, b) => { - return a - b; - }); + let res = []; + let left = 0; + let right = nums.length - 1; + nums.sort((a, b) => { + return a - b; + }); - for (let i = 0; i < nums.length - 1; i++) { - if (nums[i] > 0) return res; - if (nums[i] === nums[i - 1]) continue; + for (let i = 0; i < nums.length - 1; i++) { + if (nums[i] > 0) return res; + if (nums[i] === nums[i - 1]) continue; - left = i + 1; - right = nums.length - 1; - let temp = 0; + left = i + 1; + right = nums.length - 1; + let temp = 0; - while (left < right) { - temp = nums[left] + nums[right] + nums[i]; - if (temp === 0) { - res.push([nums[i], nums[left], nums[right]]); - left++; - right--; + while (left < right) { + temp = nums[left] + nums[right] + nums[i]; + if (temp === 0) { + res.push([nums[i], nums[left], nums[right]]); + left++; + right--; - while (nums[left] == nums[left - 1]) { - left++; - } + while (nums[left] == nums[left - 1]) { + left++; + } - while (nums[right] == nums[right + 1]) { - right--; + while (nums[right] == nums[right + 1]) { + right--; + } + } else if (temp > 0) { + right--; + } else if (temp < 0) { + left++; + } } - } else if (temp > 0) { - right--; - } else if (temp < 0) { - left++; - } } - } - return res; + return res; }; diff --git a/javascript/150-Evaluate-Reverse-Polish-Notation.js b/javascript/150-Evaluate-Reverse-Polish-Notation.js index 2964b411f..201e7839f 100644 --- a/javascript/150-Evaluate-Reverse-Polish-Notation.js +++ b/javascript/150-Evaluate-Reverse-Polish-Notation.js @@ -1,9 +1,9 @@ /** @const {!Object} */ const OPERATORS = { - '+': (a, b) => a + b, - '-': (a, b) => a - b, - '*': (a, b) => a * b, - '/': (a, b) => Math.trunc(a / b), + '+': (a, b) => a + b, + '-': (a, b) => a - b, + '*': (a, b) => a * b, + '/': (a, b) => Math.trunc(a / b), }; /** @@ -11,15 +11,15 @@ const OPERATORS = { * @return {number} */ function evalRPN(tokens) { - const stack = []; - for (const token of tokens) { - if (token in OPERATORS) { - const rhs = stack.pop(); - const lhs = stack.pop(); - stack.push(OPERATORS[token](lhs, rhs)); - } else { - stack.push(Number(token)); + const stack = []; + for (const token of tokens) { + if (token in OPERATORS) { + const rhs = stack.pop(); + const lhs = stack.pop(); + stack.push(OPERATORS[token](lhs, rhs)); + } else { + stack.push(Number(token)); + } } - } - return stack.pop(); + return stack.pop(); } diff --git a/javascript/152-Maximum-Product-Subarray.js b/javascript/152-Maximum-Product-Subarray.js index 29d2dced0..5b9e5cf4f 100644 --- a/javascript/152-Maximum-Product-Subarray.js +++ b/javascript/152-Maximum-Product-Subarray.js @@ -3,17 +3,17 @@ * @return {number} */ var maxProduct = function (nums) { - let result = nums[0]; - let prevMax = nums[0]; - let prevMin = nums[0]; - for (let i = 1; i < nums.length; i++) { - currMax = Math.max(nums[i], prevMax * nums[i], prevMin * nums[i]); - currMin = Math.min(nums[i], prevMax * nums[i], prevMin * nums[i]); + let result = nums[0]; + let prevMax = nums[0]; + let prevMin = nums[0]; + for (let i = 1; i < nums.length; i++) { + currMax = Math.max(nums[i], prevMax * nums[i], prevMin * nums[i]); + currMin = Math.min(nums[i], prevMax * nums[i], prevMin * nums[i]); - prevMax = currMax; - prevMin = currMin; + prevMax = currMax; + prevMin = currMin; - result = Math.max(currMax, result); - } - return result; + result = Math.max(currMax, result); + } + return result; }; diff --git a/javascript/153-Find-Minimum-in-Rotated-Sorted-Array.js b/javascript/153-Find-Minimum-in-Rotated-Sorted-Array.js index f7c8ac63d..b18504d93 100644 --- a/javascript/153-Find-Minimum-in-Rotated-Sorted-Array.js +++ b/javascript/153-Find-Minimum-in-Rotated-Sorted-Array.js @@ -3,15 +3,15 @@ * @return {number} */ var findMin = function (nums) { - let left = 0; - let right = nums.length - 1; - while (right > left) { - let mid = Math.floor((right + left) / 2); - if (nums[mid] > nums[right]) { - left = mid + 1; - } else { - right = mid; + let left = 0; + let right = nums.length - 1; + while (right > left) { + let mid = Math.floor((right + left) / 2); + if (nums[mid] > nums[right]) { + left = mid + 1; + } else { + right = mid; + } } - } - return nums[left]; + return nums[left]; }; diff --git a/javascript/155-Min-Stack.js b/javascript/155-Min-Stack.js index 2e3dabdfa..12f24e495 100644 --- a/javascript/155-Min-Stack.js +++ b/javascript/155-Min-Stack.js @@ -11,49 +11,49 @@ ////////////////////////////////////////////////////////////////////////////// class MinStack { - /** - * @constructor - */ - constructor() { - this.mainStack = []; - this.minStack = []; - } + /** + * @constructor + */ + constructor() { + this.mainStack = []; + this.minStack = []; + } - /** - * @param {number} val - * @return {void} - */ - push(val) { - this.mainStack.push(val); - if ( - !this.minStack.length || - val <= this.minStack[this.minStack.length - 1] - ) { - this.minStack.push(val); + /** + * @param {number} val + * @return {void} + */ + push(val) { + this.mainStack.push(val); + if ( + !this.minStack.length || + val <= this.minStack[this.minStack.length - 1] + ) { + this.minStack.push(val); + } } - } - /** - * @return {void} - */ - pop() { - const val = this.mainStack.pop(); - if (val === this.minStack[this.minStack.length - 1]) { - this.minStack.pop(); + /** + * @return {void} + */ + pop() { + const val = this.mainStack.pop(); + if (val === this.minStack[this.minStack.length - 1]) { + this.minStack.pop(); + } } - } - /** - * @return {number} - */ - top() { - return this.mainStack[this.mainStack.length - 1]; - } + /** + * @return {number} + */ + top() { + return this.mainStack[this.mainStack.length - 1]; + } - /** - * @return {number} - */ - getMin() { - return this.minStack[this.minStack.length - 1]; - } + /** + * @return {number} + */ + getMin() { + return this.minStack[this.minStack.length - 1]; + } } diff --git a/javascript/160-Intersection-of-Two-Linked-Lists.js b/javascript/160-Intersection-of-Two-Linked-Lists.js index 8615b0878..37b9b09ba 100644 --- a/javascript/160-Intersection-of-Two-Linked-Lists.js +++ b/javascript/160-Intersection-of-Two-Linked-Lists.js @@ -12,12 +12,12 @@ * @return {ListNode} */ var getIntersectionNode = function (headA, headB) { - let a = headA; - let b = headB; - while (a !== b) { - a = a === null ? headB : a.next; - b = b === null ? headA : b.next; - } + let a = headA; + let b = headB; + while (a !== b) { + a = a === null ? headB : a.next; + b = b === null ? headA : b.next; + } - return a; + return a; }; diff --git a/javascript/167-Two-Sum-II.js b/javascript/167-Two-Sum-II.js index 522d74e31..4253ee0bd 100644 --- a/javascript/167-Two-Sum-II.js +++ b/javascript/167-Two-Sum-II.js @@ -4,13 +4,13 @@ * @return {number[]} */ var twoSum = function (numbers, target) { - let start = 0; - let end = numbers.length - 1; - while (start < end) { - let currSum = numbers[start] + numbers[end]; - if (currSum > target) end--; - else if (currSum < target) start++; - else return [start + 1, end + 1]; - } - return []; + let start = 0; + let end = numbers.length - 1; + while (start < end) { + let currSum = numbers[start] + numbers[end]; + if (currSum > target) end--; + else if (currSum < target) start++; + else return [start + 1, end + 1]; + } + return []; }; diff --git a/javascript/17-Letter-Combinations-of-a-Phone-Number.js b/javascript/17-Letter-Combinations-of-a-Phone-Number.js index 6684161c5..20b830868 100644 --- a/javascript/17-Letter-Combinations-of-a-Phone-Number.js +++ b/javascript/17-Letter-Combinations-of-a-Phone-Number.js @@ -1,31 +1,31 @@ function letterCombinations(digits) { - let res = []; + let res = []; - const digitToChar = { - 2: 'abc', - 3: 'def', - 4: 'ghi', - 5: 'jkl', - 6: 'mno', - 7: 'qprs', - 8: 'tuv', - 9: 'wxyz', - }; + const digitToChar = { + 2: 'abc', + 3: 'def', + 4: 'ghi', + 5: 'jkl', + 6: 'mno', + 7: 'qprs', + 8: 'tuv', + 9: 'wxyz', + }; - function backtrack(i, curStr) { - if (curStr.length === digits.length) { - res.push(curStr); - return; - } + function backtrack(i, curStr) { + if (curStr.length === digits.length) { + res.push(curStr); + return; + } - for (const c of digitToChar[digits[i]]) { - backtrack(i + 1, curStr + c); + for (const c of digitToChar[digits[i]]) { + backtrack(i + 1, curStr + c); + } } - } - if (digits) { - backtrack(0, ''); - } + if (digits) { + backtrack(0, ''); + } - return res; + return res; } diff --git a/javascript/19-Remove-Nth-Node-From-End-of-List.js b/javascript/19-Remove-Nth-Node-From-End-of-List.js index 8dfd1ad05..1c3f5cee1 100644 --- a/javascript/19-Remove-Nth-Node-From-End-of-List.js +++ b/javascript/19-Remove-Nth-Node-From-End-of-List.js @@ -11,23 +11,23 @@ * @return {ListNode} */ var removeNthFromEnd = function (head, n) { - let currNode = head; - let nodeBeforeN = head; + let currNode = head; + let nodeBeforeN = head; - for (let i = 0; i < n; i++) { - currNode = currNode.next; - } + for (let i = 0; i < n; i++) { + currNode = currNode.next; + } - if (!currNode) { - return head.next; - } + if (!currNode) { + return head.next; + } - while (currNode.next) { - nodeBeforeN = nodeBeforeN.next; - currNode = currNode.next; - } + while (currNode.next) { + nodeBeforeN = nodeBeforeN.next; + currNode = currNode.next; + } - nodeBeforeN.next = nodeBeforeN.next.next; + nodeBeforeN.next = nodeBeforeN.next.next; - return head; + return head; }; diff --git a/javascript/190-Reverse-Bits.js b/javascript/190-Reverse-Bits.js index bd89817ec..34942f5a0 100644 --- a/javascript/190-Reverse-Bits.js +++ b/javascript/190-Reverse-Bits.js @@ -1,13 +1,13 @@ var reverseBits = function (n) { - let result = 0b0; - let curr = n; + let result = 0b0; + let curr = n; - for (let i = 0; i < 32; i++) { - const lastBit = curr & 0b1; - result = result << 1; - result = result | lastBit; - curr = curr >> 1; - } + for (let i = 0; i < 32; i++) { + const lastBit = curr & 0b1; + result = result << 1; + result = result | lastBit; + curr = curr >> 1; + } - return result >>> 0; + return result >>> 0; }; diff --git a/javascript/191-Number-of-1-bits.js b/javascript/191-Number-of-1-bits.js index 191b57608..71f232a83 100644 --- a/javascript/191-Number-of-1-bits.js +++ b/javascript/191-Number-of-1-bits.js @@ -3,10 +3,10 @@ * @return {number} */ var hammingWeight = function (n) { - let output = 0; - while (n != 0) { - n &= n - 1; - output++; - } - return output; + let output = 0; + while (n != 0) { + n &= n - 1; + output++; + } + return output; }; diff --git a/javascript/198-House-Robber.js b/javascript/198-House-Robber.js index c83e022ac..c4f7a838b 100644 --- a/javascript/198-House-Robber.js +++ b/javascript/198-House-Robber.js @@ -1,12 +1,12 @@ function rob(nums) { - let rob1 = 0; - let rob2 = 0; + let rob1 = 0; + let rob2 = 0; - for (const n of nums) { - let temp = Math.max(n + rob1, rob2); - rob1 = rob2; - rob2 = temp; - } + for (const n of nums) { + let temp = Math.max(n + rob1, rob2); + rob1 = rob2; + rob2 = temp; + } - return rob2; + return rob2; } diff --git a/javascript/199-binary-tree-right-side-view.js b/javascript/199-binary-tree-right-side-view.js index 3e0faedc0..87018b41b 100644 --- a/javascript/199-binary-tree-right-side-view.js +++ b/javascript/199-binary-tree-right-side-view.js @@ -11,25 +11,25 @@ * @return {number[]} */ var rightSideView = function (root) { - let result = []; - let queue = []; + let result = []; + let queue = []; - if (root === null) { - return []; - } + if (root === null) { + return []; + } - queue.push(root); + queue.push(root); - while (queue.length > 0) { - let length = queue.length; - for (let i = 0; i < length; i++) { - let node = queue.shift(); - if (i === length - 1) { - result.push(node.val); - } - if (node.left !== null) queue.push(node.left); - if (node.right !== null) queue.push(node.right); + while (queue.length > 0) { + let length = queue.length; + for (let i = 0; i < length; i++) { + let node = queue.shift(); + if (i === length - 1) { + result.push(node.val); + } + if (node.left !== null) queue.push(node.left); + if (node.right !== null) queue.push(node.right); + } } - } - return result; + return result; }; diff --git a/javascript/2-Add-Two-Numbers.js b/javascript/2-Add-Two-Numbers.js index ef79e9201..e21cb88d5 100644 --- a/javascript/2-Add-Two-Numbers.js +++ b/javascript/2-Add-Two-Numbers.js @@ -1,27 +1,27 @@ function addTwoNumbers(l1, l2) { - let temp1 = l1; - let temp2 = l2; + let temp1 = l1; + let temp2 = l2; - let dummy = new ListNode(0); - let merged = dummy; + let dummy = new ListNode(0); + let merged = dummy; - let carry = 0; + let carry = 0; - while (temp1 || temp2) { - let sum = (temp1?.val || 0) + (temp2?.val || 0) + carry; - carry = Math.floor(sum / 10); - sum = sum % 10; + while (temp1 || temp2) { + let sum = (temp1?.val || 0) + (temp2?.val || 0) + carry; + carry = Math.floor(sum / 10); + sum = sum % 10; - merged.next = new ListNode(sum); - merged = merged.next; + merged.next = new ListNode(sum); + merged = merged.next; - if (temp1) temp1 = temp1?.next; - if (temp2) temp2 = temp2?.next; - } + if (temp1) temp1 = temp1?.next; + if (temp2) temp2 = temp2?.next; + } - if (carry > 0) { - merged.next = new ListNode(carry); - } + if (carry > 0) { + merged.next = new ListNode(carry); + } - return dummy.next; + return dummy.next; } diff --git a/javascript/20-Valid-Parentheses.js b/javascript/20-Valid-Parentheses.js index 87b385f48..68c88dbc8 100644 --- a/javascript/20-Valid-Parentheses.js +++ b/javascript/20-Valid-Parentheses.js @@ -3,29 +3,29 @@ * @return {boolean} */ var isValid = function (s) { - let closeMap = { - '}': '{', - ')': '(', - ']': '[', - }; + let closeMap = { + '}': '{', + ')': '(', + ']': '[', + }; - let charStack = []; + let charStack = []; - if (!s) return false; + if (!s) return false; - for (let i = 0; i < s.length; i++) { - let curr = s.charAt(i); - // check if closing bracket - if (closeMap[curr]) { - topElement = charStack.length === 0 ? '#' : charStack.pop(); - if (topElement !== closeMap[curr]) { - return false; - } - // opening bracket case - } else { - charStack.push(curr); + for (let i = 0; i < s.length; i++) { + let curr = s.charAt(i); + // check if closing bracket + if (closeMap[curr]) { + topElement = charStack.length === 0 ? '#' : charStack.pop(); + if (topElement !== closeMap[curr]) { + return false; + } + // opening bracket case + } else { + charStack.push(curr); + } } - } - return charStack.length === 0; + return charStack.length === 0; }; diff --git a/javascript/200-Number-of-Islands.js b/javascript/200-Number-of-Islands.js index c53c453b5..2802e9005 100644 --- a/javascript/200-Number-of-Islands.js +++ b/javascript/200-Number-of-Islands.js @@ -1,67 +1,67 @@ // Version 1 function explore(grid, r, c, visited) { - const rowInbounds = 0 <= r && r < grid.length; - const colInbounds = 0 <= c && c < grid[0].length; + const rowInbounds = 0 <= r && r < grid.length; + const colInbounds = 0 <= c && c < grid[0].length; - if (!rowInbounds || !colInbounds) return false; - if (grid[r][c] === '0') return false; + if (!rowInbounds || !colInbounds) return false; + if (grid[r][c] === '0') return false; - const pos = r + ',' + c; + const pos = r + ',' + c; - if (visited.has(pos)) return false; - visited.add(pos); + if (visited.has(pos)) return false; + visited.add(pos); - explore(grid, r - 1, c, visited); - explore(grid, r + 1, c, visited); - explore(grid, r, c - 1, visited); - explore(grid, r, c + 1, visited); + explore(grid, r - 1, c, visited); + explore(grid, r + 1, c, visited); + explore(grid, r, c - 1, visited); + explore(grid, r, c + 1, visited); - return true; + return true; } var numIslands = function (grid) { - const visited = new Set(); - let count = 0; + const visited = new Set(); + let count = 0; - for (let r = 0; r < grid.length; r++) { - for (let c = 0; c < grid[0].length; c++) { - if (explore(grid, r, c, visited)) { - count += 1; - } + for (let r = 0; r < grid.length; r++) { + for (let c = 0; c < grid[0].length; c++) { + if (explore(grid, r, c, visited)) { + count += 1; + } + } } - } - return count; + return count; }; // Version 2 (Easier to understand/read) function dfs(grid, i, j) { - if ( - i < 0 || - i >= grid.length || - j < 0 || - j >= grid[0].length || - grid[i][j] === '0' - ) { - return; - } + if ( + i < 0 || + i >= grid.length || + j < 0 || + j >= grid[0].length || + grid[i][j] === '0' + ) { + return; + } - grid[i][j] = '0'; - dfs(grid, i + 1, j); - dfs(grid, i - 1, j); - dfs(grid, i, j + 1); - dfs(grid, i, j - 1); + grid[i][j] = '0'; + dfs(grid, i + 1, j); + dfs(grid, i - 1, j); + dfs(grid, i, j + 1); + dfs(grid, i, j - 1); } var numIslands = function (grid) { - let count = 0; + let count = 0; - for (let i = 0; i < grid.length; i++) { - for (let j = 0; j < grid[0].length; j++) { - if (grid[i][j] === '1') { - count += 1; - dfs(grid, i, j); - } + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[0].length; j++) { + if (grid[i][j] === '1') { + count += 1; + dfs(grid, i, j); + } + } } - } - return count; + return count; }; diff --git a/javascript/202-Happy-Number.js b/javascript/202-Happy-Number.js index d8a0c3bb4..65c477741 100644 --- a/javascript/202-Happy-Number.js +++ b/javascript/202-Happy-Number.js @@ -1,25 +1,25 @@ function isHappy(n) { - const visit = new Set(); + const visit = new Set(); - while (!visit.has(n)) { - visit.add(n); - n = sumOfSquares(n); + while (!visit.has(n)) { + visit.add(n); + n = sumOfSquares(n); - if (n == 1) return true; - } + if (n == 1) return true; + } - return false; + return false; } function sumOfSquares(n) { - let output = 0; + let output = 0; - while (n) { - let digit = n % 10; - digit = digit ** 2; - output += digit; - n = Math.floor(n / 10); - } + while (n) { + let digit = n % 10; + digit = digit ** 2; + output += digit; + n = Math.floor(n / 10); + } - return output; + return output; } diff --git a/javascript/206-Reverse-Linked-List.js b/javascript/206-Reverse-Linked-List.js index 865a17e55..b7dcd2f49 100644 --- a/javascript/206-Reverse-Linked-List.js +++ b/javascript/206-Reverse-Linked-List.js @@ -10,14 +10,14 @@ * @return {ListNode} */ var reverseList = function (head) { - let prev = null; + let prev = null; - while (head) { - let next = head.next; - head.next = prev; - prev = head; - head = next; - } + while (head) { + let next = head.next; + head.next = prev; + prev = head; + head = next; + } - return prev; + return prev; }; diff --git a/javascript/207-canFinish.js b/javascript/207-canFinish.js index 83aaaa27d..6f6b8ab38 100644 --- a/javascript/207-canFinish.js +++ b/javascript/207-canFinish.js @@ -1,38 +1,38 @@ function createGraph(numCourses, edges) { - const graph = Array.from({ length: numCourses }, () => []); + const graph = Array.from({ length: numCourses }, () => []); - for (let edge of edges) { - let [a, b] = edge; + for (let edge of edges) { + let [a, b] = edge; - if (!(a in graph)) graph[a] = []; - if (!(b in graph)) graph[b] = []; + if (!(a in graph)) graph[a] = []; + if (!(b in graph)) graph[b] = []; - graph[a].push(b); - } - return graph; + graph[a].push(b); + } + return graph; } function canFinish(numCourses, preq) { - const graph = createGraph(numCourses, preq); - let seen = new Set(); - let seeing = new Set(); - - function explore(course) { - if (seen.has(course)) return true; - if (seeing.has(course)) return false; - - seeing.add(course); - for (let neighbor of graph[course]) { - if (!explore(neighbor)) return false; + const graph = createGraph(numCourses, preq); + let seen = new Set(); + let seeing = new Set(); + + function explore(course) { + if (seen.has(course)) return true; + if (seeing.has(course)) return false; + + seeing.add(course); + for (let neighbor of graph[course]) { + if (!explore(neighbor)) return false; + } + + seen.add(course); + seeing.delete(course); + return true; } - seen.add(course); - seeing.delete(course); + for (let i = 0; i < numCourses; i++) { + if (!explore(i)) return false; + } return true; - } - - for (let i = 0; i < numCourses; i++) { - if (!explore(i)) return false; - } - return true; } diff --git a/javascript/208-Implement-Trie.js b/javascript/208-Implement-Trie.js index 1de957f5b..7a96fa6e1 100644 --- a/javascript/208-Implement-Trie.js +++ b/javascript/208-Implement-Trie.js @@ -7,53 +7,53 @@ */ class TrieNode { - constructor() { - this.children = {}; - this.isWord = false; - } + constructor() { + this.children = {}; + this.isWord = false; + } } class Trie { - constructor() { - this.root = new TrieNode(); - } + constructor() { + this.root = new TrieNode(); + } - /* Time O(N) | Space O(N) */ - insert(word, node = this.root) { - for (const char of word) { - const child = node.children[char] || new TrieNode(); + /* Time O(N) | Space O(N) */ + insert(word, node = this.root) { + for (const char of word) { + const child = node.children[char] || new TrieNode(); - node.children[char] = child; + node.children[char] = child; - node = child; + node = child; + } + + node.isWord = true; } - node.isWord = true; - } + /* Time O(N) | Space O(1) */ + search(word, node = this.root) { + for (const char of word) { + const child = node.children[char] || null; - /* Time O(N) | Space O(1) */ - search(word, node = this.root) { - for (const char of word) { - const child = node.children[char] || null; + if (!child) return false; - if (!child) return false; + node = child; + } - node = child; + return node.isWord; } - return node.isWord; - } + /* Time O(N) | Space O(1) */ + startsWith(prefix, node = this.root) { + for (const char of prefix) { + const child = node.children[char] || null; - /* Time O(N) | Space O(1) */ - startsWith(prefix, node = this.root) { - for (const char of prefix) { - const child = node.children[char] || null; + if (!child) return false; - if (!child) return false; + node = child; + } - node = child; + return true; } - - return true; - } } diff --git a/javascript/21-Merge-Two-Sorted-Lists.js b/javascript/21-Merge-Two-Sorted-Lists.js index fa451974b..f1d8cd723 100644 --- a/javascript/21-Merge-Two-Sorted-Lists.js +++ b/javascript/21-Merge-Two-Sorted-Lists.js @@ -11,18 +11,18 @@ * @return {ListNode} */ var mergeTwoLists = function (l1, l2) { - let nullNode = { val: 0, next: null }; - let prev = nullNode; - while (l1 && l2) { - if (l1.val >= l2.val) { - prev.next = l2; - l2 = l2.next; - } else { - prev.next = l1; - l1 = l1.next; + let nullNode = { val: 0, next: null }; + let prev = nullNode; + while (l1 && l2) { + if (l1.val >= l2.val) { + prev.next = l2; + l2 = l2.next; + } else { + prev.next = l1; + l1 = l1.next; + } + prev = prev.next; } - prev = prev.next; - } - prev.next = l1 || l2; - return nullNode.next; + prev.next = l1 || l2; + return nullNode.next; }; diff --git a/javascript/210-Course-Schedule-II.js b/javascript/210-Course-Schedule-II.js index d3952e3ac..bfc161ded 100644 --- a/javascript/210-Course-Schedule-II.js +++ b/javascript/210-Course-Schedule-II.js @@ -4,33 +4,33 @@ * @return {number[]} */ var findOrder = function (numCourses, prerequisites) { - const prereq = []; - for (let i = 0; i < numCourses; i++) { - prereq[i] = []; - } - for (const [crs, pre] of prerequisites) { - prereq[crs].push(pre); - } + const prereq = []; + for (let i = 0; i < numCourses; i++) { + prereq[i] = []; + } + for (const [crs, pre] of prerequisites) { + prereq[crs].push(pre); + } - const output = []; - const visit = new Set(); - const cycle = new Set(); - function dfs(course) { - if (cycle.has(course)) return false; - if (visit.has(course)) return true; + const output = []; + const visit = new Set(); + const cycle = new Set(); + function dfs(course) { + if (cycle.has(course)) return false; + if (visit.has(course)) return true; - cycle.add(course); - for (const pre of prereq[course]) { - if (!dfs(pre)) return false; + cycle.add(course); + for (const pre of prereq[course]) { + if (!dfs(pre)) return false; + } + cycle.delete(course); + visit.add(course); + output.push(course); + return true; } - cycle.delete(course); - visit.add(course); - output.push(course); - return true; - } - for (let j = 0; j < numCourses; j++) { - if (!dfs(j)) return []; - } - return output; + for (let j = 0; j < numCourses; j++) { + if (!dfs(j)) return []; + } + return output; }; diff --git a/javascript/211-Design-Add-and-Search-Words-Data-Structure.js b/javascript/211-Design-Add-and-Search-Words-Data-Structure.js index 1c090dbd1..bd56b167c 100644 --- a/javascript/211-Design-Add-and-Search-Words-Data-Structure.js +++ b/javascript/211-Design-Add-and-Search-Words-Data-Structure.js @@ -6,55 +6,55 @@ */ class TrieNode { - constructor() { - this.children = {}; - this.isWord = false; - } + constructor() { + this.children = {}; + this.isWord = false; + } } class WordDictionary { - constructor() { - this.root = new TrieNode(); - } + constructor() { + this.root = new TrieNode(); + } + + /* Time O(N) | Space O(N) */ + addWord(word, node = this.root) { + for (const char of word) { + const child = node.children[char] || new TrieNode(); - /* Time O(N) | Space O(N) */ - addWord(word, node = this.root) { - for (const char of word) { - const child = node.children[char] || new TrieNode(); + node.children[char] = child; - node.children[char] = child; + node = child; + } - node = child; + node.isWord = true; } - node.isWord = true; - } + /* Time O(N) | Space O(N) */ + search(word) { + return this.dfs(word, this.root, 0); + } - /* Time O(N) | Space O(N) */ - search(word) { - return this.dfs(word, this.root, 0); - } + dfs(word, node, level) { + if (!node) return false; - dfs(word, node, level) { - if (!node) return false; + const isWord = level === word.length; + if (isWord) return node.isWord; - const isWord = level === word.length; - if (isWord) return node.isWord; + const isWildCard = word[level] === '.'; + if (isWildCard) return this.hasWildCard(word, node, level); - const isWildCard = word[level] === '.'; - if (isWildCard) return this.hasWildCard(word, node, level); + return this.dfs(word, node.children[word[level]], level + 1); + } - return this.dfs(word, node.children[word[level]], level + 1); - } + hasWildCard(word, node, level) { + for (const char of Object.keys(node.children)) { + const child = node.children[char]; - hasWildCard(word, node, level) { - for (const char of Object.keys(node.children)) { - const child = node.children[char]; + const hasWord = this.dfs(word, child, level + 1); + if (hasWord) return true; + } - const hasWord = this.dfs(word, child, level + 1); - if (hasWord) return true; + return false; } - - return false; - } } diff --git a/javascript/212-Word-Search-ii.js b/javascript/212-Word-Search-ii.js index 9a4ddbec5..1f15a55f8 100644 --- a/javascript/212-Word-Search-ii.js +++ b/javascript/212-Word-Search-ii.js @@ -5,98 +5,98 @@ * @return {string[]} */ var findWords = function (board, words) { - return new Trie(words).searchBoard(board); + return new Trie(words).searchBoard(board); }; class TrieNode { - constructor() { - this.children = {}; - this.word = ''; - } + constructor() { + this.children = {}; + this.word = ''; + } } class Trie { - constructor(words) { - this.root = new TrieNode(); - words.forEach((word) => this.insert(word)); - } + constructor(words) { + this.root = new TrieNode(); + words.forEach((word) => this.insert(word)); + } + + /* Time O(N) | Space O(N) */ + insert(word, node = this.root) { + for (const char of word) { + const child = node.children[char] || new TrieNode(); - /* Time O(N) | Space O(N) */ - insert(word, node = this.root) { - for (const char of word) { - const child = node.children[char] || new TrieNode(); + node.children[char] = child; - node.children[char] = child; + node = child; + } - node = child; + node.word = word; } - node.word = word; - } + /* Time O((ROWS * COLS) * (4 * (3 ^ (WORDS - 1)))) | Space O(N) */ + searchBoard(board, node = this.root, words = []) { + const [rows, cols] = [board.length, board[0].length]; - /* Time O((ROWS * COLS) * (4 * (3 ^ (WORDS - 1)))) | Space O(N) */ - searchBoard(board, node = this.root, words = []) { - const [rows, cols] = [board.length, board[0].length]; + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + this.dfs(board, row, rows, col, cols, node, words); + } + } - for (let row = 0; row < rows; row++) { - for (let col = 0; col < cols; col++) { - this.dfs(board, row, rows, col, cols, node, words); - } + return words; } - return words; - } + dfs(board, row, rows, col, cols, node, words) { + const char = board[row][col]; + const child = node.children[char] || null; - dfs(board, row, rows, col, cols, node, words) { - const char = board[row][col]; - const child = node.children[char] || null; + if (this.canSkip(char, child)) return; - if (this.canSkip(char, child)) return; + node = child; + this.checkWord(node, words); + this.backTrack(board, row, rows, col, cols, node, words); + } - node = child; - this.checkWord(node, words); - this.backTrack(board, row, rows, col, cols, node, words); - } + canSkip(char, child) { + const hasSeen = char === '#'; + const isMissingChild = !child; - canSkip(char, child) { - const hasSeen = char === '#'; - const isMissingChild = !child; + return hasSeen || isMissingChild; + } - return hasSeen || isMissingChild; - } + checkWord(node, words) { + if (!node.word.length) return; - checkWord(node, words) { - if (!node.word.length) return; + words.push(node.word); + node.word = ''; + } - words.push(node.word); - node.word = ''; - } + backTrack(board, row, rows, col, cols, node, words) { + const char = board[row][col]; - backTrack(board, row, rows, col, cols, node, words) { - const char = board[row][col]; + board[row][col] = '#'; - board[row][col] = '#'; + for (const [_row, _col] of this.getNeighbors(row, rows, col, cols)) { + this.dfs(board, _row, rows, _col, cols, node, words); + } - for (const [_row, _col] of this.getNeighbors(row, rows, col, cols)) { - this.dfs(board, _row, rows, _col, cols, node, words); + board[row][col] = char; } - board[row][col] = char; - } - - getNeighbors(row, rows, col, cols) { - return [ - [row - 1, col], - [row + 1, col], - [row, col - 1], - [row, col + 1], - ].filter(([_row, _col]) => !this.isOutOfBounds(_row, rows, _col, cols)); - } + getNeighbors(row, rows, col, cols) { + return [ + [row - 1, col], + [row + 1, col], + [row, col - 1], + [row, col + 1], + ].filter(([_row, _col]) => !this.isOutOfBounds(_row, rows, _col, cols)); + } - isOutOfBounds(row, rows, col, cols) { - const isRowOut = row < 0 || rows <= row; - const isColOut = col < 0 || cols <= col; + isOutOfBounds(row, rows, col, cols) { + const isRowOut = row < 0 || rows <= row; + const isColOut = col < 0 || cols <= col; - return isRowOut || isColOut; - } + return isRowOut || isColOut; + } } diff --git a/javascript/213-House-Robber-II.js b/javascript/213-House-Robber-II.js index a2d2c0d72..72d6022dc 100644 --- a/javascript/213-House-Robber-II.js +++ b/javascript/213-House-Robber-II.js @@ -3,19 +3,19 @@ * @return {number} */ var rob = function (nums) { - const n = nums.length; - if (n == 1) return nums[0]; + const n = nums.length; + if (n == 1) return nums[0]; - function houseRobber(start, end) { - let first = 0; - let second = nums[start]; - for (let i = start + 1; i < end; i++) { - let temp = Math.max(first + nums[i], second); - first = second; - second = temp; + function houseRobber(start, end) { + let first = 0; + let second = nums[start]; + for (let i = start + 1; i < end; i++) { + let temp = Math.max(first + nums[i], second); + first = second; + second = temp; + } + return second; } - return second; - } - return Math.max(houseRobber(0, n - 1), houseRobber(1, n)); + return Math.max(houseRobber(0, n - 1), houseRobber(1, n)); }; diff --git a/javascript/217-Contains-Duplicate.js b/javascript/217-Contains-Duplicate.js index cb1b7d203..3d4905345 100644 --- a/javascript/217-Contains-Duplicate.js +++ b/javascript/217-Contains-Duplicate.js @@ -5,27 +5,27 @@ //First method using Map() (exit early if true) var containsDuplicate = function (nums) { - const numsSet = new Set(); - for (const i of nums) { - if (numsSet.has(i)) { - return true; + const numsSet = new Set(); + for (const i of nums) { + if (numsSet.has(i)) { + return true; + } + numsSet.add(i); } - numsSet.add(i); - } - return false; + return false; }; //Second method using Map() (Has to map entire array but code is more readable) var containsDuplicate = function (nums) { - //create a new hashmap with all the items in the array. Any duplicates will be removed. - const totalWithoutDuplicates = new Map(nums.map((i) => [i])); + //create a new hashmap with all the items in the array. Any duplicates will be removed. + const totalWithoutDuplicates = new Map(nums.map((i) => [i])); - //check if the size of the initial array is larger than the new hashmap. - return totalWithoutDuplicates.size !== nums.length; + //check if the size of the initial array is larger than the new hashmap. + return totalWithoutDuplicates.size !== nums.length; }; //Third method using Set() (Fastest runtime at 91.95% and very readable code) var containsDuplicate = function (nums) { - //Pass the array into a Set() (which removes duplicates) and then compare its size to the original array. - return new Set(nums).size !== nums.length; + //Pass the array into a Set() (which removes duplicates) and then compare its size to the original array. + return new Set(nums).size !== nums.length; }; diff --git a/javascript/22-Generate-Parentheses.js b/javascript/22-Generate-Parentheses.js index b729fcdb9..5d7005f5d 100644 --- a/javascript/22-Generate-Parentheses.js +++ b/javascript/22-Generate-Parentheses.js @@ -5,29 +5,29 @@ * @return {string[]} */ var generateParenthesis = function (n) { - const combinations = []; - const currentCombination = []; + const combinations = []; + const currentCombination = []; - function exploreParens(opensRemaining, closesAvailable) { - if (currentCombination.length == n * 2) { - combinations.push(currentCombination.join('')); - return; - } + function exploreParens(opensRemaining, closesAvailable) { + if (currentCombination.length == n * 2) { + combinations.push(currentCombination.join('')); + return; + } - if (opensRemaining) { - currentCombination.push('('); - exploreParens(opensRemaining - 1, closesAvailable + 1); - currentCombination.pop(); - } + if (opensRemaining) { + currentCombination.push('('); + exploreParens(opensRemaining - 1, closesAvailable + 1); + currentCombination.pop(); + } - if (closesAvailable) { - currentCombination.push(')'); - exploreParens(opensRemaining, closesAvailable - 1); - currentCombination.pop(); + if (closesAvailable) { + currentCombination.push(')'); + exploreParens(opensRemaining, closesAvailable - 1); + currentCombination.pop(); + } } - } - exploreParens(n, 0); + exploreParens(n, 0); - return combinations; + return combinations; }; diff --git a/javascript/226-Invert-Binary-Tree.js b/javascript/226-Invert-Binary-Tree.js index b96fb71e5..726257aed 100644 --- a/javascript/226-Invert-Binary-Tree.js +++ b/javascript/226-Invert-Binary-Tree.js @@ -11,9 +11,9 @@ * @return {TreeNode} */ var invertTree = function (root) { - if (!root) return root; - let left = root.left; - root.left = invertTree(root.right); - root.right = invertTree(left); - return root; + if (!root) return root; + let left = root.left; + root.left = invertTree(root.right); + root.right = invertTree(left); + return root; }; diff --git a/javascript/23-Merge-K-Sorted-Lists.js b/javascript/23-Merge-K-Sorted-Lists.js index ba707f9e9..b9a6cd525 100644 --- a/javascript/23-Merge-K-Sorted-Lists.js +++ b/javascript/23-Merge-K-Sorted-Lists.js @@ -1,28 +1,28 @@ var merge = function (l1, l2) { - let tempNode = new ListNode(0); - let current = tempNode; + let tempNode = new ListNode(0); + let current = tempNode; - while (l1 && l2) { - if (l1.val < l2.val) { - current.next = l1; - l1 = l1.next; - } else { - current.next = l2; - l2 = l2.next; + while (l1 && l2) { + if (l1.val < l2.val) { + current.next = l1; + l1 = l1.next; + } else { + current.next = l2; + l2 = l2.next; + } + current = current.next; } - current = current.next; - } - if (l1) current.next = l1; - if (l2) current.next = l2; + if (l1) current.next = l1; + if (l2) current.next = l2; - return tempNode.next; + return tempNode.next; }; var mergeKLists = function (lists) { - let root = lists[0]; + let root = lists[0]; - for (let i = 1; i < lists.length; i++) { - root = merge(root, lists[i]); - } - return root || null; + for (let i = 1; i < lists.length; i++) { + root = merge(root, lists[i]); + } + return root || null; }; diff --git a/javascript/230-Kth-Smallest-Element-in-a-BST.js b/javascript/230-Kth-Smallest-Element-in-a-BST.js index a0541c7dc..472fdbec4 100644 --- a/javascript/230-Kth-Smallest-Element-in-a-BST.js +++ b/javascript/230-Kth-Smallest-Element-in-a-BST.js @@ -1,21 +1,21 @@ function kthSmallest(root, k) { - let n = 0; - const stack = []; - let cur = root; + let n = 0; + const stack = []; + let cur = root; - while (cur || stack) { - while (cur) { - stack.push(cur); - cur = cur.left; - } + while (cur || stack) { + while (cur) { + stack.push(cur); + cur = cur.left; + } - cur = stack.pop(); - n += 1; + cur = stack.pop(); + n += 1; - if (n == k) { - return cur.val; - } + if (n == k) { + return cur.val; + } - cur = cur?.right; - } + cur = cur?.right; + } } diff --git a/javascript/234-Palindrome-Linked-List.js b/javascript/234-Palindrome-Linked-List.js index 3b3baeccf..45d113499 100644 --- a/javascript/234-Palindrome-Linked-List.js +++ b/javascript/234-Palindrome-Linked-List.js @@ -10,34 +10,34 @@ * @return {boolean} */ var isPalindrome = function (head) { - // find mid point - let slow = head; - let fast = head; - while (fast && fast.next) { - slow = slow.next; - fast = fast.next.next; - } - - // reverse 2nd half - let curr = slow; - let prev = null; - while (curr) { - let next = curr.next; - curr.next = prev; - prev = curr; - curr = next; - } - let head2 = prev; + // find mid point + let slow = head; + let fast = head; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } - // compare both halfs - while (head && head2) { - if (head.val !== head2.val) { - return false; + // reverse 2nd half + let curr = slow; + let prev = null; + while (curr) { + let next = curr.next; + curr.next = prev; + prev = curr; + curr = next; } + let head2 = prev; - head = head.next; - head2 = head2.next; - } + // compare both halfs + while (head && head2) { + if (head.val !== head2.val) { + return false; + } + + head = head.next; + head2 = head2.next; + } - return true; + return true; }; diff --git a/javascript/235-lowest-common-ancestor-of-a-binary-search-tree.js b/javascript/235-lowest-common-ancestor-of-a-binary-search-tree.js index d7b5d0a62..89467df16 100644 --- a/javascript/235-lowest-common-ancestor-of-a-binary-search-tree.js +++ b/javascript/235-lowest-common-ancestor-of-a-binary-search-tree.js @@ -13,13 +13,13 @@ * @return {TreeNode} */ var lowestCommonAncestor = function (root, p, q) { - while (root !== null) { - if (root.val < p.val && root.val < q.val) { - root = root.right; - } else if (root.val > p.val && root.val > q.val) { - root = root.left; - } else { - return root; + while (root !== null) { + if (root.val < p.val && root.val < q.val) { + root = root.right; + } else if (root.val > p.val && root.val > q.val) { + root = root.left; + } else { + return root; + } } - } }; diff --git a/javascript/238-Product-of-Array-Except-Self.js b/javascript/238-Product-of-Array-Except-Self.js index 63baebaef..19a47003c 100644 --- a/javascript/238-Product-of-Array-Except-Self.js +++ b/javascript/238-Product-of-Array-Except-Self.js @@ -3,19 +3,19 @@ * @return {number[]} */ var productExceptSelf = function (nums) { - const res = []; + const res = []; - let product = 1; + let product = 1; - for (let i = 0; i < nums.length; i++) { - res[i] = product; - product *= nums[i]; - } - product = 1; - for (let j = nums.length - 1; j >= 0; j--) { - res[j] *= product; - product *= nums[j]; - } + for (let i = 0; i < nums.length; i++) { + res[i] = product; + product *= nums[i]; + } + product = 1; + for (let j = nums.length - 1; j >= 0; j--) { + res[j] *= product; + product *= nums[j]; + } - return res; + return res; }; diff --git a/javascript/239-Sliding-Window-Maximum.js b/javascript/239-Sliding-Window-Maximum.js index 6ac0ea364..c2de21b5e 100644 --- a/javascript/239-Sliding-Window-Maximum.js +++ b/javascript/239-Sliding-Window-Maximum.js @@ -4,79 +4,79 @@ * @return {number[]} */ function Node(value) { - this.value = value; - this.prev = null; - this.next = null; + this.value = value; + this.prev = null; + this.next = null; } function Deque() { - this.left = null; - this.right = null; - this.size = 0; - this.pushRight = function (value) { - const node = new Node(value); - if (this.size == 0) { - this.left = node; - this.right = node; - } else { - this.right.next = node; - node.prev = this.right; - this.right = node; - } - this.size++; - return this.size; - }; - this.popRight = function () { - if (this.size == 0) return null; - const removedNode = this.right; - this.right = this.right.prev; - if (this.right) this.right.next = null; - this.size--; - return removedNode; - }; - this.pushLeft = function (value) { - const node = new Node(value); - if (this.size == 0) { - this.left = node; - this.right = node; - } else { - this.left.prev = node; - node.next = this.left; - this.left = node; - } - this.size++; - return this.size; - }; - this.popLeft = function () { - if (this.size == 0) return null; - const removedNode = this.left; - this.left = this.left.next; - if (this.left) this.left.prev = null; - this.size--; - return removedNode; - }; + this.left = null; + this.right = null; + this.size = 0; + this.pushRight = function (value) { + const node = new Node(value); + if (this.size == 0) { + this.left = node; + this.right = node; + } else { + this.right.next = node; + node.prev = this.right; + this.right = node; + } + this.size++; + return this.size; + }; + this.popRight = function () { + if (this.size == 0) return null; + const removedNode = this.right; + this.right = this.right.prev; + if (this.right) this.right.next = null; + this.size--; + return removedNode; + }; + this.pushLeft = function (value) { + const node = new Node(value); + if (this.size == 0) { + this.left = node; + this.right = node; + } else { + this.left.prev = node; + node.next = this.left; + this.left = node; + } + this.size++; + return this.size; + }; + this.popLeft = function () { + if (this.size == 0) return null; + const removedNode = this.left; + this.left = this.left.next; + if (this.left) this.left.prev = null; + this.size--; + return removedNode; + }; } var maxSlidingWindow = function (nums, k) { - const output = []; - let deque = new Deque(); - let left = 0; - let right = 0; + const output = []; + let deque = new Deque(); + let left = 0; + let right = 0; - while (right < nums.length) { - // pop smaller values from q - while (deque.right && nums[deque.right.value] < nums[right]) - deque.popRight(); - deque.pushRight(right); + while (right < nums.length) { + // pop smaller values from q + while (deque.right && nums[deque.right.value] < nums[right]) + deque.popRight(); + deque.pushRight(right); - // remove left val from window - if (left > deque.left.value) deque.popLeft(); + // remove left val from window + if (left > deque.left.value) deque.popLeft(); - if (right + 1 >= k) { - output.push(nums[deque.left.value]); - left++; + if (right + 1 >= k) { + output.push(nums[deque.left.value]); + left++; + } + right++; } - right++; - } - return output; + return output; }; diff --git a/javascript/242-Valid-Anagram.js b/javascript/242-Valid-Anagram.js index 3b7f07e84..2096d8b89 100644 --- a/javascript/242-Valid-Anagram.js +++ b/javascript/242-Valid-Anagram.js @@ -4,27 +4,27 @@ * @return {boolean} */ var isAnagram = function (s, t) { - if (s.length !== t.length) { - return false; - } - let sMap = {}; - let tMap = {}; - for (let i = 0; i < s.length; i++) { - if (sMap.hasOwnProperty(s[i])) { - sMap[s[i]]++; - } else { - sMap[s[i]] = 1; + if (s.length !== t.length) { + return false; } - if (tMap.hasOwnProperty(t[i])) { - tMap[t[i]]++; - } else { - tMap[t[i]] = 1; + let sMap = {}; + let tMap = {}; + for (let i = 0; i < s.length; i++) { + if (sMap.hasOwnProperty(s[i])) { + sMap[s[i]]++; + } else { + sMap[s[i]] = 1; + } + if (tMap.hasOwnProperty(t[i])) { + tMap[t[i]]++; + } else { + tMap[t[i]] = 1; + } } - } - for (let k in sMap) { - if (sMap[k] !== tMap[k]) { - return false; + for (let k in sMap) { + if (sMap[k] !== tMap[k]) { + return false; + } } - } - return true; + return true; }; diff --git a/javascript/25-Reverse-Nodes-in-K-Group.js b/javascript/25-Reverse-Nodes-in-K-Group.js index 5d73a791b..62776c203 100644 --- a/javascript/25-Reverse-Nodes-in-K-Group.js +++ b/javascript/25-Reverse-Nodes-in-K-Group.js @@ -11,41 +11,41 @@ * @return {ListNode} */ var reverseKGroup = function (head, k) { - let dummy = new ListNode(0, head); - let groupPrev = dummy; - - while (true) { - let kth = getKth(groupPrev, k); - if (!kth) { - break; + let dummy = new ListNode(0, head); + let groupPrev = dummy; + + while (true) { + let kth = getKth(groupPrev, k); + if (!kth) { + break; + } + + let groupNext = kth.next; + + // reverse group + let prev = kth.next; + let curr = groupPrev.next; + + while (curr !== groupNext) { + let temp = curr.next; + curr.next = prev; + prev = curr; + curr = temp; + } + + let temp = groupPrev.next; + groupPrev.next = kth; + groupPrev = temp; } - let groupNext = kth.next; - - // reverse group - let prev = kth.next; - let curr = groupPrev.next; - - while (curr !== groupNext) { - let temp = curr.next; - curr.next = prev; - prev = curr; - curr = temp; - } - - let temp = groupPrev.next; - groupPrev.next = kth; - groupPrev = temp; - } - - return dummy.next; + return dummy.next; }; function getKth(curr, k) { - while (curr && k > 0) { - curr = curr.next; - k -= 1; - } + while (curr && k > 0) { + curr = curr.next; + k -= 1; + } - return curr; + return curr; } diff --git a/javascript/252-Meeting-Rooms.js b/javascript/252-Meeting-Rooms.js index e22511cf0..33bcaf47f 100644 --- a/javascript/252-Meeting-Rooms.js +++ b/javascript/252-Meeting-Rooms.js @@ -3,12 +3,12 @@ * @return {boolean} */ var canAttendMeetings = function (intervals) { - intervals.sort((a, b) => a[0] - b[0]); + intervals.sort((a, b) => a[0] - b[0]); - for (let i = 0; i < intervals.length - 1; i++) { - if (intervals[i][1] > intervals[i + 1][0]) { - return false; + for (let i = 0; i < intervals.length - 1; i++) { + if (intervals[i][1] > intervals[i + 1][0]) { + return false; + } } - } - return true; + return true; }; diff --git a/javascript/268-Missing-Number.js b/javascript/268-Missing-Number.js index ead5bebe9..26bd8c46e 100644 --- a/javascript/268-Missing-Number.js +++ b/javascript/268-Missing-Number.js @@ -1,19 +1,19 @@ var missingNumberWithSums = function (nums) { - let res = nums.length; + let res = nums.length; - for (let i = 0; i < nums.length; i++) { - res += i - nums[i]; - } + for (let i = 0; i < nums.length; i++) { + res += i - nums[i]; + } - return res; + return res; }; var missingNumberWithBit = function (nums) { - let res = nums.length; + let res = nums.length; - for (let i = 0; i < nums.length; i++) { - res = res ^ i ^ nums[i]; - } + for (let i = 0; i < nums.length; i++) { + res = res ^ i ^ nums[i]; + } - return res; + return res; }; diff --git a/javascript/269-Alien-Dictionary.js b/javascript/269-Alien-Dictionary.js index 0a3c9af6a..8d992879c 100644 --- a/javascript/269-Alien-Dictionary.js +++ b/javascript/269-Alien-Dictionary.js @@ -1,55 +1,55 @@ let alienOrder = function (words) { - let graph = {}; + let graph = {}; - for (let i = 0; i < words.length; i++) { - for (let j = 0; j < words[i].length; j++) { - graph[words[i][j]] = new Set(); + for (let i = 0; i < words.length; i++) { + for (let j = 0; j < words[i].length; j++) { + graph[words[i][j]] = new Set(); + } } - } - for (let i = 0; i < words.length - 1; i++) { - let word1 = words[i]; - let word2 = words[i + 1]; + for (let i = 0; i < words.length - 1; i++) { + let word1 = words[i]; + let word2 = words[i + 1]; - if (word1.length > word2.length && (word1 + '').startsWith(word2)) { - return ''; - } + if (word1.length > word2.length && (word1 + '').startsWith(word2)) { + return ''; + } - for (let j = 0; j < Math.min(word1.length, word2.length); j++) { - let c1 = word1[j]; - let c2 = word2[j]; + for (let j = 0; j < Math.min(word1.length, word2.length); j++) { + let c1 = word1[j]; + let c2 = word2[j]; - if (c1 !== c2) { - graph[c1].add(c2); - break; - } + if (c1 !== c2) { + graph[c1].add(c2); + break; + } + } } - } - let visited = {}; // 'false' = visited, 'true' = current path - let res = []; + let visited = {}; // 'false' = visited, 'true' = current path + let res = []; - function dfs(c) { - if (visited[c]) { - return Boolean(visited[c]); - } + function dfs(c) { + if (visited[c]) { + return Boolean(visited[c]); + } - visited[c] = 'true'; - for (let nei of graph[c]) { - if (dfs(nei)) { - return true; - } - } + visited[c] = 'true'; + for (let nei of graph[c]) { + if (dfs(nei)) { + return true; + } + } - visited[c] = 'false'; - res.push(c); - } - - Object.keys(graph).forEach((c) => { - if (dfs(c)) { - return ''; + visited[c] = 'false'; + res.push(c); } - }); - return res.reverse().join(''); + Object.keys(graph).forEach((c) => { + if (dfs(c)) { + return ''; + } + }); + + return res.reverse().join(''); }; diff --git a/javascript/271-Encode-and-Decode-Strings.js b/javascript/271-Encode-and-Decode-Strings.js index 2470ba893..4d2298a94 100644 --- a/javascript/271-Encode-and-Decode-Strings.js +++ b/javascript/271-Encode-and-Decode-Strings.js @@ -3,7 +3,7 @@ * @return {string} */ function encode(strs) { - return strs.map((str) => `${str.length}#${str}`).join(''); + return strs.map((str) => `${str.length}#${str}`).join(''); } /** @@ -11,19 +11,19 @@ function encode(strs) { * @return {string[]} */ function decode(str) { - const res = []; - let i = 0; + const res = []; + let i = 0; - while (i < str.length) { - let j = i; - while (str[j] !== '#') { - ++j; - } + while (i < str.length) { + let j = i; + while (str[j] !== '#') { + ++j; + } - const len = Number(str.slice(i, j)); - res.push(str.slice(++j, j + len)); - i = j + len; - } + const len = Number(str.slice(i, j)); + res.push(str.slice(++j, j + len)); + i = j + len; + } - return res; + return res; } diff --git a/javascript/286-Walls-And-Gates.js b/javascript/286-Walls-And-Gates.js index b15e65d17..7c571c93b 100644 --- a/javascript/286-Walls-And-Gates.js +++ b/javascript/286-Walls-And-Gates.js @@ -15,16 +15,16 @@ const INF = 2 ** 31 - 1; * @return {void} Do not return anything, modify rooms in-place instead. */ function wallsAndGates(rooms) { - for (let i = 0; i < rooms.length; ++i) { - for (let j = 0; j < rooms[0].length; ++j) { - if (rooms[i][j] === 0) { - fillRooms(rooms, i - 1, j); - fillRooms(rooms, i + 1, j); - fillRooms(rooms, i, j - 1); - fillRooms(rooms, i, j + 1); - } + for (let i = 0; i < rooms.length; ++i) { + for (let j = 0; j < rooms[0].length; ++j) { + if (rooms[i][j] === 0) { + fillRooms(rooms, i - 1, j); + fillRooms(rooms, i + 1, j); + fillRooms(rooms, i, j - 1); + fillRooms(rooms, i, j + 1); + } + } } - } } /** @@ -35,22 +35,22 @@ function wallsAndGates(rooms) { * @return {void} */ function fillRooms(rooms, i, j, count = 0) { - if (!inBounds(rooms, i, j) || rooms[i][j] < 1) { - return; - } + if (!inBounds(rooms, i, j) || rooms[i][j] < 1) { + return; + } - ++count; + ++count; - if (rooms[i][j] !== INF && rooms[i][j] <= count) { - return; - } + if (rooms[i][j] !== INF && rooms[i][j] <= count) { + return; + } - rooms[i][j] = count; + rooms[i][j] = count; - fillRooms(rooms, i - 1, j, count); - fillRooms(rooms, i + 1, j, count); - fillRooms(rooms, i, j - 1, count); - fillRooms(rooms, i, j + 1, count); + fillRooms(rooms, i - 1, j, count); + fillRooms(rooms, i + 1, j, count); + fillRooms(rooms, i, j - 1, count); + fillRooms(rooms, i, j + 1, count); } /** @@ -60,7 +60,7 @@ function fillRooms(rooms, i, j, count = 0) { * @return {boolean} */ function inBounds(rooms, i, j) { - return i >= 0 && j >= 0 && i < rooms.length && j < rooms[0].length; + return i >= 0 && j >= 0 && i < rooms.length && j < rooms[0].length; } ////////////////////////////////////////////////////////////////////////////// @@ -75,10 +75,10 @@ function inBounds(rooms, i, j) { const INF = 2 ** 31 - 1; const DIRECTIONS = [ - [-1, 0], - [1, 0], - [0, -1], - [0, 1], + [-1, 0], + [1, 0], + [0, -1], + [0, 1], ]; /** @@ -86,36 +86,36 @@ const DIRECTIONS = [ * @return {void} */ function wallsAndGates(rooms) { - const queue = []; + const queue = []; - for (let i = 0; i < rooms.length; ++i) { - for (let j = 0; j < rooms[0].length; ++j) { - if (rooms[i][j] === 0) { - queue.push([i, j]); - } + for (let i = 0; i < rooms.length; ++i) { + for (let j = 0; j < rooms[0].length; ++j) { + if (rooms[i][j] === 0) { + queue.push([i, j]); + } + } } - } - let count = 1; + let count = 1; - while (queue.length) { - let length = queue.length; + while (queue.length) { + let length = queue.length; - while (length--) { - [i, j] = queue.shift(); + while (length--) { + [i, j] = queue.shift(); - for ([k, l] of DIRECTIONS) { - k += i; - l += j; - if (inBounds(rooms, k, l) && rooms[k][l] === INF) { - rooms[k][l] = count; - queue.push([k, l]); + for ([k, l] of DIRECTIONS) { + k += i; + l += j; + if (inBounds(rooms, k, l) && rooms[k][l] === INF) { + rooms[k][l] = count; + queue.push([k, l]); + } + } } - } - } - ++count; - } + ++count; + } } /** @@ -125,5 +125,5 @@ function wallsAndGates(rooms) { * @return {boolean} */ function inBounds(rooms, i, j) { - return i >= 0 && j >= 0 && i < rooms.length && j < rooms[0].length; + return i >= 0 && j >= 0 && i < rooms.length && j < rooms[0].length; } diff --git a/javascript/287-Find-the-Duplicate-Number.js b/javascript/287-Find-the-Duplicate-Number.js index 83627c687..8fdea2c93 100644 --- a/javascript/287-Find-the-Duplicate-Number.js +++ b/javascript/287-Find-the-Duplicate-Number.js @@ -1,24 +1,24 @@ function findDuplicate(nums) { - let slow = 0; - let fast = 0; + let slow = 0; + let fast = 0; - while (true) { - slow = nums[slow]; - fast = nums[nums[fast]]; - if (slow == fast) { - break; + while (true) { + slow = nums[slow]; + fast = nums[nums[fast]]; + if (slow == fast) { + break; + } } - } - let slow2 = 0; + let slow2 = 0; - while (true) { - slow = nums[slow]; - slow2 = nums[slow2]; - if (slow == slow2) { - break; + while (true) { + slow = nums[slow]; + slow2 = nums[slow2]; + if (slow == slow2) { + break; + } } - } - return slow; + return slow; } diff --git a/javascript/297-Serialize-and-Deserialize-Binary-Tree.js b/javascript/297-Serialize-and-Deserialize-Binary-Tree.js index 75b4cd2c2..30bd3d44c 100644 --- a/javascript/297-Serialize-and-Deserialize-Binary-Tree.js +++ b/javascript/297-Serialize-and-Deserialize-Binary-Tree.js @@ -13,21 +13,21 @@ * @return {string} */ var serialize = function (root) { - const res = []; + const res = []; - function dfs(node) { - if (!node) { - res.push('N'); - return; - } + function dfs(node) { + if (!node) { + res.push('N'); + return; + } - res.push(String(node.val)); - dfs(node.left); - dfs(node.right); - } + res.push(String(node.val)); + dfs(node.left); + dfs(node.right); + } - dfs(root); - return res.join(','); + dfs(root); + return res.join(','); }; /** @@ -37,23 +37,23 @@ var serialize = function (root) { * @return {TreeNode} */ var deserialize = function (data) { - const vals = data.split(','); - let i = 0; - - function dfs() { - if (vals[i] === 'N') { - i++; - return null; + const vals = data.split(','); + let i = 0; + + function dfs() { + if (vals[i] === 'N') { + i++; + return null; + } + + const node = new TreeNode(parseInt(vals[i])); + i++; + node.left = dfs(); + node.right = dfs(); + return node; } - const node = new TreeNode(parseInt(vals[i])); - i++; - node.left = dfs(); - node.right = dfs(); - return node; - } - - return dfs(); + return dfs(); }; /** diff --git a/javascript/3-Longest-Substring-Without-Repeating-Characters.js b/javascript/3-Longest-Substring-Without-Repeating-Characters.js index 7506b5319..26ab1e7a7 100644 --- a/javascript/3-Longest-Substring-Without-Repeating-Characters.js +++ b/javascript/3-Longest-Substring-Without-Repeating-Characters.js @@ -1,22 +1,22 @@ var lengthOfLongestSubstring = function (str) { - const hash = {}; - let start = 0; - let max = 0; + const hash = {}; + let start = 0; + let max = 0; - for (let i = 0; i < str.length; i++) { - let rightChar = str[i]; + for (let i = 0; i < str.length; i++) { + let rightChar = str[i]; - if (!(rightChar in hash)) hash[rightChar] = 0; - hash[rightChar] += 1; + if (!(rightChar in hash)) hash[rightChar] = 0; + hash[rightChar] += 1; - while (hash[rightChar] > 1) { - let leftChar = str[start]; - start += 1; + while (hash[rightChar] > 1) { + let leftChar = str[start]; + start += 1; - if (leftChar in hash) hash[leftChar] -= 1; - if (hash[leftChar] === 0) delete hash[leftChar]; + if (leftChar in hash) hash[leftChar] -= 1; + if (hash[leftChar] === 0) delete hash[leftChar]; + } + max = Math.max(max, i - start + 1); } - max = Math.max(max, i - start + 1); - } - return max; + return max; }; diff --git a/javascript/300-Longest-Increasing-Subsequence.js b/javascript/300-Longest-Increasing-Subsequence.js index e223335e9..a323e3fc7 100644 --- a/javascript/300-Longest-Increasing-Subsequence.js +++ b/javascript/300-Longest-Increasing-Subsequence.js @@ -1,12 +1,12 @@ var lengthOfLIS = function (nums) { - let arr = Array(nums.length).fill(1); + let arr = Array(nums.length).fill(1); - for (let i = 1; i < arr.length; i++) { - for (let j = 0; j < i; j++) { - if (nums[i] > nums[j]) { - arr[i] = Math.max(arr[i], arr[j] + 1); - } + for (let i = 1; i < arr.length; i++) { + for (let j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + arr[i] = Math.max(arr[i], arr[j] + 1); + } + } } - } - return Math.max(...arr); + return Math.max(...arr); }; diff --git a/javascript/322-Coin-Change.js b/javascript/322-Coin-Change.js index b25f64913..0afe24f34 100644 --- a/javascript/322-Coin-Change.js +++ b/javascript/322-Coin-Change.js @@ -4,14 +4,14 @@ * @return {number} */ var coinChange = function (coins, amount) { - let dp = Array(amount + 1).fill(amount + 1); - dp[0] = 0; - for (let i = 1; i < dp.length; i++) { - for (const coin of coins) { - if (i - coin >= 0) { - dp[i] = Math.min(dp[i], 1 + dp[i - coin]); - } + let dp = Array(amount + 1).fill(amount + 1); + dp[0] = 0; + for (let i = 1; i < dp.length; i++) { + for (const coin of coins) { + if (i - coin >= 0) { + dp[i] = Math.min(dp[i], 1 + dp[i - coin]); + } + } } - } - return dp[amount] === amount + 1 ? -1 : dp.pop(); + return dp[amount] === amount + 1 ? -1 : dp.pop(); }; diff --git a/javascript/323-countComponents.js b/javascript/323-countComponents.js index 76a83f273..174a9c08b 100644 --- a/javascript/323-countComponents.js +++ b/javascript/323-countComponents.js @@ -1,38 +1,38 @@ function buildGraph(n, edges) { - const graph = Array.from({ length: n }, () => []); + const graph = Array.from({ length: n }, () => []); - for (let edge of edges) { - let [a, b] = edge; + for (let edge of edges) { + let [a, b] = edge; - if (!(a in graph)) graph[a] = []; - if (!(b in graph)) graph[b] = []; + if (!(a in graph)) graph[a] = []; + if (!(b in graph)) graph[b] = []; - graph[a].push(b); - graph[b].push(a); - } - return graph; + graph[a].push(b); + graph[b].push(a); + } + return graph; } var countComponents = function (n, edges) { - const graph = buildGraph(n, edges); - let count = 0; - let visited = new Set(); + const graph = buildGraph(n, edges); + let count = 0; + let visited = new Set(); - function explore(graph, current, visited) { - if (visited.has(current.toString())) return; + function explore(graph, current, visited) { + if (visited.has(current.toString())) return; - visited.add(current.toString()); + visited.add(current.toString()); - for (let neighbor of graph[current]) { - explore(graph, neighbor, visited); + for (let neighbor of graph[current]) { + explore(graph, neighbor, visited); + } + return true; } - return true; - } - for (let node in graph) { - if (explore(graph, node, visited)) { - count += 1; + for (let node in graph) { + if (explore(graph, node, visited)) { + count += 1; + } } - } - return count; + return count; }; diff --git a/javascript/33-Search-in-Rotated-Sorted-Array.js b/javascript/33-Search-in-Rotated-Sorted-Array.js index a5af31b96..96fcd8cbb 100644 --- a/javascript/33-Search-in-Rotated-Sorted-Array.js +++ b/javascript/33-Search-in-Rotated-Sorted-Array.js @@ -4,38 +4,38 @@ * @return {number} */ var search = function (nums, target) { - let left = 0; - let right = nums.length - 1; + let left = 0; + let right = nums.length - 1; - while (left <= right) { - let mid = Math.floor((left + right) / 2); + while (left <= right) { + let mid = Math.floor((left + right) / 2); - if (nums[mid] === target) { - return mid; - } + if (nums[mid] === target) { + return mid; + } - // Checking if the left side is sorted - if (nums[left] <= nums[mid]) { - if (nums[left] <= target && target <= nums[mid]) { - // thus target is in the left - right = mid - 1; - } else { - // thus target is in the right - left = mid + 1; - } - } + // Checking if the left side is sorted + if (nums[left] <= nums[mid]) { + if (nums[left] <= target && target <= nums[mid]) { + // thus target is in the left + right = mid - 1; + } else { + // thus target is in the right + left = mid + 1; + } + } - // Otherwise, the right side is sorted - else { - if (nums[mid] <= target && target <= nums[right]) { - // thus target is in the right - left = mid + 1; - } else { - // thus target is in the left - right = mid - 1; - } + // Otherwise, the right side is sorted + else { + if (nums[mid] <= target && target <= nums[right]) { + // thus target is in the right + left = mid + 1; + } else { + // thus target is in the left + right = mid - 1; + } + } } - } - return -1; + return -1; }; diff --git a/javascript/332-Reconstruct-Itinerary.js b/javascript/332-Reconstruct-Itinerary.js index 8c3e450c8..6e8c444e2 100644 --- a/javascript/332-Reconstruct-Itinerary.js +++ b/javascript/332-Reconstruct-Itinerary.js @@ -3,42 +3,42 @@ * @return {string[]} */ var findItinerary = function (tickets) { - const flight_paths = new Map(); - const flight_path_order = ['JFK']; - - tickets = tickets.sort(); - - for (const [source, dest] of tickets) { - let edges = []; - if (flight_paths.has(source)) { - edges = flight_paths.get(source); + const flight_paths = new Map(); + const flight_path_order = ['JFK']; + + tickets = tickets.sort(); + + for (const [source, dest] of tickets) { + let edges = []; + if (flight_paths.has(source)) { + edges = flight_paths.get(source); + } + edges.push(dest); + flight_paths.set(source, edges); } - edges.push(dest); - flight_paths.set(source, edges); - } - const depth_first_search = (city) => { - if (flight_path_order.length === tickets.length + 1) return true; + const depth_first_search = (city) => { + if (flight_path_order.length === tickets.length + 1) return true; - const cities_to_go_to = flight_paths.get(city) || []; - if (!cities_to_go_to.length) return false; + const cities_to_go_to = flight_paths.get(city) || []; + if (!cities_to_go_to.length) return false; - const cities_copied = Array.from(cities_to_go_to); + const cities_copied = Array.from(cities_to_go_to); - for (const other_city of cities_copied) { - flight_path_order.push(other_city); - cities_to_go_to.shift(); + for (const other_city of cities_copied) { + flight_path_order.push(other_city); + cities_to_go_to.shift(); - if (depth_first_search(other_city)) { - return flight_path_order; - } else { - flight_path_order.pop(); - cities_to_go_to.push(other_city); - } - } + if (depth_first_search(other_city)) { + return flight_path_order; + } else { + flight_path_order.pop(); + cities_to_go_to.push(other_city); + } + } - return false; - }; + return false; + }; - return depth_first_search('JFK'); + return depth_first_search('JFK'); }; diff --git a/javascript/338-Counting-Bits.js b/javascript/338-Counting-Bits.js index e5685401d..70b773e42 100644 --- a/javascript/338-Counting-Bits.js +++ b/javascript/338-Counting-Bits.js @@ -3,9 +3,9 @@ * @return {number[]} */ var countBits = function (n) { - let output = [0]; - for (let i = 1; i < n + 1; i++) { - output.push(output[i >> 1] + (i & 1)); - } - return output; + let output = [0]; + for (let i = 1; i < n + 1; i++) { + output.push(output[i >> 1] + (i & 1)); + } + return output; }; diff --git a/javascript/347-Top-K-Frequent-Elements.js b/javascript/347-Top-K-Frequent-Elements.js index 3b6a5e8da..baa84b6b5 100644 --- a/javascript/347-Top-K-Frequent-Elements.js +++ b/javascript/347-Top-K-Frequent-Elements.js @@ -4,27 +4,27 @@ * @return {number[]} */ var topKFrequent = function (nums, k) { - let map = new Map(); - let res = []; - let bucket = Array.from({ length: nums.length + 1 }, () => []); // to create unique arrays + let map = new Map(); + let res = []; + let bucket = Array.from({ length: nums.length + 1 }, () => []); // to create unique arrays - // storing frequency of numbers in a map - for (let n of nums) { - map.set(n, map.has(n) ? 1 + map.get(n) : 1); - } + // storing frequency of numbers in a map + for (let n of nums) { + map.set(n, map.has(n) ? 1 + map.get(n) : 1); + } - // Poppulate the bucket with numbers in frequency - // as the index of the bucket - for (const [key, value] of map.entries()) { - bucket[value].push(key); - } + // Poppulate the bucket with numbers in frequency + // as the index of the bucket + for (const [key, value] of map.entries()) { + bucket[value].push(key); + } - for (let i = bucket.length - 1; i >= 0; i--) { - if (bucket[i].length > 0) { - for (let n of bucket[i]) { - res.push(n); - if (res.length === k) return res; - } + for (let i = bucket.length - 1; i >= 0; i--) { + if (bucket[i].length > 0) { + for (let n of bucket[i]) { + res.push(n); + if (res.length === k) return res; + } + } } - } }; diff --git a/javascript/347-Top-K-Frquent-Elements.js b/javascript/347-Top-K-Frquent-Elements.js index 3b6a5e8da..baa84b6b5 100644 --- a/javascript/347-Top-K-Frquent-Elements.js +++ b/javascript/347-Top-K-Frquent-Elements.js @@ -4,27 +4,27 @@ * @return {number[]} */ var topKFrequent = function (nums, k) { - let map = new Map(); - let res = []; - let bucket = Array.from({ length: nums.length + 1 }, () => []); // to create unique arrays + let map = new Map(); + let res = []; + let bucket = Array.from({ length: nums.length + 1 }, () => []); // to create unique arrays - // storing frequency of numbers in a map - for (let n of nums) { - map.set(n, map.has(n) ? 1 + map.get(n) : 1); - } + // storing frequency of numbers in a map + for (let n of nums) { + map.set(n, map.has(n) ? 1 + map.get(n) : 1); + } - // Poppulate the bucket with numbers in frequency - // as the index of the bucket - for (const [key, value] of map.entries()) { - bucket[value].push(key); - } + // Poppulate the bucket with numbers in frequency + // as the index of the bucket + for (const [key, value] of map.entries()) { + bucket[value].push(key); + } - for (let i = bucket.length - 1; i >= 0; i--) { - if (bucket[i].length > 0) { - for (let n of bucket[i]) { - res.push(n); - if (res.length === k) return res; - } + for (let i = bucket.length - 1; i >= 0; i--) { + if (bucket[i].length > 0) { + for (let n of bucket[i]) { + res.push(n); + if (res.length === k) return res; + } + } } - } }; diff --git a/javascript/35-Search-Insert-Position.js b/javascript/35-Search-Insert-Position.js index c4ce6ff93..a3ce8654d 100644 --- a/javascript/35-Search-Insert-Position.js +++ b/javascript/35-Search-Insert-Position.js @@ -4,20 +4,20 @@ * @return {number} */ var searchInsert = function (nums, target) { - let left = 0; - let right = nums.length - 1; - while (left <= right) { - let midIdx = Math.floor((left + right) / 2); - if (target === nums[midIdx]) { - return midIdx; - } + let left = 0; + let right = nums.length - 1; + while (left <= right) { + let midIdx = Math.floor((left + right) / 2); + if (target === nums[midIdx]) { + return midIdx; + } - if (target > nums[midIdx]) { - left = midIdx + 1; - } else { - right = midIdx - 1; + if (target > nums[midIdx]) { + left = midIdx + 1; + } else { + right = midIdx - 1; + } } - } - return left; + return left; }; diff --git a/javascript/36-Valid-Sudoku.js b/javascript/36-Valid-Sudoku.js index 570930a72..02cf65f14 100644 --- a/javascript/36-Valid-Sudoku.js +++ b/javascript/36-Valid-Sudoku.js @@ -3,39 +3,43 @@ * @return {boolean} */ function isValidSudoku(board) { - const rows = {}; - const cols = {}; - const squares = {}; + const rows = {}; + const cols = {}; + const squares = {}; - for (let r = 0; r < 9; r++) { - for (let c = 0; c < 9; c++) { - const num = board[r][c]; + for (let r = 0; r < 9; r++) { + for (let c = 0; c < 9; c++) { + const num = board[r][c]; - if (num === '.') { - continue; - } + if (num === '.') { + continue; + } - const grid = `${Math.floor(r / 3)}${Math.floor(c / 3)}`; + const grid = `${Math.floor(r / 3)}${Math.floor(c / 3)}`; - if (!cols[c]) { - cols[c] = new Set(); - } - if (!rows[r]) { - rows[r] = new Set(); - } - if (!squares[grid]) { - squares[grid] = new Set(); - } + if (!cols[c]) { + cols[c] = new Set(); + } + if (!rows[r]) { + rows[r] = new Set(); + } + if (!squares[grid]) { + squares[grid] = new Set(); + } - if (rows[r].has(num) || cols[c].has(num) || squares[grid].has(num)) { - return false; - } + if ( + rows[r].has(num) || + cols[c].has(num) || + squares[grid].has(num) + ) { + return false; + } - cols[c].add(num); - rows[r].add(num); - squares[grid].add(num); + cols[c].add(num); + rows[r].add(num); + squares[grid].add(num); + } } - } - return true; + return true; } diff --git a/javascript/371-Sum-of-Two-Integers.js b/javascript/371-Sum-of-Two-Integers.js index ca0976262..7aa7e83be 100644 --- a/javascript/371-Sum-of-Two-Integers.js +++ b/javascript/371-Sum-of-Two-Integers.js @@ -1,12 +1,12 @@ var getSum = function (a, b) { - let tb = b; - let res = a; + let tb = b; + let res = a; - while (tb) { - let temp = (res & tb) << 1; - res = res ^ tb; - tb = temp; - } + while (tb) { + let temp = (res & tb) << 1; + res = res ^ tb; + tb = temp; + } - return res; + return res; }; diff --git a/javascript/39-Combination-Sum.js b/javascript/39-Combination-Sum.js index 381f8932b..8976a5592 100644 --- a/javascript/39-Combination-Sum.js +++ b/javascript/39-Combination-Sum.js @@ -10,31 +10,35 @@ * @return {number[][]} */ function combinationSum(candidates, target) { - candidates.sort((a, b) => a - b); - const combos = []; - const combo = []; - const set = new Set(candidates); - buildCombos(target); - return combos; + candidates.sort((a, b) => a - b); + const combos = []; + const combo = []; + const set = new Set(candidates); + buildCombos(target); + return combos; - /** - * @param {number} target - * @param {number=} start = `0` - * @return {void} - */ - function buildCombos(target, start = 0) { - if (set.has(target)) { - combo.push(target); - combos.push(combo.slice()); - combo.pop(); - } + /** + * @param {number} target + * @param {number=} start = `0` + * @return {void} + */ + function buildCombos(target, start = 0) { + if (set.has(target)) { + combo.push(target); + combos.push(combo.slice()); + combo.pop(); + } - const mid = Math.floor(target / 2); - for (let i = start; i < candidates.length && candidates[i] <= mid; ++i) { - const candidate = candidates[i]; - combo.push(candidate); - buildCombos(target - candidate, i); - combo.pop(); + const mid = Math.floor(target / 2); + for ( + let i = start; + i < candidates.length && candidates[i] <= mid; + ++i + ) { + const candidate = candidates[i]; + combo.push(candidate); + buildCombos(target - candidate, i); + combo.pop(); + } } - } } diff --git a/javascript/4-Median-Of-Two-Sorted-Arrays.js b/javascript/4-Median-Of-Two-Sorted-Arrays.js index f5e013ab5..0e04693c8 100644 --- a/javascript/4-Median-Of-Two-Sorted-Arrays.js +++ b/javascript/4-Median-Of-Two-Sorted-Arrays.js @@ -4,31 +4,31 @@ * @return {number} */ var findMedianSortedArrays = function (nums1, nums2) { - let [A, B] = [nums1, nums2]; - const total = nums1.length + nums2.length; - const half = Math.floor(total / 2); + let [A, B] = [nums1, nums2]; + const total = nums1.length + nums2.length; + const half = Math.floor(total / 2); - if (B.length < A.length) { - [A, B] = [B, A]; - } + if (B.length < A.length) { + [A, B] = [B, A]; + } - let [l, r] = [0, A.length - 1]; - while (true) { - const i = l + r; - const j = half - i - 2; + let [l, r] = [0, A.length - 1]; + while (true) { + const i = l + r; + const j = half - i - 2; - const Aleft = i >= 0 ? A[i] : -Infinity; - const Aright = i + 1 < A.length ? A[i + 1] : Infinity; - const Bleft = j >= 0 ? B[j] : -Infinity; - const Bright = j + 1 < B.length ? B[j + 1] : Infinity; + const Aleft = i >= 0 ? A[i] : -Infinity; + const Aright = i + 1 < A.length ? A[i + 1] : Infinity; + const Bleft = j >= 0 ? B[j] : -Infinity; + const Bright = j + 1 < B.length ? B[j + 1] : Infinity; - if (Aleft <= Bright && Bleft <= Aright) { - if (total % 2) { - return Math.min(Aright, Bright); - } + if (Aleft <= Bright && Bleft <= Aright) { + if (total % 2) { + return Math.min(Aright, Bright); + } - return (Math.max(Aleft, Bleft) + Math.min(Aright, Bright)) / 2; - } else if (Aleft > Bright) r = i - 1; - else l = i + 1; - } + return (Math.max(Aleft, Bleft) + Math.min(Aright, Bright)) / 2; + } else if (Aleft > Bright) r = i - 1; + else l = i + 1; + } }; diff --git a/javascript/40-Combination-Sum-II.js b/javascript/40-Combination-Sum-II.js index ca541c911..df1a22b78 100644 --- a/javascript/40-Combination-Sum-II.js +++ b/javascript/40-Combination-Sum-II.js @@ -10,39 +10,43 @@ * @return {number[][]} */ function combinationSum2(candidates, target) { - candidates.sort((a, b) => a - b); + candidates.sort((a, b) => a - b); - const combos = []; - const combo = []; - const map = Object.create(null); + const combos = []; + const combo = []; + const map = Object.create(null); - for (let i = 0; i < candidates.length; ++i) { - map[candidates[i]] = i; - } + for (let i = 0; i < candidates.length; ++i) { + map[candidates[i]] = i; + } - getCombos(target); - return combos; + getCombos(target); + return combos; - /** - * @param {number} target - * @param {number=} start = `0` - * @return {void} - */ - function getCombos(target, start = 0) { - if (target in map && start <= map[target]) { - combo.push(target); - combos.push(combo.slice()); - combo.pop(); - } + /** + * @param {number} target + * @param {number=} start = `0` + * @return {void} + */ + function getCombos(target, start = 0) { + if (target in map && start <= map[target]) { + combo.push(target); + combos.push(combo.slice()); + combo.pop(); + } - const mid = Math.floor(target / 2); - for (let i = start; i < candidates.length && candidates[i] <= mid; ++i) { - if (i !== start && candidates[i] === candidates[i - 1]) { - continue; - } - combo.push(candidates[i]); - getCombos(target - candidates[i], i + 1); - combo.pop(); + const mid = Math.floor(target / 2); + for ( + let i = start; + i < candidates.length && candidates[i] <= mid; + ++i + ) { + if (i !== start && candidates[i] === candidates[i - 1]) { + continue; + } + combo.push(candidates[i]); + getCombos(target - candidates[i], i + 1); + combo.pop(); + } } - } } diff --git a/javascript/417-Pacific-Atlantic-Water-Flow.js b/javascript/417-Pacific-Atlantic-Water-Flow.js index 4c247acfb..87a8faf8f 100644 --- a/javascript/417-Pacific-Atlantic-Water-Flow.js +++ b/javascript/417-Pacific-Atlantic-Water-Flow.js @@ -11,10 +11,10 @@ ////////////////////////////////////////////////////////////////////////////// class Drains { - constructor(west = false, east = false) { - this.west = west; - this.east = east; - } + constructor(west = false, east = false) { + this.west = west; + this.east = east; + } } /** @@ -22,73 +22,73 @@ class Drains { * @return {number[][]} */ function pacificAtlantic(heights) { - const rowLen = heights.length; - const colLen = heights[0].length; - const lastRow = rowLen - 1; - const lastCol = colLen - 1; - const drainage = new Array(rowLen); - const drainsBoth = []; + const rowLen = heights.length; + const colLen = heights[0].length; + const lastRow = rowLen - 1; + const lastCol = colLen - 1; + const drainage = new Array(rowLen); + const drainsBoth = []; + + for (let r = 0; r < rowLen; ++r) { + drainage[r] = new Array(colLen); + for (let c = 0; c < colLen; ++c) { + drainage[r][c] = new Drains(); + } + } - for (let r = 0; r < rowLen; ++r) { - drainage[r] = new Array(colLen); + for (let r = 0; r < rowLen; ++r) { + markDrainage(r, 0, true); + markDrainage(r, lastCol); + } for (let c = 0; c < colLen; ++c) { - drainage[r][c] = new Drains(); + markDrainage(0, c, true); + markDrainage(lastRow, c); } - } - for (let r = 0; r < rowLen; ++r) { - markDrainage(r, 0, true); - markDrainage(r, lastCol); - } - for (let c = 0; c < colLen; ++c) { - markDrainage(0, c, true); - markDrainage(lastRow, c); - } + return drainsBoth; - return drainsBoth; + /** + * @param {number} r + * @param {number} c + * @param {boolean=} west = `false` + * @param {number=} prev = `-Infinity` + * @return {void} + */ + function markDrainage(r, c, west = false, prev = -Infinity) { + if ( + !inBounds(r, c) || + heights[r][c] < prev || + (west && drainage[r][c].west) || + (!west && drainage[r][c].east) + ) { + return; + } - /** - * @param {number} r - * @param {number} c - * @param {boolean=} west = `false` - * @param {number=} prev = `-Infinity` - * @return {void} - */ - function markDrainage(r, c, west = false, prev = -Infinity) { - if ( - !inBounds(r, c) || - heights[r][c] < prev || - (west && drainage[r][c].west) || - (!west && drainage[r][c].east) - ) { - return; - } + const drains = drainage[r][c]; + const height = heights[r][c]; - const drains = drainage[r][c]; - const height = heights[r][c]; + if (west) { + drains.west = true; + } else { + drains.east = true; + } - if (west) { - drains.west = true; - } else { - drains.east = true; - } + if (drains.west && drains.east) { + drainsBoth.push([r, c]); + } - if (drains.west && drains.east) { - drainsBoth.push([r, c]); + markDrainage(r - 1, c, west, height); + markDrainage(r + 1, c, west, height); + markDrainage(r, c - 1, west, height); + markDrainage(r, c + 1, west, height); } - markDrainage(r - 1, c, west, height); - markDrainage(r + 1, c, west, height); - markDrainage(r, c - 1, west, height); - markDrainage(r, c + 1, west, height); - } - - /** - * @param {number} r - * @param {number} c - * @return {boolean} - */ - function inBounds(r, c) { - return r >= 0 && c >= 0 && r < rowLen && c < colLen; - } + /** + * @param {number} r + * @param {number} c + * @return {boolean} + */ + function inBounds(r, c) { + return r >= 0 && c >= 0 && r < rowLen && c < colLen; + } } diff --git a/javascript/42-Trapping-Rain-Water.js b/javascript/42-Trapping-Rain-Water.js index 10adc430d..866f077c7 100644 --- a/javascript/42-Trapping-Rain-Water.js +++ b/javascript/42-Trapping-Rain-Water.js @@ -7,31 +7,31 @@ * @return {number} */ function trap(heights) { - let l = 0; - let r = heights.length - 1; - let lMax = 0; - let rMax = 0; - let total = 0; - - while (l < r) { - if (heights[l] < heights[r]) { - if (heights[l] >= lMax) { - lMax = heights[l]; - } else { - total += lMax - heights[l]; - } - ++l; - } else { - if (heights[r] >= rMax) { - rMax = heights[r]; - } else { - total += rMax - heights[r]; - } - --r; + let l = 0; + let r = heights.length - 1; + let lMax = 0; + let rMax = 0; + let total = 0; + + while (l < r) { + if (heights[l] < heights[r]) { + if (heights[l] >= lMax) { + lMax = heights[l]; + } else { + total += lMax - heights[l]; + } + ++l; + } else { + if (heights[r] >= rMax) { + rMax = heights[r]; + } else { + total += rMax - heights[r]; + } + --r; + } } - } - return total; + return total; } ////////////////////////////////////////////////////////////////////////////// @@ -43,27 +43,27 @@ function trap(heights) { * @return {number} */ function trap(heights) { - const stack = []; - let total = 0; + const stack = []; + let total = 0; - for (let i = 0; i < heights.length; ++i) { - while (stack.length && heights[i] > heights[top(stack)]) { - const j = stack.pop(); + for (let i = 0; i < heights.length; ++i) { + while (stack.length && heights[i] > heights[top(stack)]) { + const j = stack.pop(); - if (!stack.length) { - break; - } + if (!stack.length) { + break; + } - const k = top(stack); - const spread = i - k - 1; - const height = Math.min(heights[i], heights[k]) - heights[j]; - total += spread * height; - } + const k = top(stack); + const spread = i - k - 1; + const height = Math.min(heights[i], heights[k]) - heights[j]; + total += spread * height; + } - stack.push(i); - } + stack.push(i); + } - return total; + return total; } /** @@ -71,7 +71,7 @@ function trap(heights) { * @return {*} */ function top(stack) { - return stack[stack.length - 1]; + return stack[stack.length - 1]; } ////////////////////////////////////////////////////////////////////////////// @@ -83,37 +83,37 @@ function top(stack) { * @return {number} */ function trap(heights) { - let valley = []; - let barrier = 0; - let trapped = 0; - - for (const height of heights) { - if (height >= barrier) { - while (valley.length) { - trapped += barrier - valley.pop(); - } - barrier = height; - } else { - valley.push(height); + let valley = []; + let barrier = 0; + let trapped = 0; + + for (const height of heights) { + if (height >= barrier) { + while (valley.length) { + trapped += barrier - valley.pop(); + } + barrier = height; + } else { + valley.push(height); + } } - } - - valley.reverse(); - valley.push(barrier); - heights = valley; - valley = []; - barrier = 0; - - for (const height of heights) { - if (height >= barrier) { - while (valley.length) { - trapped += barrier - valley.pop(); - } - barrier = height; - } else { - valley.push(height); + + valley.reverse(); + valley.push(barrier); + heights = valley; + valley = []; + barrier = 0; + + for (const height of heights) { + if (height >= barrier) { + while (valley.length) { + trapped += barrier - valley.pop(); + } + barrier = height; + } else { + valley.push(height); + } } - } - return trapped; + return trapped; } diff --git a/javascript/424-Longest-Repeating-Character-Replacement.js b/javascript/424-Longest-Repeating-Character-Replacement.js index 9f51c627b..5536c3633 100644 --- a/javascript/424-Longest-Repeating-Character-Replacement.js +++ b/javascript/424-Longest-Repeating-Character-Replacement.js @@ -4,27 +4,27 @@ * @return {number} */ var characterReplacement = function (s, k) { - let sCharacterSet = {}; - let result = 0; - let l = 0; - let maxLength = 0; + let sCharacterSet = {}; + let result = 0; + let l = 0; + let maxLength = 0; - for (let r = 0; r < s.length; r++) { - if (sCharacterSet[s[r]] !== undefined) { - sCharacterSet[s[r]] = 1 + sCharacterSet[s[r]]; - } else { - sCharacterSet[s[r]] = 1; - } + for (let r = 0; r < s.length; r++) { + if (sCharacterSet[s[r]] !== undefined) { + sCharacterSet[s[r]] = 1 + sCharacterSet[s[r]]; + } else { + sCharacterSet[s[r]] = 1; + } - maxLength = Math.max(maxLength, sCharacterSet[s[r]]); + maxLength = Math.max(maxLength, sCharacterSet[s[r]]); - if (r - l + 1 - maxLength > k) { - sCharacterSet[s[l]] -= 1; - l += 1; - } + if (r - l + 1 - maxLength > k) { + sCharacterSet[s[l]] -= 1; + l += 1; + } - result = Math.max(result, r - l + 1); - } + result = Math.max(result, r - l + 1); + } - return result; + return result; }; diff --git a/javascript/435-Non-overlapping-Intervals.js b/javascript/435-Non-overlapping-Intervals.js index e72d7d108..5b3e7f6a7 100644 --- a/javascript/435-Non-overlapping-Intervals.js +++ b/javascript/435-Non-overlapping-Intervals.js @@ -1,17 +1,17 @@ let eraseOverlapIntervals = function (intervals) { - intervals = intervals.sort((a, b) => a[0] - b[1]); + intervals = intervals.sort((a, b) => a[0] - b[1]); - let currentEnd = intervals[0][1]; - let res = 0; + let currentEnd = intervals[0][1]; + let res = 0; - for (let i = 1; i < intervals.length; i++) { - if (currentEnd > intervals[i][0]) { - res += 1; - currentEnd = Math.min(intervals[i][1], currentEnd); - } else { - currentEnd = intervals[i][1]; + for (let i = 1; i < intervals.length; i++) { + if (currentEnd > intervals[i][0]) { + res += 1; + currentEnd = Math.min(intervals[i][1], currentEnd); + } else { + currentEnd = intervals[i][1]; + } } - } - return res; + return res; }; diff --git a/javascript/46-Permutations.js b/javascript/46-Permutations.js index d86c0a650..3f0c90e05 100644 --- a/javascript/46-Permutations.js +++ b/javascript/46-Permutations.js @@ -1,25 +1,25 @@ function permute(nums) { - const res = []; + const res = []; - if (nums.length === 1) { - return [nums.slice()]; - } + if (nums.length === 1) { + return [nums.slice()]; + } - for (const i of nums) { - let n = nums.shift(); + for (const i of nums) { + let n = nums.shift(); - let perms = permute(nums); + let perms = permute(nums); - for (const perm of perms) { - perm.push(n); - } + for (const perm of perms) { + perm.push(n); + } - perms.forEach((perm) => { - res.push(perm); - }); + perms.forEach((perm) => { + res.push(perm); + }); - nums.push(n); - } + nums.push(n); + } - return res; + return res; } diff --git a/javascript/473-Matchsticks-To-Square.js b/javascript/473-Matchsticks-To-Square.js index 5899006bd..4e77ee436 100644 --- a/javascript/473-Matchsticks-To-Square.js +++ b/javascript/473-Matchsticks-To-Square.js @@ -1,11 +1,11 @@ function check(arr) { - let temp = arr[0]; - for (let i = 1; i < arr.length; i++) { - if (arr[i] !== temp) { - return false; + let temp = arr[0]; + for (let i = 1; i < arr.length; i++) { + if (arr[i] !== temp) { + return false; + } } - } - return true; + return true; } /** @@ -13,37 +13,37 @@ function check(arr) { * @return {boolean} */ var makesquare = function (matchsticks) { - let sides = new Array(4).fill(0), - ans = false, - size = 0; + let sides = new Array(4).fill(0), + ans = false, + size = 0; - for (let i = 0; i < matchsticks.length; i++) { - size += matchsticks[i]; - } - let max_size = size / 4; - if (max_size - Math.floor(max_size) !== 0) return false; + for (let i = 0; i < matchsticks.length; i++) { + size += matchsticks[i]; + } + let max_size = size / 4; + if (max_size - Math.floor(max_size) !== 0) return false; - matchsticks = matchsticks.sort((a, b) => b - a); + matchsticks = matchsticks.sort((a, b) => b - a); - function backtrack(i) { - if (ans) return; - if (i >= matchsticks.length) { - if (check(sides)) { - ans = true; - } - return; - } - for (let j = 0; j < 4; j++) { - if (sides[j] + matchsticks[i] > max_size) { - continue; - } - sides[j] += matchsticks[i]; + function backtrack(i) { + if (ans) return; + if (i >= matchsticks.length) { + if (check(sides)) { + ans = true; + } + return; + } + for (let j = 0; j < 4; j++) { + if (sides[j] + matchsticks[i] > max_size) { + continue; + } + sides[j] += matchsticks[i]; - backtrack(i + 1); - sides[j] -= matchsticks[i]; + backtrack(i + 1); + sides[j] -= matchsticks[i]; + } } - } - backtrack(0); + backtrack(0); - return ans; + return ans; }; diff --git a/javascript/49-Group-Anagrams.js b/javascript/49-Group-Anagrams.js index 01d6a73f0..5874ea653 100644 --- a/javascript/49-Group-Anagrams.js +++ b/javascript/49-Group-Anagrams.js @@ -7,32 +7,32 @@ /** @const {!Object} */ const CODES = { - a: 0, - b: 1, - c: 2, - d: 3, - e: 4, - f: 5, - g: 6, - h: 7, - i: 8, - j: 9, - k: 10, - l: 11, - m: 12, - n: 13, - o: 14, - p: 15, - q: 16, - r: 17, - s: 18, - t: 19, - u: 20, - v: 21, - w: 22, - x: 23, - y: 24, - z: 25, + a: 0, + b: 1, + c: 2, + d: 3, + e: 4, + f: 5, + g: 6, + h: 7, + i: 8, + j: 9, + k: 10, + l: 11, + m: 12, + n: 13, + o: 14, + p: 15, + q: 16, + r: 17, + s: 18, + t: 19, + u: 20, + v: 21, + w: 22, + x: 23, + y: 24, + z: 25, }; /** @@ -40,20 +40,20 @@ const CODES = { * @return {string[][]} */ function groupAnagrams(words) { - const map = Object.create(null); - for (const word of words) { - const hash = hashWord(word); - if (!(hash in map)) { - map[hash] = []; + const map = Object.create(null); + for (const word of words) { + const hash = hashWord(word); + if (!(hash in map)) { + map[hash] = []; + } + map[hash].push(word); } - map[hash].push(word); - } - const groups = []; - for (const key in map) { - groups.push(map[key]); - } - return groups; + const groups = []; + for (const key in map) { + groups.push(map[key]); + } + return groups; } /** @@ -61,11 +61,11 @@ function groupAnagrams(words) { * @return {string} */ function hashWord(word) { - const hash = new Array(26).fill(0); - for (const ch of word) { - ++hash[CODES[ch]]; - } - return hash.toString(); + const hash = new Array(26).fill(0); + for (const ch of word) { + ++hash[CODES[ch]]; + } + return hash.toString(); } ////////////////////////////////////////////////////////////////////////////// @@ -80,20 +80,20 @@ function hashWord(word) { * @return {string[][]} */ const groupAnagrams = (strs) => { - const result = []; - const map = new Map(); - for (let i = 0; i < strs.length; i++) { - const sorted = strs[i].split('').sort().join(''); - //! we are just splitting the string and sorting it and joining it back - if (map.has(sorted)) { - map.get(sorted).push(strs[i]); //! if the map has the sorted string, we push the string into the array - } else { - map.set(sorted, [strs[i]]); //! we are pushing the string into the map with the sorted string as the key + const result = []; + const map = new Map(); + for (let i = 0; i < strs.length; i++) { + const sorted = strs[i].split('').sort().join(''); + //! we are just splitting the string and sorting it and joining it back + if (map.has(sorted)) { + map.get(sorted).push(strs[i]); //! if the map has the sorted string, we push the string into the array + } else { + map.set(sorted, [strs[i]]); //! we are pushing the string into the map with the sorted string as the key + } } - } - for (let [key, value] of map) { - result.push(value); - } - return result; + for (let [key, value] of map) { + result.push(value); + } + return result; }; diff --git a/javascript/49-Rotate-Image.js b/javascript/49-Rotate-Image.js index 50f6f8e9d..7b5fe174a 100644 --- a/javascript/49-Rotate-Image.js +++ b/javascript/49-Rotate-Image.js @@ -3,28 +3,28 @@ * @return {void} Do not return anything, modify matrix in-place instead. */ var rotate = function (matrix) { - transpose(matrix); - reflect(matrix); + transpose(matrix); + reflect(matrix); }; var transpose = function (matrix) { - let n = matrix.length; - for (let i = 0; i < n; i++) { - for (let j = i + 1; j < n; j++) { - let temp = matrix[j][i]; - matrix[j][i] = matrix[i][j]; - matrix[i][j] = temp; + let n = matrix.length; + for (let i = 0; i < n; i++) { + for (let j = i + 1; j < n; j++) { + let temp = matrix[j][i]; + matrix[j][i] = matrix[i][j]; + matrix[i][j] = temp; + } } - } }; var reflect = function (matrix) { - let n = matrix.length; - for (let i = 0; i < n; i++) { - for (let j = 0; j < n / 2; j++) { - let temp = matrix[i][j]; - matrix[i][j] = matrix[i][n - j - 1]; - matrix[i][n - j - 1] = temp; + let n = matrix.length; + for (let i = 0; i < n; i++) { + for (let j = 0; j < n / 2; j++) { + let temp = matrix[i][j]; + matrix[i][j] = matrix[i][n - j - 1]; + matrix[i][n - j - 1] = temp; + } } - } }; diff --git a/javascript/5-Longest-Palindromic-Substring.js b/javascript/5-Longest-Palindromic-Substring.js index aa5c1447f..0366d007b 100644 --- a/javascript/5-Longest-Palindromic-Substring.js +++ b/javascript/5-Longest-Palindromic-Substring.js @@ -1,34 +1,34 @@ function longestPalindrome(s) { - let res = ''; - let resLen = 0; + let res = ''; + let resLen = 0; - for (let i = 0; i < s.length; i++) { - let l = i; - let r = i; + for (let i = 0; i < s.length; i++) { + let l = i; + let r = i; - while (l >= 0 && r < s.length && s[l] === s[r]) { - if (r - l + 1 > resLen) { - res = s.slice(l, r + 1); - resLen = r - l + 1; - } + while (l >= 0 && r < s.length && s[l] === s[r]) { + if (r - l + 1 > resLen) { + res = s.slice(l, r + 1); + resLen = r - l + 1; + } - l -= 1; - r += 1; - } + l -= 1; + r += 1; + } - l = i; - r = i + 1; + l = i; + r = i + 1; - while (l >= 0 && r < s.length && s[l] === s[r]) { - if (r - l + 1 > resLen) { - res = s.slice(l, r + 1); - resLen = r - l + 1; - } + while (l >= 0 && r < s.length && s[l] === s[r]) { + if (r - l + 1 > resLen) { + res = s.slice(l, r + 1); + resLen = r - l + 1; + } - l -= 1; - r += 1; + l -= 1; + r += 1; + } } - } - return res; + return res; } diff --git a/javascript/50. Pow(x, n).js b/javascript/50. Pow(x, n).js index 464b81bd2..97825fb03 100644 --- a/javascript/50. Pow(x, n).js +++ b/javascript/50. Pow(x, n).js @@ -4,16 +4,16 @@ * @return {number} */ var myPow = function (x, n) { - // return Math.pow(x,n).toFixed(5) // One line solution + // return Math.pow(x,n).toFixed(5) // One line solution - if (x === 1.0 || n === 0) return 1; + if (x === 1.0 || n === 0) return 1; - if (n === 1) return x; - else if (n % 2 === 0) { - return myPow(x * x, n / 2); - } else if (n % 2 === 1) { - return x * myPow(x, n - 1); - } else { - return 1 / myPow(x, -n); - } + if (n === 1) return x; + else if (n % 2 === 0) { + return myPow(x * x, n / 2); + } else if (n % 2 === 1) { + return x * myPow(x, n - 1); + } else { + return 1 / myPow(x, -n); + } }; diff --git a/javascript/51-solveNQueens.js b/javascript/51-solveNQueens.js index 8abe65ed2..c2426caaa 100644 --- a/javascript/51-solveNQueens.js +++ b/javascript/51-solveNQueens.js @@ -1,41 +1,41 @@ function solveNQueens(n) { - let col = new Set(); - let posDiag = new Set(); // (r + c) - let negDiag = new Set(); // (r - c) - - let board = new Array(n).fill().map(() => new Array(n).fill('.')); - let res = []; - - function backtrack(r) { - let temp = []; - - if (r === n) { - for (let row of board) { - temp.push(row.join('')); - } - - res.push(temp); - return; - } - - for (let c = 0; c < n; c++) { - if (col.has(c) || posDiag.has(r + c) || negDiag.has(r - c)) { - continue; - } - - col.add(c); - posDiag.add(r + c); - negDiag.add(r - c); - board[r][c] = 'Q'; - - backtrack(r + 1); - - col.delete(c); - posDiag.delete(r + c); - negDiag.delete(r - c); - board[r][c] = '.'; + let col = new Set(); + let posDiag = new Set(); // (r + c) + let negDiag = new Set(); // (r - c) + + let board = new Array(n).fill().map(() => new Array(n).fill('.')); + let res = []; + + function backtrack(r) { + let temp = []; + + if (r === n) { + for (let row of board) { + temp.push(row.join('')); + } + + res.push(temp); + return; + } + + for (let c = 0; c < n; c++) { + if (col.has(c) || posDiag.has(r + c) || negDiag.has(r - c)) { + continue; + } + + col.add(c); + posDiag.add(r + c); + negDiag.add(r - c); + board[r][c] = 'Q'; + + backtrack(r + 1); + + col.delete(c); + posDiag.delete(r + c); + negDiag.delete(r - c); + board[r][c] = '.'; + } } - } - backtrack(0); - return res; + backtrack(0); + return res; } diff --git a/javascript/52-totalNQueens.js b/javascript/52-totalNQueens.js index 084d75df3..c29cd1773 100644 --- a/javascript/52-totalNQueens.js +++ b/javascript/52-totalNQueens.js @@ -1,33 +1,33 @@ var totalNQueens = function (n) { - let col = new Set(); - let posDiag = new Set(); // (r + c) - let negDiag = new Set(); // (r - c) + let col = new Set(); + let posDiag = new Set(); // (r + c) + let negDiag = new Set(); // (r - c) - let board = new Array(n).fill().map(() => new Array(n).fill('.')); - let res = 0; + let board = new Array(n).fill().map(() => new Array(n).fill('.')); + let res = 0; - function backtrack(r) { - if (r === n) { - res += 1; - return; - } + function backtrack(r) { + if (r === n) { + res += 1; + return; + } - for (let c = 0; c < n; c++) { - if (col.has(c) || posDiag.has(r + c) || negDiag.has(r - c)) { - continue; - } + for (let c = 0; c < n; c++) { + if (col.has(c) || posDiag.has(r + c) || negDiag.has(r - c)) { + continue; + } - col.add(c); - posDiag.add(r + c); - negDiag.add(r - c); + col.add(c); + posDiag.add(r + c); + negDiag.add(r - c); - backtrack(r + 1); + backtrack(r + 1); - col.delete(c); - posDiag.delete(r + c); - negDiag.delete(r - c); + col.delete(c); + posDiag.delete(r + c); + negDiag.delete(r - c); + } } - } - backtrack(0); - return res; + backtrack(0); + return res; }; diff --git a/javascript/53-Maximum-Subarray.js b/javascript/53-Maximum-Subarray.js index 1cec9dc59..5b268503c 100644 --- a/javascript/53-Maximum-Subarray.js +++ b/javascript/53-Maximum-Subarray.js @@ -3,12 +3,12 @@ * @return {number} */ var maxSubArray = function (nums) { - let curr = nums[0]; - let max = nums[0]; + let curr = nums[0]; + let max = nums[0]; - for (let i = 1; i < nums.length; i++) { - curr = Math.max(curr + nums[i], nums[i]); - max = Math.max(max, curr); - } - return max; + for (let i = 1; i < nums.length; i++) { + curr = Math.max(curr + nums[i], nums[i]); + max = Math.max(max, curr); + } + return max; }; diff --git a/javascript/54-Spiral-Matrix.js b/javascript/54-Spiral-Matrix.js index b04066262..2a3b89ff7 100644 --- a/javascript/54-Spiral-Matrix.js +++ b/javascript/54-Spiral-Matrix.js @@ -3,36 +3,36 @@ * @return {number[]} */ var spiralOrder = function (matrix) { - const results = []; - let startRow = 0, - startCol = 0, - endRow = matrix.length - 1, - endCol = matrix[0].length - 1; + const results = []; + let startRow = 0, + startCol = 0, + endRow = matrix.length - 1, + endCol = matrix[0].length - 1; - while (results.length < matrix.length * matrix[0].length) { - for (let col = startCol; col <= endCol; col++) { - results.push(matrix[startRow][col]); - } + while (results.length < matrix.length * matrix[0].length) { + for (let col = startCol; col <= endCol; col++) { + results.push(matrix[startRow][col]); + } - for (let row = startRow + 1; row <= endRow; row++) { - results.push(matrix[row][endCol]); - } + for (let row = startRow + 1; row <= endRow; row++) { + results.push(matrix[row][endCol]); + } - for (let col = endCol - 1; col >= startCol; col--) { - if (startRow === endRow) break; - results.push(matrix[endRow][col]); - } + for (let col = endCol - 1; col >= startCol; col--) { + if (startRow === endRow) break; + results.push(matrix[endRow][col]); + } - for (let row = endRow - 1; row >= startRow + 1; row--) { - if (endCol === startCol) break; - results.push(matrix[row][startCol]); - } + for (let row = endRow - 1; row >= startRow + 1; row--) { + if (endCol === startCol) break; + results.push(matrix[row][startCol]); + } - startRow++; - startCol++; - endRow--; - endCol--; - } + startRow++; + startCol++; + endRow--; + endCol--; + } - return results; + return results; }; diff --git a/javascript/543-Diameter-Of-Binary-Tree.js b/javascript/543-Diameter-Of-Binary-Tree.js index e76e2a7d7..cb004fc75 100644 --- a/javascript/543-Diameter-Of-Binary-Tree.js +++ b/javascript/543-Diameter-Of-Binary-Tree.js @@ -11,18 +11,18 @@ * @return {number} */ var diameterOfBinaryTree = function (root) { - let diameter = 0; + let diameter = 0; - function dfs(root) { - if (root == null) return -1; + function dfs(root) { + if (root == null) return -1; - const left = dfs(root.left); - const right = dfs(root.right); - diameter = Math.max(diameter, 2 + left + right); + const left = dfs(root.left); + const right = dfs(root.right); + diameter = Math.max(diameter, 2 + left + right); - return 1 + Math.max(left, right); - } - dfs(root); + return 1 + Math.max(left, right); + } + dfs(root); - return diameter; + return diameter; }; diff --git a/javascript/55-Jump-Game.js b/javascript/55-Jump-Game.js index 772aae55c..99d3b2afc 100644 --- a/javascript/55-Jump-Game.js +++ b/javascript/55-Jump-Game.js @@ -3,13 +3,13 @@ * @return {boolean} */ var canJump = function (nums) { - let goal = nums.length - 1; + let goal = nums.length - 1; - for (let i = nums.length - 2; i >= 0; i--) { - if (i + nums[i] >= goal) { - goal = i; + for (let i = nums.length - 2; i >= 0; i--) { + if (i + nums[i] >= goal) { + goal = i; + } } - } - if (goal === 0) return true; - else return false; + if (goal === 0) return true; + else return false; }; diff --git a/javascript/56-Merge-Intervals.js b/javascript/56-Merge-Intervals.js index 7cffdeac5..4a68024e2 100644 --- a/javascript/56-Merge-Intervals.js +++ b/javascript/56-Merge-Intervals.js @@ -1,16 +1,16 @@ var merge = function (intervals) { - intervals.sort((a, b) => a[0] - b[0]); + intervals.sort((a, b) => a[0] - b[0]); - let res = [intervals[0]]; + let res = [intervals[0]]; - for (let i = 1; i < intervals.length; i++) { - let prev = res[res.length - 1]; + for (let i = 1; i < intervals.length; i++) { + let prev = res[res.length - 1]; - if (prev[1] >= intervals[i][0]) { - prev[1] = Math.max(prev[1], intervals[i][1]); - } else { - res.push(intervals[i]); + if (prev[1] >= intervals[i][0]) { + prev[1] = Math.max(prev[1], intervals[i][1]); + } else { + res.push(intervals[i]); + } } - } - return res; + return res; }; diff --git a/javascript/567-Permutation-In-String.js b/javascript/567-Permutation-In-String.js index a0271df06..ee479edb6 100644 --- a/javascript/567-Permutation-In-String.js +++ b/javascript/567-Permutation-In-String.js @@ -14,66 +14,66 @@ * @return {boolean} */ function checkInclusion(s1, s2) { - if (s1.length > s2.length) { - return false; - } - - const s1Chars = Object.create(null); - const s2Chars = Object.create(null); - - for (const ch of s1) { - if (!(ch in s1Chars)) { - s1Chars[ch] = 0; - s2Chars[ch] = 0; + if (s1.length > s2.length) { + return false; } - ++s1Chars[ch]; - } - for (let i = 0; i < s1.length; ++i) { - const ch = s2[i]; - if (ch in s1Chars) { - ++s2Chars[ch]; - } - } + const s1Chars = Object.create(null); + const s2Chars = Object.create(null); - let matches = 0; - let matched = 0; - - for (const ch in s1Chars) { - if (s1Chars[ch] === s2Chars[ch]) { - ++matches; + for (const ch of s1) { + if (!(ch in s1Chars)) { + s1Chars[ch] = 0; + s2Chars[ch] = 0; + } + ++s1Chars[ch]; } - ++matched; - } - - const last = s2.length - s1.length; - for (let i = 0; i < last; ++i) { - if (matches === matched) { - return true; + for (let i = 0; i < s1.length; ++i) { + const ch = s2[i]; + if (ch in s1Chars) { + ++s2Chars[ch]; + } } - const ch1 = s2[i]; - const ch2 = s2[i + s1.length]; + let matches = 0; + let matched = 0; - if (ch1 in s1Chars) { - if (s1Chars[ch1] === s2Chars[ch1]--) { - --matches; - } else if (s1Chars[ch1] === s2Chars[ch1]) { - ++matches; - } + for (const ch in s1Chars) { + if (s1Chars[ch] === s2Chars[ch]) { + ++matches; + } + ++matched; } - if (ch2 in s1Chars) { - if (s1Chars[ch2] === s2Chars[ch2]++) { - --matches; - } else if (s1Chars[ch2] === s2Chars[ch2]) { - ++matches; - } + const last = s2.length - s1.length; + + for (let i = 0; i < last; ++i) { + if (matches === matched) { + return true; + } + + const ch1 = s2[i]; + const ch2 = s2[i + s1.length]; + + if (ch1 in s1Chars) { + if (s1Chars[ch1] === s2Chars[ch1]--) { + --matches; + } else if (s1Chars[ch1] === s2Chars[ch1]) { + ++matches; + } + } + + if (ch2 in s1Chars) { + if (s1Chars[ch2] === s2Chars[ch2]++) { + --matches; + } else if (s1Chars[ch2] === s2Chars[ch2]) { + ++matches; + } + } } - } - return matches === matched; + return matches === matched; } ////////////////////////////////////////////////////////////////////////////// @@ -92,62 +92,62 @@ function checkInclusion(s1, s2) { * @return {boolean} */ function checkInclusion(s1, s2) { - if (s1.length > s2.length) { - return false; - } + if (s1.length > s2.length) { + return false; + } - const s1Chars = Object.create(null); + const s1Chars = Object.create(null); - for (const ch of s1) { - if (!(ch in s1Chars)) { - s1Chars[ch] = 0; + for (const ch of s1) { + if (!(ch in s1Chars)) { + s1Chars[ch] = 0; + } + ++s1Chars[ch]; } - ++s1Chars[ch]; - } - const last = s2.length - s1.length; - let i = 0; + const last = s2.length - s1.length; + let i = 0; - while (i <= last) { - while (i <= last && !(s2[i] in s1Chars)) { - ++i; - } + while (i <= last) { + while (i <= last && !(s2[i] in s1Chars)) { + ++i; + } - if (i > last) { - return false; - } + if (i > last) { + return false; + } - const subChars = Object.create(null); - let j = i; + const subChars = Object.create(null); + let j = i; - while (j < s2.length && s2[j] in s1Chars) { - const ch = s2[j]; + while (j < s2.length && s2[j] in s1Chars) { + const ch = s2[j]; - if (!(ch in subChars)) { - subChars[ch] = 0; - } - ++subChars[ch]; + if (!(ch in subChars)) { + subChars[ch] = 0; + } + ++subChars[ch]; - if (subChars[ch] > s1Chars[ch]) { - break; - } + if (subChars[ch] > s1Chars[ch]) { + break; + } - ++j; - } + ++j; + } - if (s1.length === j - i) { - return true; - } + if (s1.length === j - i) { + return true; + } - if (j < s2.length && s2[j] in s1Chars) { - while (s2[i] !== s2[j]) { - ++i; - } - ++i; - } else { - i = j; + if (j < s2.length && s2[j] in s1Chars) { + while (s2[i] !== s2[j]) { + ++i; + } + ++i; + } else { + i = j; + } } - } - return false; + return false; } diff --git a/javascript/57-Insert-Interval.js b/javascript/57-Insert-Interval.js index e8c107b30..81467da2a 100644 --- a/javascript/57-Insert-Interval.js +++ b/javascript/57-Insert-Interval.js @@ -1,26 +1,26 @@ let insert = function (intervals, newInterval) { - let res = []; - let isAdded = false; + let res = []; + let isAdded = false; - intervals.forEach((int) => { - if (int[0] > newInterval[1]) { - if (!isAdded) { - res.push(newInterval); - isAdded = true; - } + intervals.forEach((int) => { + if (int[0] > newInterval[1]) { + if (!isAdded) { + res.push(newInterval); + isAdded = true; + } - res.push(int); - } else if (int[1] < newInterval[0]) { - res.push(int); - } else { - newInterval[0] = Math.min(newInterval[0], int[0]); - newInterval[1] = Math.max(newInterval[1], int[1]); - } - }); + res.push(int); + } else if (int[1] < newInterval[0]) { + res.push(int); + } else { + newInterval[0] = Math.min(newInterval[0], int[0]); + newInterval[1] = Math.max(newInterval[1], int[1]); + } + }); - if (!isAdded) { - res.push(newInterval); - } + if (!isAdded) { + res.push(newInterval); + } - return res; + return res; }; diff --git a/javascript/572-Subtree-of-Another-Tree.js b/javascript/572-Subtree-of-Another-Tree.js index 820b21584..dc4409720 100644 --- a/javascript/572-Subtree-of-Another-Tree.js +++ b/javascript/572-Subtree-of-Another-Tree.js @@ -12,19 +12,19 @@ * @return {boolean} */ var isSubtree = function (root, subRoot) { - // given two nodes are they the same? - const isSame = (n1, n2) => { - if (!n1 && !n2) return true; - if (!n1 || !n2 || n1.val !== n2.val) return false; - return isSame(n1.left, n2.left) && isSame(n1.right, n2.right); - }; + // given two nodes are they the same? + const isSame = (n1, n2) => { + if (!n1 && !n2) return true; + if (!n1 || !n2 || n1.val !== n2.val) return false; + return isSame(n1.left, n2.left) && isSame(n1.right, n2.right); + }; - // check if subRoot is subtree of root: - const DFS = (node) => { - if (!node) return false; - if (isSame(node, subRoot)) return true; - return DFS(node.left) || DFS(node.right); - }; + // check if subRoot is subtree of root: + const DFS = (node) => { + if (!node) return false; + if (isSame(node, subRoot)) return true; + return DFS(node.left) || DFS(node.right); + }; - return DFS(root); + return DFS(root); }; diff --git a/javascript/62-Unique-Paths.js b/javascript/62-Unique-Paths.js index 104a122a0..ff240620f 100644 --- a/javascript/62-Unique-Paths.js +++ b/javascript/62-Unique-Paths.js @@ -1,15 +1,15 @@ function uniquePaths(m, n) { - let row = new Array(n).fill(1); + let row = new Array(n).fill(1); - for (let i = 0; i < m - 1; i++) { - let newRow = new Array(n).fill(1); + for (let i = 0; i < m - 1; i++) { + let newRow = new Array(n).fill(1); - for (let j = n - 2; j > -1; j--) { - newRow[j] = newRow[j + 1] + row[j]; - } + for (let j = n - 2; j > -1; j--) { + newRow[j] = newRow[j + 1] + row[j]; + } - row = newRow; - } + row = newRow; + } - return row[0]; + return row[0]; } diff --git a/javascript/647-Palindromic-Substrings.js b/javascript/647-Palindromic-Substrings.js index b77823d57..4de72b6b9 100644 --- a/javascript/647-Palindromic-Substrings.js +++ b/javascript/647-Palindromic-Substrings.js @@ -1,25 +1,25 @@ function countSubstrings(s) { - let res = 0; + let res = 0; - for (let i = 0; i < s.length; i++) { - let l = i; - let r = i; + for (let i = 0; i < s.length; i++) { + let l = i; + let r = i; - while (l >= 0 && r < s.length && s[l] === s[r]) { - res += 1; - l -= 1; - r += 1; - } + while (l >= 0 && r < s.length && s[l] === s[r]) { + res += 1; + l -= 1; + r += 1; + } - l = i; - r = i + 1; + l = i; + r = i + 1; - while (l >= 0 && r < s.length && s[l] === s[r]) { - res += 1; - l -= 1; - r += 1; + while (l >= 0 && r < s.length && s[l] === s[r]) { + res += 1; + l -= 1; + r += 1; + } } - } - return res; + return res; } diff --git a/javascript/66-plus-one.js b/javascript/66-plus-one.js index 2a0685146..aa2d73d3c 100644 --- a/javascript/66-plus-one.js +++ b/javascript/66-plus-one.js @@ -3,14 +3,14 @@ * @return {number[]} */ var plusOne = function (digits) { - for (let i = digits.length - 1; i >= 0; i--) { - if (digits[i] !== 9) { - digits[i]++; - return digits; - } else { - digits[i] = 0; + for (let i = digits.length - 1; i >= 0; i--) { + if (digits[i] !== 9) { + digits[i]++; + return digits; + } else { + digits[i] = 0; + } } - } - digits.unshift(1); - return digits; + digits.unshift(1); + return digits; }; diff --git a/javascript/684-Redundant-Connection.js b/javascript/684-Redundant-Connection.js index 1f00dc9d1..e9fe7505c 100644 --- a/javascript/684-Redundant-Connection.js +++ b/javascript/684-Redundant-Connection.js @@ -1,33 +1,33 @@ var findRedundantConnection = function (edges) { - let n = edges.length, - par = new Array(n + 1).fill(0).map((_, index) => index); - let rank = new Array(n + 1).fill(1); + let n = edges.length, + par = new Array(n + 1).fill(0).map((_, index) => index); + let rank = new Array(n + 1).fill(1); - function findParent(node) { - let p = par[node]; - while (p != par[p]) { - par[p] = par[par[p]]; - p = par[p]; + function findParent(node) { + let p = par[node]; + while (p != par[p]) { + par[p] = par[par[p]]; + p = par[p]; + } + return p; } - return p; - } - function union(n1, n2) { - let p1 = findParent(n1), - p2 = findParent(n2); - if (p1 == p2) return false; + function union(n1, n2) { + let p1 = findParent(n1), + p2 = findParent(n2); + if (p1 == p2) return false; - if (rank[p1] > rank[p2]) { - par[p2] = p1; - rank[p1] += rank[p2]; - } else { - par[p1] = p2; - rank[p2] += rank[p1]; + if (rank[p1] > rank[p2]) { + par[p2] = p1; + rank[p1] += rank[p2]; + } else { + par[p1] = p2; + rank[p2] += rank[p1]; + } + return true; } - return true; - } - for (let [n1, n2] of edges) { - if (!union(n1, n2)) return [n1, n2]; - } + for (let [n1, n2] of edges) { + if (!union(n1, n2)) return [n1, n2]; + } }; diff --git a/javascript/695-Max-Area-Of-Island.js b/javascript/695-Max-Area-Of-Island.js index d83834d3d..2864d33e6 100644 --- a/javascript/695-Max-Area-Of-Island.js +++ b/javascript/695-Max-Area-Of-Island.js @@ -3,34 +3,34 @@ * @return {number} */ var maxAreaOfIsland = function (grid) { - function find(x, y) { - if (grid[y] === undefined || grid[y][x] === undefined) { - return 0; - } + function find(x, y) { + if (grid[y] === undefined || grid[y][x] === undefined) { + return 0; + } - if (grid[y][x] === 0) { - return 0; - } + if (grid[y][x] === 0) { + return 0; + } - grid[y][x] = 0; + grid[y][x] = 0; - let square = 1; + let square = 1; - square += find(x + 1, y); - square += find(x - 1, y); - square += find(x, y + 1); - square += find(x, y - 1); + square += find(x + 1, y); + square += find(x - 1, y); + square += find(x, y + 1); + square += find(x, y - 1); - return square; - } + return square; + } - let max = 0; + let max = 0; - for (let y = 0; y < grid.length; y++) { - for (let x = 0; x < grid[0].length; x++) { - max = Math.max(max, find(x, y)); + for (let y = 0; y < grid.length; y++) { + for (let x = 0; x < grid[0].length; x++) { + max = Math.max(max, find(x, y)); + } } - } - return max; + return max; }; diff --git a/javascript/7-Reverse-Integer.js b/javascript/7-Reverse-Integer.js index a915ee6a0..6f783a2a8 100644 --- a/javascript/7-Reverse-Integer.js +++ b/javascript/7-Reverse-Integer.js @@ -3,25 +3,25 @@ * @return {number} */ const reverse = function (x) { - const max = 2 ** 31 - 1; - const min = -(2 ** 31); + const max = 2 ** 31 - 1; + const min = -(2 ** 31); - let result = 0; - while (x !== 0) { - const digit = x % 10; - x = Math.trunc(x / 10); + let result = 0; + while (x !== 0) { + const digit = x % 10; + x = Math.trunc(x / 10); - if (result > max / 10 || (result === max / 10 && digit >= max % 10)) { - return 0; - } else if ( - result < min / 10 || - (result === max / 10 && digit <= min % 10) - ) { - return 0; - } else { - result = result * 10 + digit; + if (result > max / 10 || (result === max / 10 && digit >= max % 10)) { + return 0; + } else if ( + result < min / 10 || + (result === max / 10 && digit <= min % 10) + ) { + return 0; + } else { + result = result * 10 + digit; + } } - } - return result; + return result; }; diff --git a/javascript/70-Climbing-Stairs.js b/javascript/70-Climbing-Stairs.js index ec9b57e0b..8768bc4b3 100644 --- a/javascript/70-Climbing-Stairs.js +++ b/javascript/70-Climbing-Stairs.js @@ -3,21 +3,21 @@ * @return {number} */ var climbStairs = function (n) { - const memoized = climb(); - return memoized(n); + const memoized = climb(); + return memoized(n); }; function climb() { - let cache = {}; + let cache = {}; - return function climbStairs(n) { - if (n in cache) { - return cache[n]; - } else if (n >= 1 && n < 4) { - return n; - } else { - cache[n] = climbStairs(n - 2) + climbStairs(n - 1); - return cache[n]; - } - }; + return function climbStairs(n) { + if (n in cache) { + return cache[n]; + } else if (n >= 1 && n < 4) { + return n; + } else { + cache[n] = climbStairs(n - 2) + climbStairs(n - 1); + return cache[n]; + } + }; } diff --git a/javascript/703-Kth-Largest-Element-In-A-Stream.js b/javascript/703-Kth-Largest-Element-In-A-Stream.js index 53ad9d80d..d27c3bc68 100644 --- a/javascript/703-Kth-Largest-Element-In-A-Stream.js +++ b/javascript/703-Kth-Largest-Element-In-A-Stream.js @@ -17,96 +17,96 @@ ////////////////////////////////////////////////////////////////////////////// class KthLargest { - /** - * @param {number} k - * @param {number[]} nums - * @constructor - */ - constructor(k, nums) { - this.heap = new MinHeap(nums, k); - } + /** + * @param {number} k + * @param {number[]} nums + * @constructor + */ + constructor(k, nums) { + this.heap = new MinHeap(nums, k); + } - /** - * @param {number} val - * @return {number} - */ - add(val) { - this.heap.add(val); - return this.heap.getMin(); - } + /** + * @param {number} val + * @return {number} + */ + add(val) { + this.heap.add(val); + return this.heap.getMin(); + } } class MinHeap { - /** - * @param {number[]} nums - * @param {number} size - * @constructor - */ - constructor(nums, size) { - this.size = size; - this.length = 0; - this.heap = []; - for (const num of nums) { - this.add(num); + /** + * @param {number[]} nums + * @param {number} size + * @constructor + */ + constructor(nums, size) { + this.size = size; + this.length = 0; + this.heap = []; + for (const num of nums) { + this.add(num); + } } - } - /** - * @param {number} num - * @return {void} - */ - add(num) { - if (this.length < this.size) { - ++this.length; - this.heap.push(num); - this.siftUp(this.length - 1); - } else if (num > this.heap[0]) { - this.heap[0] = num; - this.siftDown(0); + /** + * @param {number} num + * @return {void} + */ + add(num) { + if (this.length < this.size) { + ++this.length; + this.heap.push(num); + this.siftUp(this.length - 1); + } else if (num > this.heap[0]) { + this.heap[0] = num; + this.siftDown(0); + } } - } - /** - * @return {number} - */ - getMin() { - return this.heap[0]; - } + /** + * @return {number} + */ + getMin() { + return this.heap[0]; + } - /** - * @param {number} i - * @return {void} - */ - siftDown(i) { - const length = this.length; - const heap = this.heap; - let k = i * 2 + 1; - while (k < length) { - if (k + 1 < length && heap[k + 1] < heap[k]) { - ++k; - } - if (heap[i] <= heap[k]) { - return; - } - [heap[i], heap[k]] = [heap[k], heap[i]]; - i = k; - k = i * 2 + 1; + /** + * @param {number} i + * @return {void} + */ + siftDown(i) { + const length = this.length; + const heap = this.heap; + let k = i * 2 + 1; + while (k < length) { + if (k + 1 < length && heap[k + 1] < heap[k]) { + ++k; + } + if (heap[i] <= heap[k]) { + return; + } + [heap[i], heap[k]] = [heap[k], heap[i]]; + i = k; + k = i * 2 + 1; + } } - } - /** - * @param {number} i - * @return {void} - */ - siftUp(i) { - const heap = this.heap; - let p = Math.floor((i - 1) / 2); - while (i > 0 && heap[i] < heap[p]) { - [heap[i], heap[p]] = [heap[p], heap[i]]; - i = p; - p = Math.floor((i - 1) / 2); + /** + * @param {number} i + * @return {void} + */ + siftUp(i) { + const heap = this.heap; + let p = Math.floor((i - 1) / 2); + while (i > 0 && heap[i] < heap[p]) { + [heap[i], heap[p]] = [heap[p], heap[i]]; + i = p; + p = Math.floor((i - 1) / 2); + } } - } } /** @@ -129,39 +129,39 @@ class MinHeap { ////////////////////////////////////////////////////////////////////////////// class KthLargest { - /** - * @param {number} k - * @param {number[]} nums - * @constructor - */ - constructor(k, nums) { - this.nums = nums.sort((a, b) => b - a); - this.k = k; - } + /** + * @param {number} k + * @param {number[]} nums + * @constructor + */ + constructor(k, nums) { + this.nums = nums.sort((a, b) => b - a); + this.k = k; + } - /** - * @param {number} val - * @return {number} - */ - add(val) { - const nums = this.nums; - let l = 0; - let r = nums.length; - while (l <= r) { - const m = Math.floor((l + r) / 2); - if (val === nums[m]) { - l = m; - break; - } - if (val < nums[m]) { - l = m + 1; - } else { - r = m - 1; - } + /** + * @param {number} val + * @return {number} + */ + add(val) { + const nums = this.nums; + let l = 0; + let r = nums.length; + while (l <= r) { + const m = Math.floor((l + r) / 2); + if (val === nums[m]) { + l = m; + break; + } + if (val < nums[m]) { + l = m + 1; + } else { + r = m - 1; + } + } + nums.splice(l, 0, val); + return nums[this.k - 1]; } - nums.splice(l, 0, val); - return nums[this.k - 1]; - } } /** diff --git a/javascript/704-Binary-Search.js b/javascript/704-Binary-Search.js index 3335329a4..929dc0f44 100644 --- a/javascript/704-Binary-Search.js +++ b/javascript/704-Binary-Search.js @@ -4,22 +4,22 @@ * @return {number} */ var search = function (nums, target) { - let left = 0; - let right = nums.length - 1; + let left = 0; + let right = nums.length - 1; - while (left <= right) { - let middle = Math.floor((left + right) / 2); + while (left <= right) { + let middle = Math.floor((left + right) / 2); - if (nums[middle] === target) { - return middle; - } else if (nums[middle] < target) { - left = middle + 1; - } else { - right = middle - 1; + if (nums[middle] === target) { + return middle; + } else if (nums[middle] < target) { + left = middle + 1; + } else { + right = middle - 1; + } } - } - return -1; + return -1; }; // Runtime: 98 ms, faster than 34.02% of JavaScript online submissions for Binary Search. diff --git a/javascript/72-Edit-Distance.js b/javascript/72-Edit-Distance.js index 9fc7f7a19..d49d42b4b 100644 --- a/javascript/72-Edit-Distance.js +++ b/javascript/72-Edit-Distance.js @@ -10,31 +10,33 @@ * @return {number} */ function minDistance(word1, word2) { - const len1 = word1.length; - const len2 = word2.length; + const len1 = word1.length; + const len2 = word2.length; - if (!len1 || !len2) { - return len1 || len2; - } + if (!len1 || !len2) { + return len1 || len2; + } - const dp = new Array(len1 + 1).fill().map(() => new Array(len2 + 1)); + const dp = new Array(len1 + 1).fill().map(() => new Array(len2 + 1)); - for (let i = 0; i <= len1; ++i) { - dp[i][0] = i; - } - for (let i = 0; i <= len2; ++i) { - dp[0][i] = i; - } + for (let i = 0; i <= len1; ++i) { + dp[i][0] = i; + } + for (let i = 0; i <= len2; ++i) { + dp[0][i] = i; + } - for (let i = 1; i <= len1; ++i) { - for (let j = 1; j <= len2; ++j) { - const a = dp[i - 1][j] + 1; - const b = dp[i][j - 1] + 1; - const c = - word1[i - 1] === word2[j - 1] ? dp[i - 1][j - 1] : dp[i - 1][j - 1] + 1; - dp[i][j] = Math.min(a, b, c); + for (let i = 1; i <= len1; ++i) { + for (let j = 1; j <= len2; ++j) { + const a = dp[i - 1][j] + 1; + const b = dp[i][j - 1] + 1; + const c = + word1[i - 1] === word2[j - 1] + ? dp[i - 1][j - 1] + : dp[i - 1][j - 1] + 1; + dp[i][j] = Math.min(a, b, c); + } } - } - return dp[len1][len2]; + return dp[len1][len2]; } diff --git a/javascript/73-Set-Matrix-Zeroes.js b/javascript/73-Set-Matrix-Zeroes.js index b4d9f04a3..fcf36bf02 100644 --- a/javascript/73-Set-Matrix-Zeroes.js +++ b/javascript/73-Set-Matrix-Zeroes.js @@ -3,23 +3,23 @@ * @return {void} Do not return anything, modify matrix in-place instead. */ var setZeroes = function (matrix) { - let row = new Array(matrix.length); - let col = new Array(matrix[0].length); + let row = new Array(matrix.length); + let col = new Array(matrix[0].length); - for (let i = 0; i < row.length; i++) { - for (let j = 0; j < col.length; j++) { - if (matrix[i][j] === 0) { - row[i] = 0; - col[j] = 0; - } + for (let i = 0; i < row.length; i++) { + for (let j = 0; j < col.length; j++) { + if (matrix[i][j] === 0) { + row[i] = 0; + col[j] = 0; + } + } } - } - for (let i = 0; i < row.length; i++) { - for (let j = 0; j < col.length; j++) { - if (row[i] == 0 || col[j] == 0) { - matrix[i][j] = 0; - } + for (let i = 0; i < row.length; i++) { + for (let j = 0; j < col.length; j++) { + if (row[i] == 0 || col[j] == 0) { + matrix[i][j] = 0; + } + } } - } }; diff --git a/javascript/739-daily-temperatures.js b/javascript/739-daily-temperatures.js index c9cfb5d15..87314ea44 100644 --- a/javascript/739-daily-temperatures.js +++ b/javascript/739-daily-temperatures.js @@ -3,17 +3,20 @@ * @return {number[]} */ const dailyTemperatures = function (temperatures) { - const output = Array(temperatures.length).fill(0); + const output = Array(temperatures.length).fill(0); - const stack = []; + const stack = []; - for (let i = 0; i < temperatures.length; i++) { - while (stack.length !== 0 && stack[stack.length - 1][0] < temperatures[i]) { - const [temp, idx] = stack.pop(); - output[idx] = i - idx; + for (let i = 0; i < temperatures.length; i++) { + while ( + stack.length !== 0 && + stack[stack.length - 1][0] < temperatures[i] + ) { + const [temp, idx] = stack.pop(); + output[idx] = i - idx; + } + stack.push([temperatures[i], i]); } - stack.push([temperatures[i], i]); - } - return output; + return output; }; diff --git a/javascript/74-Search-A-2D-Matrix.js b/javascript/74-Search-A-2D-Matrix.js index 3db75d30e..2d9454f7d 100644 --- a/javascript/74-Search-A-2D-Matrix.js +++ b/javascript/74-Search-A-2D-Matrix.js @@ -9,28 +9,28 @@ * @return {boolean} */ function searchMatrix(matrix, target) { - const width = matrix[0].length; - const height = matrix.length; - let i = 0; - let j = height * width - 1; + const width = matrix[0].length; + const height = matrix.length; + let i = 0; + let j = height * width - 1; - while (i <= j) { - const m = Math.floor((i + j) / 2); - const r = Math.floor(m / width); - const c = m % width; + while (i <= j) { + const m = Math.floor((i + j) / 2); + const r = Math.floor(m / width); + const c = m % width; - if (matrix[r][c] === target) { - return true; - } + if (matrix[r][c] === target) { + return true; + } - if (matrix[r][c] < target) { - i = m + 1; - } else { - j = m - 1; + if (matrix[r][c] < target) { + i = m + 1; + } else { + j = m - 1; + } } - } - return false; + return false; } ////////////////////////////////////////////////////////////////////////////// @@ -44,43 +44,43 @@ function searchMatrix(matrix, target) { * @return {boolean} */ function searchMatrix(matrix, target) { - let row = -1; - let i = 0; - let j = matrix.length - 1; + let row = -1; + let i = 0; + let j = matrix.length - 1; - while (i <= j) { - let m = Math.floor((i + j) / 2); - if (target < matrix[m][0]) { - j = m - 1; - } else if (target === matrix[m][0] || target === top(matrix[m])) { - return true; - } else if (target < top(matrix[m])) { - row = m; - break; - } else { - i = m + 1; + while (i <= j) { + let m = Math.floor((i + j) / 2); + if (target < matrix[m][0]) { + j = m - 1; + } else if (target === matrix[m][0] || target === top(matrix[m])) { + return true; + } else if (target < top(matrix[m])) { + row = m; + break; + } else { + i = m + 1; + } } - } - if (row < 0) { - return false; - } + if (row < 0) { + return false; + } - const vals = matrix[row]; - i = 1; - j = vals.length - 2; + const vals = matrix[row]; + i = 1; + j = vals.length - 2; - while (i <= j) { - let m = Math.floor((i + j) / 2); - if (target < vals[m]) { - j = m - 1; - } else if (target > vals[m]) { - i = m + 1; - } else { - return true; + while (i <= j) { + let m = Math.floor((i + j) / 2); + if (target < vals[m]) { + j = m - 1; + } else if (target > vals[m]) { + i = m + 1; + } else { + return true; + } } - } - return false; + return false; } /** @@ -88,5 +88,5 @@ function searchMatrix(matrix, target) { * @return {*} */ function top(arr) { - return arr[arr.length - 1]; + return arr[arr.length - 1]; } diff --git a/javascript/746-Min-Cost-Climbing-Stairs.js b/javascript/746-Min-Cost-Climbing-Stairs.js index f6effa83d..c5817b6e3 100644 --- a/javascript/746-Min-Cost-Climbing-Stairs.js +++ b/javascript/746-Min-Cost-Climbing-Stairs.js @@ -1,9 +1,9 @@ function minCostClimbingStairs(cost) { - cost.push(0); + cost.push(0); - for (let i = cost.length - 3; i > -1; i--) { - cost[i] += Math.min(cost[i + 1], cost[i + 2]); - } + for (let i = cost.length - 3; i > -1; i--) { + cost[i] += Math.min(cost[i + 1], cost[i + 2]); + } - return Math.min(cost[0], cost[1]); + return Math.min(cost[0], cost[1]); } diff --git a/javascript/76-Minimum-Window-Substring.js b/javascript/76-Minimum-Window-Substring.js index 3eafa01d6..6772095a0 100644 --- a/javascript/76-Minimum-Window-Substring.js +++ b/javascript/76-Minimum-Window-Substring.js @@ -1,37 +1,37 @@ var minWindow = function (str, target) { - const hash = target.split('').reduce((acc, val) => { - if (!acc[val]) acc[val] = 0; - acc[val] += 1; - return acc; - }, {}); + const hash = target.split('').reduce((acc, val) => { + if (!acc[val]) acc[val] = 0; + acc[val] += 1; + return acc; + }, {}); - let start = 0; - let min = Infinity; - let matched = 0; - let subStringStart = null; + let start = 0; + let min = Infinity; + let matched = 0; + let subStringStart = null; - for (let i = 0; i < str.length; i++) { - let rightChar = str[i]; + for (let i = 0; i < str.length; i++) { + let rightChar = str[i]; - if (rightChar in hash) hash[rightChar] -= 1; - if (hash[rightChar] >= 0) matched += 1; + if (rightChar in hash) hash[rightChar] -= 1; + if (hash[rightChar] >= 0) matched += 1; - while (matched === target.length) { - if (i - start + 1 < min) { - subStringStart = start; - min = i - start + 1; - } + while (matched === target.length) { + if (i - start + 1 < min) { + subStringStart = start; + min = i - start + 1; + } - let leftChar = str[start]; - start += 1; + let leftChar = str[start]; + start += 1; - if (leftChar in hash) { - if (hash[leftChar] === 0) matched -= 1; - hash[leftChar] += 1; - } + if (leftChar in hash) { + if (hash[leftChar] === 0) matched -= 1; + hash[leftChar] += 1; + } + } } - } - return min === Infinity - ? '' - : str.substring(subStringStart, subStringStart + min); + return min === Infinity + ? '' + : str.substring(subStringStart, subStringStart + min); }; diff --git a/javascript/78-Subsets.js b/javascript/78-Subsets.js index 1e5760bb0..a9a824aea 100644 --- a/javascript/78-Subsets.js +++ b/javascript/78-Subsets.js @@ -1,20 +1,20 @@ function subsets(nums) { - let res = []; - let subset = []; - function dfs(i) { - if (i >= nums.length) { - res.push(subset.slice()); - return; - } + let res = []; + let subset = []; + function dfs(i) { + if (i >= nums.length) { + res.push(subset.slice()); + return; + } - subset.push(nums[i]); - dfs(i + 1); + subset.push(nums[i]); + dfs(i + 1); - subset.pop(); - dfs(i + 1); - } + subset.pop(); + dfs(i + 1); + } - dfs(0); + dfs(0); - return res; + return res; } diff --git a/javascript/79-Word-Search.js b/javascript/79-Word-Search.js index bbbf67987..26e9d3b60 100644 --- a/javascript/79-Word-Search.js +++ b/javascript/79-Word-Search.js @@ -1,28 +1,29 @@ function dfs(board, i, j, remain) { - if (remain === '') return true; - if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false; - if (board[i][j] !== remain[0]) return false; + if (remain === '') return true; + if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) + return false; + if (board[i][j] !== remain[0]) return false; - let temp = board[i][j]; - board[i][j] = '-'; + let temp = board[i][j]; + board[i][j] = '-'; - let result = - dfs(board, i - 1, j, remain.slice(1)) || - dfs(board, i + 1, j, remain.slice(1)) || - dfs(board, i, j - 1, remain.slice(1)) || - dfs(board, i, j + 1, remain.slice(1)); + let result = + dfs(board, i - 1, j, remain.slice(1)) || + dfs(board, i + 1, j, remain.slice(1)) || + dfs(board, i, j - 1, remain.slice(1)) || + dfs(board, i, j + 1, remain.slice(1)); - board[i][j] = temp; - return result; + board[i][j] = temp; + return result; } var exist = function (board, word) { - for (let i = 0; i < board.length; i++) { - for (let j = 0; j < board[0].length; j++) { - if (dfs(board, i, j, word)) { - return true; - } + for (let i = 0; i < board.length; i++) { + for (let j = 0; j < board[0].length; j++) { + if (dfs(board, i, j, word)) { + return true; + } + } } - } - return false; + return false; }; diff --git a/javascript/84-Largest-Rectangle-in-Histogram.js b/javascript/84-Largest-Rectangle-in-Histogram.js index 6717b19ad..b3bc6df13 100644 --- a/javascript/84-Largest-Rectangle-in-Histogram.js +++ b/javascript/84-Largest-Rectangle-in-Histogram.js @@ -3,25 +3,25 @@ * @return {number} */ var largestRectangleArea = function (heights) { - let largestArea = 0; - let stack = []; + let largestArea = 0; + let stack = []; - for (let i = 0; i < heights.length; i++) { - let start = i; + for (let i = 0; i < heights.length; i++) { + let start = i; - while (stack.length > 0 && stack[stack.length - 1][1] > heights[i]) { - let [lastI, lastH] = stack.pop(); - largestArea = Math.max(largestArea, lastH * (i - lastI)); - start = lastI; - } + while (stack.length > 0 && stack[stack.length - 1][1] > heights[i]) { + let [lastI, lastH] = stack.pop(); + largestArea = Math.max(largestArea, lastH * (i - lastI)); + start = lastI; + } - stack.push([start, heights[i]]); - } + stack.push([start, heights[i]]); + } - for (let j = 0; j < stack.length; j++) { - let currArea = stack[j][1] * (heights.length - stack[j][0]); - largestArea = Math.max(largestArea, currArea); - } + for (let j = 0; j < stack.length; j++) { + let currArea = stack[j][1] * (heights.length - stack[j][0]); + largestArea = Math.max(largestArea, currArea); + } - return largestArea; + return largestArea; }; diff --git a/javascript/853-Car-Fleet.js b/javascript/853-Car-Fleet.js index e610fbd4a..1ab4235ad 100644 --- a/javascript/853-Car-Fleet.js +++ b/javascript/853-Car-Fleet.js @@ -1,25 +1,25 @@ function carFleet(target, position, speed) { - const combined = position - .map((item, index) => { - return [item, speed[index]]; - }) - .sort((a, b) => a[0] - b[0]); + const combined = position + .map((item, index) => { + return [item, speed[index]]; + }) + .sort((a, b) => a[0] - b[0]); - const stack = []; + const stack = []; - for (let i = combined.length - 1; i > -1; i--) { - const p = combined[i][0]; - const s = combined[i][1]; + for (let i = combined.length - 1; i > -1; i--) { + const p = combined[i][0]; + const s = combined[i][1]; - stack.push((target - p) / s); + stack.push((target - p) / s); - if ( - stack.length >= 2 && - stack[stack.length - 1] <= stack[stack.length - 2] - ) { - stack.pop(); + if ( + stack.length >= 2 && + stack[stack.length - 1] <= stack[stack.length - 2] + ) { + stack.pop(); + } } - } - return stack.length; + return stack.length; } diff --git a/javascript/875-Koko-Eating-Bananas.js b/javascript/875-Koko-Eating-Bananas.js index ab53c87d6..98b6e85d5 100644 --- a/javascript/875-Koko-Eating-Bananas.js +++ b/javascript/875-Koko-Eating-Bananas.js @@ -9,25 +9,25 @@ * @return {number} */ function minEatingSpeed(piles, h) { - let l = 0; - let r = Math.max.apply(Math, piles); + let l = 0; + let r = Math.max.apply(Math, piles); - if (piles.length === h) { - return r; - } - - while (l < r) { - const m = Math.floor((l + r) / 2); - let hours = 0; - for (const pile of piles) { - hours += Math.ceil(pile / m); + if (piles.length === h) { + return r; } - if (hours > h) { - l = m + 1; - } else { - r = m; + + while (l < r) { + const m = Math.floor((l + r) / 2); + let hours = 0; + for (const pile of piles) { + hours += Math.ceil(pile / m); + } + if (hours > h) { + l = m + 1; + } else { + r = m; + } } - } - return l; + return l; } diff --git a/javascript/9-Palindrome-Number.js b/javascript/9-Palindrome-Number.js index cd263b2a0..2d6770d07 100644 --- a/javascript/9-Palindrome-Number.js +++ b/javascript/9-Palindrome-Number.js @@ -3,18 +3,18 @@ * @return {boolean} */ var isPalindrome = function (x) { - // Creates array from int characters - // 121 -> [1,2,1] - let arr = Array.from(String(x), Number); + // Creates array from int characters + // 121 -> [1,2,1] + let arr = Array.from(String(x), Number); - // Uses two pointer - for (let i = 0; i < arr.length; i++) { - if (arr[i] !== arr[arr.length - 1 - i]) { - return false; + // Uses two pointer + for (let i = 0; i < arr.length; i++) { + if (arr[i] !== arr[arr.length - 1 - i]) { + return false; + } } - } - return true; + return true; }; // Runtime: 302 ms, faster than 40.50% of JavaScript online submissions for Palindrome Number. diff --git a/javascript/90-Subsets-II.js b/javascript/90-Subsets-II.js index 2f69400d5..5026562d1 100644 --- a/javascript/90-Subsets-II.js +++ b/javascript/90-Subsets-II.js @@ -9,26 +9,26 @@ * @return {number[][]} */ function subsetsWithDup(nums) { - nums.sort((a, b) => a - b); - const results = []; - const result = []; - getSubsets(); - return results; + nums.sort((a, b) => a - b); + const results = []; + const result = []; + getSubsets(); + return results; - /** - * @param {number} start = `0` - * @return {void} - */ - function getSubsets(start = 0) { - results.push(result.slice()); + /** + * @param {number} start = `0` + * @return {void} + */ + function getSubsets(start = 0) { + results.push(result.slice()); - for (let i = start; i < nums.length; ++i) { - if (i !== start && nums[i] === nums[i - 1]) { - continue; - } - result.push(nums[i]); - getSubsets(i + 1); - result.pop(); + for (let i = start; i < nums.length; ++i) { + if (i !== start && nums[i] === nums[i - 1]) { + continue; + } + result.push(nums[i]); + getSubsets(i + 1); + result.pop(); + } } - } } diff --git a/javascript/91-Decode-Ways.js b/javascript/91-Decode-Ways.js index e6525f163..9286d74af 100644 --- a/javascript/91-Decode-Ways.js +++ b/javascript/91-Decode-Ways.js @@ -1,20 +1,20 @@ function numDecodings(s) { - let dp = { - [s.length]: 1, - }; + let dp = { + [s.length]: 1, + }; - for (let i = s.length - 1; i > -1; i--) { - if (s[i] == '0') { - dp[i] = 0; - } else { - dp[i] = dp[i + 1]; + for (let i = s.length - 1; i > -1; i--) { + if (s[i] == '0') { + dp[i] = 0; + } else { + dp[i] = dp[i + 1]; + } + if ( + i + 1 < s.length && + (s[i] == '1' || (s[i] == '2' && '0123456'.includes(s[i + 1]))) + ) { + dp[i] += dp[i + 2]; + } } - if ( - i + 1 < s.length && - (s[i] == '1' || (s[i] == '2' && '0123456'.includes(s[i + 1]))) - ) { - dp[i] += dp[i + 2]; - } - } - return dp[0]; + return dp[0]; } diff --git a/javascript/97-Interleaving-String.js b/javascript/97-Interleaving-String.js index ca97df730..0ef92044a 100644 --- a/javascript/97-Interleaving-String.js +++ b/javascript/97-Interleaving-String.js @@ -11,31 +11,31 @@ * @return {boolean} */ function isInterleave(s1, s2, s3) { - const l1 = s1.length; - const l2 = s2.length; - const l3 = s3.length; + const l1 = s1.length; + const l2 = s2.length; + const l3 = s3.length; - if (l1 + l2 !== l3) { - return false; - } - if (!s1 || !s2 || !s3) { - return (!s1 && !s2 && !s3) || (s1 ? s1 === s3 : s2 === s3); - } + if (l1 + l2 !== l3) { + return false; + } + if (!s1 || !s2 || !s3) { + return (!s1 && !s2 && !s3) || (s1 ? s1 === s3 : s2 === s3); + } - const seen = new Array(l2 + 1); - seen[l2] = true; + const seen = new Array(l2 + 1); + seen[l2] = true; - for (let i = l2 - 1; i >= 0; --i) { - seen[i] = seen[i + 1] && s2[i] === s3[l1 + i]; - } - for (let i = l1 - 1; i >= 0; --i) { - for (let j = l2; j >= 0; --j) { - seen[j] = - (seen[j] && s1[i] === s3[i + j]) || - (j !== l2 && seen[j + 1] && s2[j] === s3[i + j]); + for (let i = l2 - 1; i >= 0; --i) { + seen[i] = seen[i + 1] && s2[i] === s3[l1 + i]; + } + for (let i = l1 - 1; i >= 0; --i) { + for (let j = l2; j >= 0; --j) { + seen[j] = + (seen[j] && s1[i] === s3[i + j]) || + (j !== l2 && seen[j + 1] && s2[j] === s3[i + j]); + } } - } - return seen[0]; + return seen[0]; } ////////////////////////////////////////////////////////////////////////////// @@ -51,34 +51,34 @@ function isInterleave(s1, s2, s3) { * @return {boolean} */ function isInterleave(s1, s2, s3) { - const l1 = s1.length; - const l2 = s2.length; - const l3 = s3.length; + const l1 = s1.length; + const l2 = s2.length; + const l3 = s3.length; - if (l1 + l2 !== l3) { - return false; - } - if (!s1 || !s2 || !s3) { - return (!s1 && !s2 && !s3) || (s1 ? s1 === s3 : s2 === s3); - } + if (l1 + l2 !== l3) { + return false; + } + if (!s1 || !s2 || !s3) { + return (!s1 && !s2 && !s3) || (s1 ? s1 === s3 : s2 === s3); + } - const seen = new Array(l1 + 1).fill().map(() => new Array(l2 + 1)); - seen[l1][l2] = true; + const seen = new Array(l1 + 1).fill().map(() => new Array(l2 + 1)); + seen[l1][l2] = true; - for (let i = l1 - 1; i >= 0; --i) { - seen[i][l2] = seen[i + 1][l2] && s1[i] === s3[i + l2]; - } - for (let j = l2 - 1; j >= 0; --j) { - seen[l1][j] = seen[l1][j + 1] && s2[j] === s3[l1 + j]; - } - for (let i = l1 - 1; i >= 0; --i) { + for (let i = l1 - 1; i >= 0; --i) { + seen[i][l2] = seen[i + 1][l2] && s1[i] === s3[i + l2]; + } for (let j = l2 - 1; j >= 0; --j) { - seen[i][j] = - (seen[i + 1][j] && s1[i] === s3[i + j]) || - (seen[i][j + 1] && s2[j] === s3[i + j]); + seen[l1][j] = seen[l1][j + 1] && s2[j] === s3[l1 + j]; + } + for (let i = l1 - 1; i >= 0; --i) { + for (let j = l2 - 1; j >= 0; --j) { + seen[i][j] = + (seen[i + 1][j] && s1[i] === s3[i + j]) || + (seen[i][j + 1] && s2[j] === s3[i + j]); + } } - } - return seen[0][0]; + return seen[0][0]; } ////////////////////////////////////////////////////////////////////////////// @@ -94,34 +94,38 @@ function isInterleave(s1, s2, s3) { * @return {boolean} */ function isInterleave(s1, s2, s3) { - const l1 = s1.length; - const l2 = s2.length; - const l3 = s3.length; + const l1 = s1.length; + const l2 = s2.length; + const l3 = s3.length; - if (l1 + l2 !== l3) { - return false; - } - if (!s1 || !s2 || !s3) { - return (!s1 && !s2 && !s3) || (s1 ? s1 === s3 : s2 === s3); - } + if (l1 + l2 !== l3) { + return false; + } + if (!s1 || !s2 || !s3) { + return (!s1 && !s2 && !s3) || (s1 ? s1 === s3 : s2 === s3); + } - const seen = new Array(l1 + 1).fill().map(() => new Array(l2 + 1)); - return checkStrings(); + const seen = new Array(l1 + 1).fill().map(() => new Array(l2 + 1)); + return checkStrings(); - /** - * @param {number=} i = `0` - * @param {number=} j = `0` - * @param {number=} k = `0` - * @return {boolean} - */ - function checkStrings(i = 0, j = 0, k = 0) { - return ( - k === l3 || - (seen[i][j] !== undefined - ? seen[i][j] - : (seen[i][j] = - (i < l1 && s1[i] === s3[k] && checkStrings(i + 1, j, k + 1)) || - (j < l2 && s2[j] === s3[k] && checkStrings(i, j + 1, k + 1)))) - ); - } + /** + * @param {number=} i = `0` + * @param {number=} j = `0` + * @param {number=} k = `0` + * @return {boolean} + */ + function checkStrings(i = 0, j = 0, k = 0) { + return ( + k === l3 || + (seen[i][j] !== undefined + ? seen[i][j] + : (seen[i][j] = + (i < l1 && + s1[i] === s3[k] && + checkStrings(i + 1, j, k + 1)) || + (j < l2 && + s2[j] === s3[k] && + checkStrings(i, j + 1, k + 1)))) + ); + } } diff --git a/javascript/973-K-Closest-Points-to-Origin.js b/javascript/973-K-Closest-Points-to-Origin.js index 5857f452d..1d754bcc2 100644 --- a/javascript/973-K-Closest-Points-to-Origin.js +++ b/javascript/973-K-Closest-Points-to-Origin.js @@ -10,11 +10,11 @@ * @return {number[][]} */ var kClosest = function (points, k) { - // Sort the array with a custom lambda comparator function - points.sort((a, b) => squaredDistance(a) - squaredDistance(b)); + // Sort the array with a custom lambda comparator function + points.sort((a, b) => squaredDistance(a) - squaredDistance(b)); - // Return the first k elements of the sorted array - return points.slice(0, k); + // Return the first k elements of the sorted array + return points.slice(0, k); }; // Calculate and return the squared Euclidean distance @@ -32,22 +32,22 @@ const squaredDistance = ([x, y]) => x ** 2 + y ** 2; * @return {number[][]} */ var kClosest = function (points, k) { - let maxPQ = new MaxPriorityQueue(); - for (let point of points) { - let dist = squaredDistance(point); - if (maxPQ.size() < k) { - // Fill the max PQ up to k points - maxPQ.enqueue(point, dist); - } else if (dist < maxPQ.front().priority) { - // If the max PQ is full and a closer point is found, - // discard the farthest point and add this one - maxPQ.dequeue(); - maxPQ.enqueue(point, dist); + let maxPQ = new MaxPriorityQueue(); + for (let point of points) { + let dist = squaredDistance(point); + if (maxPQ.size() < k) { + // Fill the max PQ up to k points + maxPQ.enqueue(point, dist); + } else if (dist < maxPQ.front().priority) { + // If the max PQ is full and a closer point is found, + // discard the farthest point and add this one + maxPQ.dequeue(); + maxPQ.enqueue(point, dist); + } } - } - // Return all points stored in the max PQ - return maxPQ.toArray().map((el) => el.element); + // Return all points stored in the max PQ + return maxPQ.toArray().map((el) => el.element); }; // Calculate and return the squared Euclidean distance @@ -65,52 +65,52 @@ const squaredDistance = ([x, y]) => x ** 2 + y ** 2; * @return {number[][]} */ var kClosest = function (points, k) { - // Precompute the Euclidean distance for each point - let distances = points.map(euclideanDistance); - // Create a reference array of point indices - let remaining = points.map((_, i) => i); - // Define the initial binary search range - let low = 0, - high = Math.max(...distances); - - // Perform a binary search of the distances - // to find the k closest points - let closest = []; - while (k) { - let mid = low + (high - low) / 2; - let [closer, farther] = splitDistances(remaining, distances, mid); - if (closer.length > k) { - // If more than k points are in the closer distances - // then discard the farther points and continue - remaining = closer; - high = mid; - } else { - // Add the closer points to the answer array and keep - // searching the farther distances for the remaining points - k -= closer.length; - closest.push(...closer); - remaining = farther; - low = mid; + // Precompute the Euclidean distance for each point + let distances = points.map(euclideanDistance); + // Create a reference array of point indices + let remaining = points.map((_, i) => i); + // Define the initial binary search range + let low = 0, + high = Math.max(...distances); + + // Perform a binary search of the distances + // to find the k closest points + let closest = []; + while (k) { + let mid = low + (high - low) / 2; + let [closer, farther] = splitDistances(remaining, distances, mid); + if (closer.length > k) { + // If more than k points are in the closer distances + // then discard the farther points and continue + remaining = closer; + high = mid; + } else { + // Add the closer points to the answer array and keep + // searching the farther distances for the remaining points + k -= closer.length; + closest.push(...closer); + remaining = farther; + low = mid; + } } - } - // Return the k closest points using the reference indices - return closest.map((i) => points[i]); + // Return the k closest points using the reference indices + return closest.map((i) => points[i]); }; var splitDistances = function (remaining, distances, mid) { - // Split the distances around the midpoint - // and return them in separate arrays - let closer = [], - farther = []; - for (let index of remaining) { - if (distances[index] <= mid) { - closer.push(index); - } else { - farther.push(index); + // Split the distances around the midpoint + // and return them in separate arrays + let closer = [], + farther = []; + for (let index of remaining) { + if (distances[index] <= mid) { + closer.push(index); + } else { + farther.push(index); + } } - } - return [closer, farther]; + return [closer, farther]; }; // Calculate and return the squared Euclidean distance @@ -128,54 +128,54 @@ const euclideanDistance = ([x, y]) => x ** 2 + y ** 2; * @return {number[][]} */ var kClosest = function (points, k) { - return quickSelect(points, k); + return quickSelect(points, k); }; var quickSelect = function (points, k) { - let left = 0, - right = points.length - 1; - let pivotIndex = points.length; - while (pivotIndex !== k) { - // Repeatedly partition the array - // while narrowing in on the kth element - pivotIndex = partition(points, left, right); - if (pivotIndex < k) { - left = pivotIndex; - } else { - right = pivotIndex - 1; + let left = 0, + right = points.length - 1; + let pivotIndex = points.length; + while (pivotIndex !== k) { + // Repeatedly partition the array + // while narrowing in on the kth element + pivotIndex = partition(points, left, right); + if (pivotIndex < k) { + left = pivotIndex; + } else { + right = pivotIndex - 1; + } } - } - // Return the first k elements of the partially sorted array - return points.slice(0, k); + // Return the first k elements of the partially sorted array + return points.slice(0, k); }; var partition = function (points, left, right) { - let pivot = choosePivot(points, left, right); - let pivotDist = squaredDistance(pivot); - while (left < right) { - // Iterate through the range and swap elements to make sure - // that all points closer than the pivot are to the left - if (squaredDistance(points[left]) >= pivotDist) { - [points[left], points[right]] = [points[right], points[left]]; - right--; - } else { - left++; + let pivot = choosePivot(points, left, right); + let pivotDist = squaredDistance(pivot); + while (left < right) { + // Iterate through the range and swap elements to make sure + // that all points closer than the pivot are to the left + if (squaredDistance(points[left]) >= pivotDist) { + [points[left], points[right]] = [points[right], points[left]]; + right--; + } else { + left++; + } } - } - // Ensure the left pointer is just past the end of - // the left range then return it as the new pivotIndex - if (squaredDistance(points[left]) < pivotDist) { - left++; - } + // Ensure the left pointer is just past the end of + // the left range then return it as the new pivotIndex + if (squaredDistance(points[left]) < pivotDist) { + left++; + } - return left; + return left; }; // Choose a pivot element of the array const choosePivot = (points, left, right) => - points[left + ((right - left) >> 1)]; + points[left + ((right - left) >> 1)]; // Calculate and return the squared Euclidean distance const squaredDistance = ([x, y]) => x ** 2 + y ** 2; diff --git a/javascript/98-Validate-Binary-Search-Tree.js b/javascript/98-Validate-Binary-Search-Tree.js index ad478142a..62293d546 100644 --- a/javascript/98-Validate-Binary-Search-Tree.js +++ b/javascript/98-Validate-Binary-Search-Tree.js @@ -12,19 +12,20 @@ */ var isValidBST = function (root) { - return validate(root, null, null); + return validate(root, null, null); }; function validate(root, max, min) { - if (!root) { - return true; - } else if ( - (max !== null && root.val >= max) || - (min !== null && root.val <= min) - ) { - return false; - } else - return ( - validate(root.left, root.val, min) && validate(root.right, max, root.val) - ); + if (!root) { + return true; + } else if ( + (max !== null && root.val >= max) || + (min !== null && root.val <= min) + ) { + return false; + } else + return ( + validate(root.left, root.val, min) && + validate(root.right, max, root.val) + ); } diff --git a/javascript/981-Time-Based-Key-Value-Store.js b/javascript/981-Time-Based-Key-Value-Store.js index 209b311aa..1fed28efc 100644 --- a/javascript/981-Time-Based-Key-Value-Store.js +++ b/javascript/981-Time-Based-Key-Value-Store.js @@ -1,5 +1,5 @@ var TimeMap = function () { - this.keyStore = {}; + this.keyStore = {}; }; /** @@ -9,8 +9,8 @@ var TimeMap = function () { * @return {void} */ TimeMap.prototype.set = function (key, value, timestamp) { - if (!this.keyStore[key]) this.keyStore[key] = []; - this.keyStore[key].push([value, timestamp]); + if (!this.keyStore[key]) this.keyStore[key] = []; + this.keyStore[key].push([value, timestamp]); }; /** @@ -19,20 +19,20 @@ TimeMap.prototype.set = function (key, value, timestamp) { * @return {string} */ TimeMap.prototype.get = function (key, timestamp) { - let res = ''; - const values = this.keyStore[key] || []; - let l = 0, - r = values.length - 1; + let res = ''; + const values = this.keyStore[key] || []; + let l = 0, + r = values.length - 1; - while (l <= r) { - const m = Math.floor((l + r) / 2); - if (values[m][1] <= timestamp) { - res = values[m][0]; - l = m + 1; - } else r = m - 1; - } + while (l <= r) { + const m = Math.floor((l + r) / 2); + if (values[m][1] <= timestamp) { + res = values[m][0]; + l = m + 1; + } else r = m - 1; + } - return res; + return res; }; /** diff --git a/javascript/994-Rotting-Oranges.js b/javascript/994-Rotting-Oranges.js index 831d5cf2f..d65ce10a4 100644 --- a/javascript/994-Rotting-Oranges.js +++ b/javascript/994-Rotting-Oranges.js @@ -3,42 +3,48 @@ * @return {number} */ var orangesRotting = function (grid) { - let [ROWS, COLS, time, fresh, q] = [grid.length, grid[0].length, 0, 0, []]; - let dirs = [ - [0, 1], - [0, -1], - [1, 0], - [-1, 0], - ]; - - // count fresh oranges and add rotten oranges to queue - for (let i = 0; i < ROWS; i++) { - for (let j = 0; j < COLS; j++) { - if (grid[i][j] === 1) fresh++; - if (grid[i][j] === 2) q.push([i, j]); + let [ROWS, COLS, time, fresh, q] = [grid.length, grid[0].length, 0, 0, []]; + let dirs = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; + + // count fresh oranges and add rotten oranges to queue + for (let i = 0; i < ROWS; i++) { + for (let j = 0; j < COLS; j++) { + if (grid[i][j] === 1) fresh++; + if (grid[i][j] === 2) q.push([i, j]); + } } - } - while (q.length > 0 && fresh > 0) { - let qLen = q.length; + while (q.length > 0 && fresh > 0) { + let qLen = q.length; - for (let rot = 0; rot < qLen; rot++) { - let [row, col] = q.shift(); + for (let rot = 0; rot < qLen; rot++) { + let [row, col] = q.shift(); - for (let dir of dirs) { - let [r, c] = [row + dir[0], col + dir[1]]; + for (let dir of dirs) { + let [r, c] = [row + dir[0], col + dir[1]]; - if (r < 0 || r >= ROWS || c < 0 || c >= COLS || grid[r][c] !== 1) - continue; + if ( + r < 0 || + r >= ROWS || + c < 0 || + c >= COLS || + grid[r][c] !== 1 + ) + continue; - grid[r][c] = 2; - fresh--; - q.push([r, c]); - } - } + grid[r][c] = 2; + fresh--; + q.push([r, c]); + } + } - time++; - } + time++; + } - return fresh > 0 ? -1 : time; + return fresh > 0 ? -1 : time; }; diff --git a/typescript/1-Two-Sum.ts b/typescript/1-Two-Sum.ts index 73fba22ee..0ff16436c 100644 --- a/typescript/1-Two-Sum.ts +++ b/typescript/1-Two-Sum.ts @@ -1,11 +1,11 @@ function twoSum(nums: number[], target: number): number[] { - let hash: { [key: number]: number } = {}; - for (let i = 0; i < nums.length; i++) { - let diff = target - nums[i]; - if (diff in hash) { - return [hash[diff], i]; - } else { - hash[nums[i]] = i; + let hash: { [key: number]: number } = {}; + for (let i = 0; i < nums.length; i++) { + let diff = target - nums[i]; + if (diff in hash) { + return [hash[diff], i]; + } else { + hash[nums[i]] = i; + } } - } } diff --git a/typescript/100-Same-Tree.ts b/typescript/100-Same-Tree.ts index 0599ed4ff..45ec0ebab 100644 --- a/typescript/100-Same-Tree.ts +++ b/typescript/100-Same-Tree.ts @@ -13,16 +13,16 @@ */ function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { - if (p === null && q === null) return true; + if (p === null && q === null) return true; - if ((p === null && q !== null) || (p !== null && q === null)) return false; + if ((p === null && q !== null) || (p !== null && q === null)) return false; - let leftSame = isSameTree(p.left, q.left); - let rightSame = isSameTree(p.right, q.right); + let leftSame = isSameTree(p.left, q.left); + let rightSame = isSameTree(p.right, q.right); - if (p.val === q.val && leftSame && rightSame) { - return true; - } + if (p.val === q.val && leftSame && rightSame) { + return true; + } - return false; + return false; } diff --git a/typescript/102-Binary-Tree-Level-Order-Traversal.ts b/typescript/102-Binary-Tree-Level-Order-Traversal.ts index 48b477ac2..5913691ab 100644 --- a/typescript/102-Binary-Tree-Level-Order-Traversal.ts +++ b/typescript/102-Binary-Tree-Level-Order-Traversal.ts @@ -13,24 +13,24 @@ */ function levelOrder(root: TreeNode | null): number[][] { - const levels: number[][] = []; + const levels: number[][] = []; - function getHeight(node: TreeNode | null, height: number) { - if (!node) return 0; + function getHeight(node: TreeNode | null, height: number) { + if (!node) return 0; - if (node.left || node.right) { - getHeight(node.left, height + 1); - getHeight(node.right, height + 1); - } + if (node.left || node.right) { + getHeight(node.left, height + 1); + getHeight(node.right, height + 1); + } - if (levels[height]) { - levels[height].push(node.val); - } else { - levels[height] = [node.val]; + if (levels[height]) { + levels[height].push(node.val); + } else { + levels[height] = [node.val]; + } } - } - getHeight(root, 0); + getHeight(root, 0); - return levels; + return levels; } diff --git a/typescript/104-Maximum-Depth-of-Binary-Tree.ts b/typescript/104-Maximum-Depth-of-Binary-Tree.ts index 949af17d6..10c14e26c 100644 --- a/typescript/104-Maximum-Depth-of-Binary-Tree.ts +++ b/typescript/104-Maximum-Depth-of-Binary-Tree.ts @@ -13,7 +13,7 @@ */ function maxDepth(root: TreeNode | null): number { - if (!root) return 0; + if (!root) return 0; - return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); } diff --git a/typescript/11-Container-With-Most-Water.ts b/typescript/11-Container-With-Most-Water.ts index 59a4dac59..f46b902ee 100644 --- a/typescript/11-Container-With-Most-Water.ts +++ b/typescript/11-Container-With-Most-Water.ts @@ -1,19 +1,19 @@ function maxArea(height: number[]): number { - let l = 0; - let r = height.length - 1; - let max = 0; + let l = 0; + let r = height.length - 1; + let max = 0; - while (l < r) { - let area = (r - l) * Math.min(height[l], height[r]); + while (l < r) { + let area = (r - l) * Math.min(height[l], height[r]); - max = Math.max(max, area); + max = Math.max(max, area); - if (height[l] < height[r]) { - l += 1; - } else { - r -= 1; + if (height[l] < height[r]) { + l += 1; + } else { + r -= 1; + } } - } - return max; + return max; } diff --git a/typescript/110-Balanced-Binary-Tree.ts b/typescript/110-Balanced-Binary-Tree.ts index 331d05d50..5b4dec441 100644 --- a/typescript/110-Balanced-Binary-Tree.ts +++ b/typescript/110-Balanced-Binary-Tree.ts @@ -13,18 +13,20 @@ */ function isBalanced(root: TreeNode | null): boolean { - let array = getHeight(root); - return array[0]; + let array = getHeight(root); + return array[0]; } function getHeight(root: TreeNode | null) { - if (!root) return [true, 0]; + if (!root) return [true, 0]; - let [leftBalanced, leftHeight] = getHeight(root.left); - let [rightBalanced, rightHeight] = getHeight(root.right); + let [leftBalanced, leftHeight] = getHeight(root.left); + let [rightBalanced, rightHeight] = getHeight(root.right); - let balanced = - leftBalanced && rightBalanced && Math.abs(rightHeight - leftHeight) <= 1; + let balanced = + leftBalanced && + rightBalanced && + Math.abs(rightHeight - leftHeight) <= 1; - return [balanced, 1 + Math.max(leftHeight, rightHeight)]; + return [balanced, 1 + Math.max(leftHeight, rightHeight)]; } diff --git a/typescript/1143-Longest-Common-Subsequence.ts b/typescript/1143-Longest-Common-Subsequence.ts index ae3da3dc8..532bcbbe4 100644 --- a/typescript/1143-Longest-Common-Subsequence.ts +++ b/typescript/1143-Longest-Common-Subsequence.ts @@ -1,20 +1,20 @@ function longestCommonSubsequence(text1: string, text2: string): number { - let temp: number[][] = []; - let max: number = 0; - for (let i = 0; i <= text1.length; i++) { - temp.push(new Array(text2.length + 1).fill(0)); - } + let temp: number[][] = []; + let max: number = 0; + for (let i = 0; i <= text1.length; i++) { + temp.push(new Array(text2.length + 1).fill(0)); + } - for (let i = 1; i < temp.length; i++) { - for (let j = 1; j < temp[0].length; j++) { - if (text1[i - 1] === text2[j - 1]) { - temp[i][j] = temp[i - 1][j - 1] + 1; - } else { - temp[i][j] = Math.max(temp[i - 1][j], temp[i][j - 1]); - } - max = Math.max(max, temp[i][j]); + for (let i = 1; i < temp.length; i++) { + for (let j = 1; j < temp[0].length; j++) { + if (text1[i - 1] === text2[j - 1]) { + temp[i][j] = temp[i - 1][j - 1] + 1; + } else { + temp[i][j] = Math.max(temp[i - 1][j], temp[i][j - 1]); + } + max = Math.max(max, temp[i][j]); + } } - } - return max; + return max; } diff --git a/typescript/121-Best-Time-To-Buy-and-Sell-Stock.ts b/typescript/121-Best-Time-To-Buy-and-Sell-Stock.ts index aa05c61d4..903468424 100644 --- a/typescript/121-Best-Time-To-Buy-and-Sell-Stock.ts +++ b/typescript/121-Best-Time-To-Buy-and-Sell-Stock.ts @@ -1,19 +1,19 @@ function maxProfit(prices: number[]): number { - let max = 0; - let l = 0; - let r = 1; + let max = 0; + let l = 0; + let r = 1; - while (r < prices.length) { - if (prices[l] < prices[r]) { - let profit = prices[r] - prices[l]; - if (profit > max) { - max = profit; - } - } else { - l = r; + while (r < prices.length) { + if (prices[l] < prices[r]) { + let profit = prices[r] - prices[l]; + if (profit > max) { + max = profit; + } + } else { + l = r; + } + r++; } - r++; - } - return max; + return max; } diff --git a/typescript/125-Valid-Palindrome.ts b/typescript/125-Valid-Palindrome.ts index 1a26c22e0..0cc391536 100644 --- a/typescript/125-Valid-Palindrome.ts +++ b/typescript/125-Valid-Palindrome.ts @@ -1,17 +1,17 @@ function isPalindrome(s: string): boolean { - const array = s - .toLowerCase() - .replace(/[^A-Za-z0-9]/g, '') - .replace(/\s/g, '') - .split(''); + const array = s + .toLowerCase() + .replace(/[^A-Za-z0-9]/g, '') + .replace(/\s/g, '') + .split(''); - for (let i = 0; i < array.length; i++) { - const first = array[i]; - const second = array[array.length - 1 - i]; + for (let i = 0; i < array.length; i++) { + const first = array[i]; + const second = array[array.length - 1 - i]; - if (first !== second) { - return false; + if (first !== second) { + return false; + } } - } - return true; + return true; } diff --git a/typescript/128-Longest-Consecutive-Sequence.ts b/typescript/128-Longest-Consecutive-Sequence.ts index 74b437aa5..77963f3c1 100644 --- a/typescript/128-Longest-Consecutive-Sequence.ts +++ b/typescript/128-Longest-Consecutive-Sequence.ts @@ -1,16 +1,16 @@ function longestConsecutive(nums: number[]): number { - const number = new Set(nums); - let longest = 0; + const number = new Set(nums); + let longest = 0; - for (const n of nums) { - if (!number.has(n - 1)) { - let length = 0; - while (number.has(n + length)) { - length += 1; - } - longest = Math.max(length, longest); + for (const n of nums) { + if (!number.has(n - 1)) { + let length = 0; + while (number.has(n + length)) { + length += 1; + } + longest = Math.max(length, longest); + } } - } - return longest; + return longest; } diff --git a/typescript/131-Palindrome-Partitioning.ts b/typescript/131-Palindrome-Partitioning.ts index 134b4c19b..96fe44f82 100644 --- a/typescript/131-Palindrome-Partitioning.ts +++ b/typescript/131-Palindrome-Partitioning.ts @@ -1,33 +1,33 @@ function partition(s: string): string[][] { - let res: string[][] = []; - let part: string[] = []; + let res: string[][] = []; + let part: string[] = []; - function dfs(i: number) { - if (i >= s.length) { - res.push(part.slice()); - return; - } + function dfs(i: number) { + if (i >= s.length) { + res.push(part.slice()); + return; + } - for (let j = i; j < s.length; j++) { - if (isPali(s, i, j)) { - part.push(s.slice(i, j + 1)); - dfs(j + 1); - part.pop(); - } + for (let j = i; j < s.length; j++) { + if (isPali(s, i, j)) { + part.push(s.slice(i, j + 1)); + dfs(j + 1); + part.pop(); + } + } } - } - dfs(0); - return res; + dfs(0); + return res; - function isPali(s: string, l: number, r: number) { - while (l < r) { - if (s[l] != s[r]) { - return false; - } - l = l + 1; - r = r - 1; + function isPali(s: string, l: number, r: number) { + while (l < r) { + if (s[l] != s[r]) { + return false; + } + l = l + 1; + r = r - 1; + } + return true; } - return true; - } } diff --git a/typescript/136-Single-Number.ts b/typescript/136-Single-Number.ts index a87e7cf05..6ee083afc 100644 --- a/typescript/136-Single-Number.ts +++ b/typescript/136-Single-Number.ts @@ -1,9 +1,9 @@ function singleNumber(nums: number[]): number { - let res = 0; + let res = 0; - for (let i = 0; i < nums.length; i++) { - res = nums[i] ^ res; - } + for (let i = 0; i < nums.length; i++) { + res = nums[i] ^ res; + } - return res; + return res; } diff --git a/typescript/139-Word-Break.ts b/typescript/139-Word-Break.ts index c20ad3ba0..1c0abb046 100644 --- a/typescript/139-Word-Break.ts +++ b/typescript/139-Word-Break.ts @@ -1,18 +1,18 @@ function wordBreak(s: string, wordDict: string[]): boolean { - const dp = Array(s.length + 1).fill(false); + const dp = Array(s.length + 1).fill(false); - dp[s.length] = true; + dp[s.length] = true; - for (let i = s.length - 1; i > -1; i--) { - for (const w of wordDict) { - if (i + w.length <= s.length && s.slice(i, i + w.length) == w) { - dp[i] = dp[i + w.length]; - } - if (dp[i]) { - break; - } + for (let i = s.length - 1; i > -1; i--) { + for (const w of wordDict) { + if (i + w.length <= s.length && s.slice(i, i + w.length) == w) { + dp[i] = dp[i + w.length]; + } + if (dp[i]) { + break; + } + } } - } - return dp[0]; + return dp[0]; } diff --git a/typescript/141-Linked-List-Cycle.ts b/typescript/141-Linked-List-Cycle.ts index 48990f3e6..7dd62d5ee 100644 --- a/typescript/141-Linked-List-Cycle.ts +++ b/typescript/141-Linked-List-Cycle.ts @@ -11,18 +11,18 @@ */ function hasCycle(head: ListNode | null): boolean { - let slow = head; - let fast = head; + let slow = head; + let fast = head; - while (fast && fast.next) { - if (slow) { - slow = slow.next; + while (fast && fast.next) { + if (slow) { + slow = slow.next; + } + fast = fast.next.next; + if (slow == fast) { + return true; + } } - fast = fast.next.next; - if (slow == fast) { - return true; - } - } - return false; + return false; } diff --git a/typescript/143-Reorder-List.ts b/typescript/143-Reorder-List.ts index 549c807cf..370ab5b67 100644 --- a/typescript/143-Reorder-List.ts +++ b/typescript/143-Reorder-List.ts @@ -14,35 +14,35 @@ Do not return anything, modify head in-place instead. */ function reorderList(head: ListNode | null): void { - let slow: ListNode | null | undefined = head; - let fast: ListNode | null | undefined = head?.next; + let slow: ListNode | null | undefined = head; + let fast: ListNode | null | undefined = head?.next; - while (fast && fast.next) { - slow = slow?.next; - fast = fast?.next?.next; - } + while (fast && fast.next) { + slow = slow?.next; + fast = fast?.next?.next; + } - // reverse second half - if (!(slow && slow.next)) return; - let second: ListNode | null = slow.next; - slow.next = null; - let prev: ListNode | null = null; - while (second) { - let temp = second.next; - second.next = prev; - prev = second; - second = temp; - } + // reverse second half + if (!(slow && slow.next)) return; + let second: ListNode | null = slow.next; + slow.next = null; + let prev: ListNode | null = null; + while (second) { + let temp = second.next; + second.next = prev; + prev = second; + second = temp; + } - // merge two halfs - let first: any = head; - second = prev; - while (second) { - let temp1 = first.next; - let temp2 = second.next; - first.next = second; - second.next = temp1; - first = temp1; - second = temp2; - } + // merge two halfs + let first: any = head; + second = prev; + while (second) { + let temp1 = first.next; + let temp2 = second.next; + first.next = second; + second.next = temp1; + first = temp1; + second = temp2; + } } diff --git a/typescript/15-3Sum.ts b/typescript/15-3Sum.ts index eee406ca8..be88fe6b4 100644 --- a/typescript/15-3Sum.ts +++ b/typescript/15-3Sum.ts @@ -1,29 +1,29 @@ function threeSum(nums: number[]): number[][] { - const res: number[][] = []; - nums = nums.sort((a, b) => a - b); + const res: number[][] = []; + nums = nums.sort((a, b) => a - b); - for (let i = 0; i < nums.length; i++) { - if (i > 0 && nums[i] == nums[i - 1]) { - continue; - } + for (let i = 0; i < nums.length; i++) { + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } - let l = i + 1; - let r = nums.length - 1; - while (l < r) { - let sum = nums[i] + nums[l] + nums[r]; + let l = i + 1; + let r = nums.length - 1; + while (l < r) { + let sum = nums[i] + nums[l] + nums[r]; - if (sum > 0) { - r -= 1; - } else if (sum < 0) { - l += 1; - } else { - res.push([nums[i], nums[l], nums[r]]); - l += 1; - while (nums[l] == nums[l - 1] && l < r) { - l += 1; + if (sum > 0) { + r -= 1; + } else if (sum < 0) { + l += 1; + } else { + res.push([nums[i], nums[l], nums[r]]); + l += 1; + while (nums[l] == nums[l - 1] && l < r) { + l += 1; + } + } } - } } - } - return res; + return res; } diff --git a/typescript/150-Evaluate-Reverse-Polish-Notation.ts b/typescript/150-Evaluate-Reverse-Polish-Notation.ts index 6d3230a04..a3c7bec9e 100644 --- a/typescript/150-Evaluate-Reverse-Polish-Notation.ts +++ b/typescript/150-Evaluate-Reverse-Polish-Notation.ts @@ -1,23 +1,23 @@ function evalRPN(tokens: string[]): number { - const stack: number[] = []; + const stack: number[] = []; - tokens.forEach((token) => { - if (token === '+') { - stack.push(Number(stack.pop()) + Number(stack.pop())); - } else if (token === '-') { - const a = Number(stack.pop()); - const b = Number(stack.pop()); - stack.push(b - a); - } else if (token === '/') { - const a = Number(stack.pop()); - const b = Number(stack.pop()); - stack.push(Math.trunc(b / a)); - } else if (token === '*') { - stack.push(Number(stack.pop()) * Number(stack.pop())); - } else { - stack.push(Number(token)); - } - }); + tokens.forEach((token) => { + if (token === '+') { + stack.push(Number(stack.pop()) + Number(stack.pop())); + } else if (token === '-') { + const a = Number(stack.pop()); + const b = Number(stack.pop()); + stack.push(b - a); + } else if (token === '/') { + const a = Number(stack.pop()); + const b = Number(stack.pop()); + stack.push(Math.trunc(b / a)); + } else if (token === '*') { + stack.push(Number(stack.pop()) * Number(stack.pop())); + } else { + stack.push(Number(token)); + } + }); - return stack[0]; + return stack[0]; } diff --git a/typescript/152-Maximum-Product-Subarray.ts b/typescript/152-Maximum-Product-Subarray.ts index 4f1fef063..a70db9b85 100644 --- a/typescript/152-Maximum-Product-Subarray.ts +++ b/typescript/152-Maximum-Product-Subarray.ts @@ -1,20 +1,20 @@ function maxProduct(nums: number[]): number { - let res = Math.max(...nums); - let curMax = 1; - let curMin = 1; + let res = Math.max(...nums); + let curMax = 1; + let curMin = 1; - for (const n of nums) { - if (n === 0) { - curMin = 1; - curMax = 1; - continue; - } + for (const n of nums) { + if (n === 0) { + curMin = 1; + curMax = 1; + continue; + } - let temp = curMax * n; - curMax = Math.max(n * curMax, n * curMin, n); - curMin = Math.min(temp, n * curMin, n); - res = Math.max(res, curMax); - } + let temp = curMax * n; + curMax = Math.max(n * curMax, n * curMin, n); + curMin = Math.min(temp, n * curMin, n); + res = Math.max(res, curMax); + } - return res; + return res; } diff --git a/typescript/153-Find-Minimum-in-Rotated-Sorted-Array.ts b/typescript/153-Find-Minimum-in-Rotated-Sorted-Array.ts index 30d488670..ea326b8f7 100644 --- a/typescript/153-Find-Minimum-in-Rotated-Sorted-Array.ts +++ b/typescript/153-Find-Minimum-in-Rotated-Sorted-Array.ts @@ -1,13 +1,13 @@ function findMin(nums: number[]): number { - let left: number = 0; - let right: number = nums.length - 1; - while (right > left) { - let midIdx: number = Math.floor((left + right) / 2); - if (nums[midIdx] > nums[right]) { - left = midIdx + 1; - } else { - right = midIdx; + let left: number = 0; + let right: number = nums.length - 1; + while (right > left) { + let midIdx: number = Math.floor((left + right) / 2); + if (nums[midIdx] > nums[right]) { + left = midIdx + 1; + } else { + right = midIdx; + } } - } - return nums[left]; + return nums[left]; } diff --git a/typescript/155-Min-Stack.ts b/typescript/155-Min-Stack.ts index d15f46cfb..84e719569 100644 --- a/typescript/155-Min-Stack.ts +++ b/typescript/155-Min-Stack.ts @@ -1,36 +1,36 @@ class MinStack { - stack: number[]; - minstack: number[]; + stack: number[]; + minstack: number[]; - constructor() { - this.stack = []; - this.minstack = []; - } + constructor() { + this.stack = []; + this.minstack = []; + } - push(val: number): void { - this.stack.push(val); - if ( - val < this.minstack[this.minstack.length - 1] || - this.minstack.length === 0 - ) { - this.minstack.push(val); - } else { - this.minstack.push(this.minstack[this.minstack.length - 1]); + push(val: number): void { + this.stack.push(val); + if ( + val < this.minstack[this.minstack.length - 1] || + this.minstack.length === 0 + ) { + this.minstack.push(val); + } else { + this.minstack.push(this.minstack[this.minstack.length - 1]); + } } - } - pop(): void { - this.stack.pop(); - this.minstack.pop(); - } + pop(): void { + this.stack.pop(); + this.minstack.pop(); + } - top(): number { - return this.stack[this.stack.length - 1]; - } + top(): number { + return this.stack[this.stack.length - 1]; + } - getMin(): number { - return this.minstack[this.minstack.length - 1]; - } + getMin(): number { + return this.minstack[this.minstack.length - 1]; + } } /** diff --git a/typescript/167-Two-Sum-II.ts b/typescript/167-Two-Sum-II.ts index 2d8c23590..ba7eadd09 100644 --- a/typescript/167-Two-Sum-II.ts +++ b/typescript/167-Two-Sum-II.ts @@ -1,14 +1,14 @@ function twoSum(numbers: number[], target: number): number[] { - let L = 0; - let R = numbers.length - 1; + let L = 0; + let R = numbers.length - 1; - while (numbers[L] + numbers[R] !== target) { - if (numbers[L] + numbers[R] > target) { - R = R - 1; - } else if (numbers[L] + numbers[R] < target) { - L = L + 1; + while (numbers[L] + numbers[R] !== target) { + if (numbers[L] + numbers[R] > target) { + R = R - 1; + } else if (numbers[L] + numbers[R] < target) { + L = L + 1; + } } - } - return [L + 1, R + 1]; + return [L + 1, R + 1]; } diff --git a/typescript/17-Letter-Combinations-of-a-Phone-Number.ts b/typescript/17-Letter-Combinations-of-a-Phone-Number.ts index b54150a79..23badfda1 100644 --- a/typescript/17-Letter-Combinations-of-a-Phone-Number.ts +++ b/typescript/17-Letter-Combinations-of-a-Phone-Number.ts @@ -1,31 +1,31 @@ function letterCombinations(digits: string): string[] { - let res: string[] = []; + let res: string[] = []; - const digitToChar = { - '2': 'abc', - '3': 'def', - '4': 'ghi', - '5': 'jkl', - '6': 'mno', - '7': 'qprs', - '8': 'tuv', - '9': 'wxyz', - }; + const digitToChar = { + '2': 'abc', + '3': 'def', + '4': 'ghi', + '5': 'jkl', + '6': 'mno', + '7': 'qprs', + '8': 'tuv', + '9': 'wxyz', + }; - function backtrack(i: number, curStr: string) { - if (curStr.length === digits.length) { - res.push(curStr); - return; - } + function backtrack(i: number, curStr: string) { + if (curStr.length === digits.length) { + res.push(curStr); + return; + } - for (const c of digitToChar[digits[i]]) { - backtrack(i + 1, curStr + c); + for (const c of digitToChar[digits[i]]) { + backtrack(i + 1, curStr + c); + } } - } - if (digits) { - backtrack(0, ''); - } + if (digits) { + backtrack(0, ''); + } - return res; + return res; } diff --git a/typescript/19-Remove-Nth-Node-From-End-of-List.ts b/typescript/19-Remove-Nth-Node-From-End-of-List.ts index e8045142d..dc5330234 100644 --- a/typescript/19-Remove-Nth-Node-From-End-of-List.ts +++ b/typescript/19-Remove-Nth-Node-From-End-of-List.ts @@ -11,21 +11,21 @@ */ function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { - let dummy: ListNode = new ListNode(0, head); - let left = dummy; - let right = head; + let dummy: ListNode = new ListNode(0, head); + let left = dummy; + let right = head; - while (n > 0) { - right = right.next; - n -= 1; - } + while (n > 0) { + right = right.next; + n -= 1; + } - while (right) { - left = left.next; - right = right.next; - } + while (right) { + left = left.next; + right = right.next; + } - // delete - left.next = left.next.next; - return dummy.next; + // delete + left.next = left.next.next; + return dummy.next; } diff --git a/typescript/191-Number-of-1-Bits.ts b/typescript/191-Number-of-1-Bits.ts index 426665e0d..d2e9cba35 100644 --- a/typescript/191-Number-of-1-Bits.ts +++ b/typescript/191-Number-of-1-Bits.ts @@ -1,12 +1,12 @@ function hammingWeight(n: number): number { - let base2 = n.toString(2).split(''); - let count = 0; + let base2 = n.toString(2).split(''); + let count = 0; - base2.forEach((item) => { - if (item === '1') { - count += 1; - } - }); + base2.forEach((item) => { + if (item === '1') { + count += 1; + } + }); - return count; + return count; } diff --git a/typescript/198-House-Robber.ts b/typescript/198-House-Robber.ts index b5efaa77c..fda63adc5 100644 --- a/typescript/198-House-Robber.ts +++ b/typescript/198-House-Robber.ts @@ -1,12 +1,12 @@ function rob(nums: number[]): number { - let rob1 = 0; - let rob2 = 0; + let rob1 = 0; + let rob2 = 0; - for (const n of nums) { - let temp = Math.max(n + rob1, rob2); - rob1 = rob2; - rob2 = temp; - } + for (const n of nums) { + let temp = Math.max(n + rob1, rob2); + rob1 = rob2; + rob2 = temp; + } - return rob2; + return rob2; } diff --git a/typescript/2-Add-Two-Numbers.ts b/typescript/2-Add-Two-Numbers.ts index 8152928aa..94e91f412 100644 --- a/typescript/2-Add-Two-Numbers.ts +++ b/typescript/2-Add-Two-Numbers.ts @@ -11,27 +11,27 @@ */ function addTwoNumbers( - l1: ListNode | null, - l2: ListNode | null + l1: ListNode | null, + l2: ListNode | null ): ListNode | null { - let dummyNode: ListNode = new ListNode(); - let currentNode: ListNode = dummyNode; - let carry: number = 0; + let dummyNode: ListNode = new ListNode(); + let currentNode: ListNode = dummyNode; + let carry: number = 0; - while (l1 !== null || l2 !== null || carry !== 0) { - const val1 = l1 !== null ? l1.val : 0; - const val2 = l2 !== null ? l2.val : 0; + while (l1 !== null || l2 !== null || carry !== 0) { + const val1 = l1 !== null ? l1.val : 0; + const val2 = l2 !== null ? l2.val : 0; - const sum: number = val1 + val2 + carry; - const value: number = sum % 10; - const newLinkedList: ListNode = new ListNode(value); - currentNode.next = newLinkedList; - currentNode = newLinkedList; - carry = Math.floor(sum / 10); + const sum: number = val1 + val2 + carry; + const value: number = sum % 10; + const newLinkedList: ListNode = new ListNode(value); + currentNode.next = newLinkedList; + currentNode = newLinkedList; + carry = Math.floor(sum / 10); - l1 = l1 !== null ? l1.next : null; - l2 = l2 !== null ? l2.next : null; - } + l1 = l1 !== null ? l1.next : null; + l2 = l2 !== null ? l2.next : null; + } - return dummyNode.next; + return dummyNode.next; } diff --git a/typescript/20-Valid-Parentheses.ts b/typescript/20-Valid-Parentheses.ts index ce6388132..c6d9178ae 100644 --- a/typescript/20-Valid-Parentheses.ts +++ b/typescript/20-Valid-Parentheses.ts @@ -1,28 +1,28 @@ function isValid(s: string): boolean { - const closingToOpening = { - '}': '{', - ']': '[', - ')': '(', - }; - const stack: string[] = []; - const chars = s.split(''); + const closingToOpening = { + '}': '{', + ']': '[', + ')': '(', + }; + const stack: string[] = []; + const chars = s.split(''); - for (let i = 0; i < chars.length; i++) { - const element = chars[i]; - if (element in closingToOpening) { - const pop = stack.pop(); + for (let i = 0; i < chars.length; i++) { + const element = chars[i]; + if (element in closingToOpening) { + const pop = stack.pop(); - if (closingToOpening[element] === pop) { - continue; - } else { - return false; - } - } else { - stack.push(element); + if (closingToOpening[element] === pop) { + continue; + } else { + return false; + } + } else { + stack.push(element); + } } - } - if (stack.length > 0) return false; + if (stack.length > 0) return false; - return true; + return true; } diff --git a/typescript/202-Happy-Number.ts b/typescript/202-Happy-Number.ts index 9d126d4d3..3bd506415 100644 --- a/typescript/202-Happy-Number.ts +++ b/typescript/202-Happy-Number.ts @@ -1,25 +1,25 @@ function isHappy(n: number): boolean { - const visit = new Set(); + const visit = new Set(); - while (!visit.has(n)) { - visit.add(n); - n = sumOfSquares(n); + while (!visit.has(n)) { + visit.add(n); + n = sumOfSquares(n); - if (n == 1) return true; - } + if (n == 1) return true; + } - return false; + return false; } function sumOfSquares(n: number): number { - let output = 0; + let output = 0; - while (n) { - let digit = n % 10; - digit = digit ** 2; - output += digit; - n = Math.floor(n / 10); - } + while (n) { + let digit = n % 10; + digit = digit ** 2; + output += digit; + n = Math.floor(n / 10); + } - return output; + return output; } diff --git a/typescript/206-Reverse-Linked-List.ts b/typescript/206-Reverse-Linked-List.ts index 792b7e1e8..e8c6207b1 100644 --- a/typescript/206-Reverse-Linked-List.ts +++ b/typescript/206-Reverse-Linked-List.ts @@ -11,13 +11,13 @@ */ function reverseList(head: ListNode | null): ListNode | null { - let prev: ListNode | null = null; + let prev: ListNode | null = null; - while (head) { - let ele = head.next; - head.next = prev; - prev = head; - head = ele; - } - return prev; + while (head) { + let ele = head.next; + head.next = prev; + prev = head; + head = ele; + } + return prev; } diff --git a/typescript/208-Implement-Trie.ts b/typescript/208-Implement-Trie.ts index 25c15196a..7a86a84dd 100644 --- a/typescript/208-Implement-Trie.ts +++ b/typescript/208-Implement-Trie.ts @@ -1,55 +1,55 @@ class TrieNode { - children: {}; - endOfWord: boolean; - constructor() { - this.children = {}; - this.endOfWord = false; - } + children: {}; + endOfWord: boolean; + constructor() { + this.children = {}; + this.endOfWord = false; + } } class Trie { - root: TrieNode; - constructor() { - this.root = new TrieNode(); - } - - insert(word: string): void { - let cur = this.root; - - for (const c of word) { - if (!(c in cur.children)) { - cur.children[c] = new TrieNode(); - } - cur = cur.children[c]; + root: TrieNode; + constructor() { + this.root = new TrieNode(); } - cur.endOfWord = true; - } - search(word: string): boolean { - let cur = this.root; + insert(word: string): void { + let cur = this.root; - for (const c of word) { - if (!(c in cur.children)) { - return false; - } - cur = cur.children[c]; + for (const c of word) { + if (!(c in cur.children)) { + cur.children[c] = new TrieNode(); + } + cur = cur.children[c]; + } + cur.endOfWord = true; } - return cur.endOfWord; - } + search(word: string): boolean { + let cur = this.root; - startsWith(prefix: string): boolean { - let cur = this.root; + for (const c of word) { + if (!(c in cur.children)) { + return false; + } + cur = cur.children[c]; + } - for (const c of prefix) { - if (!(c in cur.children)) { - return false; - } - cur = cur.children[c]; + return cur.endOfWord; } - return true; - } + startsWith(prefix: string): boolean { + let cur = this.root; + + for (const c of prefix) { + if (!(c in cur.children)) { + return false; + } + cur = cur.children[c]; + } + + return true; + } } const trie = new Trie(); diff --git a/typescript/21-Merge-Two-Sorted-Lists.ts b/typescript/21-Merge-Two-Sorted-Lists.ts index 6f12d7340..83dbbef75 100644 --- a/typescript/21-Merge-Two-Sorted-Lists.ts +++ b/typescript/21-Merge-Two-Sorted-Lists.ts @@ -11,26 +11,26 @@ */ function mergeTwoLists( - list1: ListNode | null, - list2: ListNode | null + list1: ListNode | null, + list2: ListNode | null ): ListNode | null { - let dummyList: ListNode = new ListNode(0); - let currentNode: ListNode = dummyList; + let dummyList: ListNode = new ListNode(0); + let currentNode: ListNode = dummyList; - while (list1 !== null && list2 !== null) { - if (list1.val < list2.val) { - currentNode.next = list1; - list1 = list1.next; - } else { - currentNode.next = list2; - list2 = list2.next; - } + while (list1 !== null && list2 !== null) { + if (list1.val < list2.val) { + currentNode.next = list1; + list1 = list1.next; + } else { + currentNode.next = list2; + list2 = list2.next; + } - currentNode = currentNode.next; - } + currentNode = currentNode.next; + } - if (list1 !== null) currentNode.next = list1; - if (list2 !== null) currentNode.next = list2; + if (list1 !== null) currentNode.next = list1; + if (list2 !== null) currentNode.next = list2; - return dummyList.next; + return dummyList.next; } diff --git a/typescript/211-Design-Add-and-Search-Words-Data-Structure.ts b/typescript/211-Design-Add-and-Search-Words-Data-Structure.ts index 7c239b593..2bbcdd69a 100644 --- a/typescript/211-Design-Add-and-Search-Words-Data-Structure.ts +++ b/typescript/211-Design-Add-and-Search-Words-Data-Structure.ts @@ -1,57 +1,62 @@ class TrieNode { - children: { [key: string]: TrieNode }; - endOfWord: boolean; - constructor() { - this.children = {}; - this.endOfWord = false; - } + children: { [key: string]: TrieNode }; + endOfWord: boolean; + constructor() { + this.children = {}; + this.endOfWord = false; + } } class WordDictionary { - root: TrieNode; - constructor() { - this.root = new TrieNode(); - } + root: TrieNode; + constructor() { + this.root = new TrieNode(); + } - addWord(word: string): void { - let cur = this.root; + addWord(word: string): void { + let cur = this.root; - for (const c of word) { - if (!(c in cur.children)) { - cur.children[c] = new TrieNode(); - } - cur = cur.children[c]; + for (const c of word) { + if (!(c in cur.children)) { + cur.children[c] = new TrieNode(); + } + cur = cur.children[c]; + } + cur.endOfWord = true; } - cur.endOfWord = true; - } - search(word: string): boolean { - function dfs(j: number, root: TrieNode): boolean { - let cur = root; + search(word: string): boolean { + function dfs(j: number, root: TrieNode): boolean { + let cur = root; - for (let i = j; i < word.length; i++) { - const c = word[i]; + for (let i = j; i < word.length; i++) { + const c = word[i]; - if (c === '.') { - for (const key in cur.children) { - if (Object.prototype.hasOwnProperty.call(cur.children, key)) { - const child = cur.children[key]; - if (dfs(i + 1, child)) { - return true; - } + if (c === '.') { + for (const key in cur.children) { + if ( + Object.prototype.hasOwnProperty.call( + cur.children, + key + ) + ) { + const child = cur.children[key]; + if (dfs(i + 1, child)) { + return true; + } + } + } + return false; + } else { + if (!(c in cur.children)) { + return false; + } + cur = cur.children[c]; + } } - } - return false; - } else { - if (!(c in cur.children)) { - return false; - } - cur = cur.children[c]; - } - } - return cur.endOfWord; + return cur.endOfWord; + } + return dfs(0, this.root); } - return dfs(0, this.root); - } } diff --git a/typescript/213-House-Robber-II.ts b/typescript/213-House-Robber-II.ts index 91ff332f7..b8cbfe6f8 100644 --- a/typescript/213-House-Robber-II.ts +++ b/typescript/213-House-Robber-II.ts @@ -1,20 +1,20 @@ function helper(nums: number[]): number { - let rob1 = 0; - let rob2 = 0; + let rob1 = 0; + let rob2 = 0; - for (const n of nums) { - let temp = Math.max(n + rob1, rob2); - rob1 = rob2; - rob2 = temp; - } + for (const n of nums) { + let temp = Math.max(n + rob1, rob2); + rob1 = rob2; + rob2 = temp; + } - return rob2; + return rob2; } function rob(nums: number[]): number { - return Math.max( - nums[0], - helper(nums.slice(0, nums.length - 1)), - helper(nums.slice(1)) - ); + return Math.max( + nums[0], + helper(nums.slice(0, nums.length - 1)), + helper(nums.slice(1)) + ); } diff --git a/typescript/217-Contains-Duplicate.ts b/typescript/217-Contains-Duplicate.ts index f569cdf6e..f93d89eb9 100644 --- a/typescript/217-Contains-Duplicate.ts +++ b/typescript/217-Contains-Duplicate.ts @@ -1,10 +1,10 @@ function containsDuplicate(nums: number[]): boolean { - const set = new Set(); + const set = new Set(); - for (let i = 0; i < nums.length; i++) { - if (set.has(nums[i])) return true; - else set.add(nums[i]); - } + for (let i = 0; i < nums.length; i++) { + if (set.has(nums[i])) return true; + else set.add(nums[i]); + } - return false; + return false; } diff --git a/typescript/22-Generate-Parentheses.ts b/typescript/22-Generate-Parentheses.ts index 6783cb7c3..e51e7c2a6 100644 --- a/typescript/22-Generate-Parentheses.ts +++ b/typescript/22-Generate-Parentheses.ts @@ -1,27 +1,27 @@ function generateParenthesis(n: number): string[] { - const stack: string[] = []; - const res: string[] = []; + const stack: string[] = []; + const res: string[] = []; - function backtrack(openN: number, closedN: number) { - if (openN === n && closedN === n) { - res.push(stack.join('')); - return; - } + function backtrack(openN: number, closedN: number) { + if (openN === n && closedN === n) { + res.push(stack.join('')); + return; + } - if (openN < n) { - stack.push('('); - backtrack(openN + 1, closedN); - stack.pop(); - } + if (openN < n) { + stack.push('('); + backtrack(openN + 1, closedN); + stack.pop(); + } - if (closedN < openN) { - stack.push(')'); - backtrack(openN, closedN + 1); - stack.pop(); + if (closedN < openN) { + stack.push(')'); + backtrack(openN, closedN + 1); + stack.pop(); + } } - } - backtrack(0, 0); + backtrack(0, 0); - return res; + return res; } diff --git a/typescript/226-Invert-Binary-Tree.ts b/typescript/226-Invert-Binary-Tree.ts index 7b98dd7c3..959c509c8 100644 --- a/typescript/226-Invert-Binary-Tree.ts +++ b/typescript/226-Invert-Binary-Tree.ts @@ -13,15 +13,15 @@ */ function invertTree(root: TreeNode | null): TreeNode | null { - let temp: TreeNode | null; + let temp: TreeNode | null; - if (!root) return null; + if (!root) return null; - if (root.left || root.right) { - temp = root.left; - root.left = invertTree(root.right); - root.right = invertTree(temp); - } + if (root.left || root.right) { + temp = root.left; + root.left = invertTree(root.right); + root.right = invertTree(temp); + } - return root; + return root; } diff --git a/typescript/235-Lowest-Common-Ancestor-of-a-Binary Search-Tree.ts b/typescript/235-Lowest-Common-Ancestor-of-a-Binary Search-Tree.ts index 141942cac..6d4db5b9b 100644 --- a/typescript/235-Lowest-Common-Ancestor-of-a-Binary Search-Tree.ts +++ b/typescript/235-Lowest-Common-Ancestor-of-a-Binary Search-Tree.ts @@ -13,19 +13,19 @@ */ function lowestCommonAncestor( - root: TreeNode | null, - p: TreeNode | null, - q: TreeNode | null + root: TreeNode | null, + p: TreeNode | null, + q: TreeNode | null ): TreeNode | null { - let cur = root; + let cur = root; - while (cur) { - if (p.val > cur.val && q.val > cur.val) { - cur = cur.right; - } else if (p.val < cur.val && q.val < cur.val) { - cur = cur.left; - } else { - return cur; + while (cur) { + if (p.val > cur.val && q.val > cur.val) { + cur = cur.right; + } else if (p.val < cur.val && q.val < cur.val) { + cur = cur.left; + } else { + return cur; + } } - } } diff --git a/typescript/238-Product-of-Array-Except-Self.ts b/typescript/238-Product-of-Array-Except-Self.ts index 8fa4d93ee..e2bcf6883 100644 --- a/typescript/238-Product-of-Array-Except-Self.ts +++ b/typescript/238-Product-of-Array-Except-Self.ts @@ -1,18 +1,18 @@ function productExceptSelf(nums: number[]): number[] { - const array: Array = []; - let product: number = 1; + const array: Array = []; + let product: number = 1; - for (let idx = 0; idx < nums.length; idx++) { - array[idx] = product; - product *= nums[idx]; - } + for (let idx = 0; idx < nums.length; idx++) { + array[idx] = product; + product *= nums[idx]; + } - product = 1; + product = 1; - for (let idx = nums.length - 1; idx >= 0; idx--) { - array[idx] *= product; - product *= nums[idx]; - } + for (let idx = nums.length - 1; idx >= 0; idx--) { + array[idx] *= product; + product *= nums[idx]; + } - return array; + return array; } diff --git a/typescript/242-Valid-Anagram.ts b/typescript/242-Valid-Anagram.ts index 1c7b5e2a9..76a5ef0c5 100644 --- a/typescript/242-Valid-Anagram.ts +++ b/typescript/242-Valid-Anagram.ts @@ -1,20 +1,20 @@ function isAnagram(s: string, t: string) { - if (s.length !== t.length) return false; + if (s.length !== t.length) return false; - let first: Array = s.split(''); - const second = t.split(''); + let first: Array = s.split(''); + const second = t.split(''); - for (let i = 0; i < second.length; i++) { - const element = second[i]; + for (let i = 0; i < second.length; i++) { + const element = second[i]; - let found = first.indexOf(element); + let found = first.indexOf(element); - if (found !== -1) { - first[found] = null; - } else { - return false; + if (found !== -1) { + first[found] = null; + } else { + return false; + } } - } - return true; + return true; } diff --git a/typescript/242-Valid-Anagrams.ts b/typescript/242-Valid-Anagrams.ts index 4ec3da0ce..506812c10 100644 --- a/typescript/242-Valid-Anagrams.ts +++ b/typescript/242-Valid-Anagrams.ts @@ -1,16 +1,16 @@ function isAnagram(s: string, t: string): boolean { - if (s.length !== t.length) return false; + if (s.length !== t.length) return false; - const store = new Array(26).fill(0); + const store = new Array(26).fill(0); - for (let i = 0; i < s.length; i++) { - store[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; - store[t.charCodeAt(i) - 'a'.charCodeAt(0)]--; - } + for (let i = 0; i < s.length; i++) { + store[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; + store[t.charCodeAt(i) - 'a'.charCodeAt(0)]--; + } - for (let i = 0; i < store.length; i++) { - if (store[i] !== 0) return false; - } + for (let i = 0; i < store.length; i++) { + if (store[i] !== 0) return false; + } - return true; + return true; } diff --git a/typescript/261-Graph-Valid-Tree.ts b/typescript/261-Graph-Valid-Tree.ts index 6bd391ce5..99d286cd9 100644 --- a/typescript/261-Graph-Valid-Tree.ts +++ b/typescript/261-Graph-Valid-Tree.ts @@ -1,42 +1,42 @@ interface Obj { - [key: number]: Array; + [key: number]: Array; } interface Visited { - [key: number]: boolean; + [key: number]: boolean; } function validTree(n: number, edges: number[][]): boolean { - if (n === 0) return true; + if (n === 0) return true; - let adjacent: Obj = {}; - let visited: Visited = {}; - for (let i = 0; i < n; i++) { - adjacent[i] = []; - } + let adjacent: Obj = {}; + let visited: Visited = {}; + for (let i = 0; i < n; i++) { + adjacent[i] = []; + } - for (const val of edges) { - const [n1, n2] = val; - adjacent[n1].push(n2); - adjacent[n2].push(n1); - } + for (const val of edges) { + const [n1, n2] = val; + adjacent[n1].push(n2); + adjacent[n2].push(n1); + } - return dfs(0, -1, visited, adjacent) && Object.keys(visited).length === n; + return dfs(0, -1, visited, adjacent) && Object.keys(visited).length === n; } function dfs( - node: number, - prevNode: number, - visited: Visited, - adjacent: Obj + node: number, + prevNode: number, + visited: Visited, + adjacent: Obj ): boolean { - if (visited[node]) return false; - visited[node] = true; + if (visited[node]) return false; + visited[node] = true; - for (const ele of adjacent[node]) { - if (ele === prevNode) continue; - if (!dfs(ele, node, visited, adjacent)) return false; - } + for (const ele of adjacent[node]) { + if (ele === prevNode) continue; + if (!dfs(ele, node, visited, adjacent)) return false; + } - return true; + return true; } diff --git a/typescript/268-Missing-Number.ts b/typescript/268-Missing-Number.ts index ceb92fea4..e6907a99f 100644 --- a/typescript/268-Missing-Number.ts +++ b/typescript/268-Missing-Number.ts @@ -1,8 +1,8 @@ function missingNumber(nums: number[]): number { - let sum: number = 0; - let total: number = (nums.length * (nums.length + 1)) / 2; - for (let i = 0; i < nums.length; i++) { - sum += nums[i]; - } - return total - sum; + let sum: number = 0; + let total: number = (nums.length * (nums.length + 1)) / 2; + for (let i = 0; i < nums.length; i++) { + sum += nums[i]; + } + return total - sum; } diff --git a/typescript/287-Find-the-Duplicate-Number.ts b/typescript/287-Find-the-Duplicate-Number.ts index ed3fee9c5..d68cf28d4 100644 --- a/typescript/287-Find-the-Duplicate-Number.ts +++ b/typescript/287-Find-the-Duplicate-Number.ts @@ -11,23 +11,23 @@ */ function findDuplicate(nums: number[]): number { - let slow = 0; - let fast = 0; - while (true) { - slow = nums[slow]; - fast = nums[nums[fast]]; - if (slow == fast) { - break; + let slow = 0; + let fast = 0; + while (true) { + slow = nums[slow]; + fast = nums[nums[fast]]; + if (slow == fast) { + break; + } } - } - let slow2 = 0; + let slow2 = 0; - while (true) { - slow = nums[slow]; - slow2 = nums[slow2]; - if (slow == slow2) { - break; + while (true) { + slow = nums[slow]; + slow2 = nums[slow2]; + if (slow == slow2) { + break; + } } - } - return slow; + return slow; } diff --git a/typescript/3-Longest-Substring-Without-Repeating-Characters.ts b/typescript/3-Longest-Substring-Without-Repeating-Characters.ts index bd48df17b..dd2137f77 100644 --- a/typescript/3-Longest-Substring-Without-Repeating-Characters.ts +++ b/typescript/3-Longest-Substring-Without-Repeating-Characters.ts @@ -1,15 +1,15 @@ function lengthOfLongestSubstring(s: string): number { - const charSet = new Set(); - let l = 0; - let res = 0; + const charSet = new Set(); + let l = 0; + let res = 0; - for (let r = 0; r < s.length; r++) { - while (charSet.has(s[r])) { - charSet.delete(s[l]); - l += 1; + for (let r = 0; r < s.length; r++) { + while (charSet.has(s[r])) { + charSet.delete(s[l]); + l += 1; + } + charSet.add(s[r]); + res = Math.max(res, r - l + 1); } - charSet.add(s[r]); - res = Math.max(res, r - l + 1); - } - return res; + return res; } diff --git a/typescript/300-Longest-Increasing-Subsequence.ts b/typescript/300-Longest-Increasing-Subsequence.ts index 2e2047309..9d0c0145c 100644 --- a/typescript/300-Longest-Increasing-Subsequence.ts +++ b/typescript/300-Longest-Increasing-Subsequence.ts @@ -1,13 +1,13 @@ function lengthOfLIS(nums: number[]): number { - const lis = Array(nums.length).fill(1); + const lis = Array(nums.length).fill(1); - for (let i = nums.length - 1; i > -1; i--) { - for (let j = i + 1; j < nums.length; j++) { - if (nums[i] < nums[j]) { - lis[i] = Math.max(lis[i], 1 + lis[j]); - } + for (let i = nums.length - 1; i > -1; i--) { + for (let j = i + 1; j < nums.length; j++) { + if (nums[i] < nums[j]) { + lis[i] = Math.max(lis[i], 1 + lis[j]); + } + } } - } - return Math.max(...lis); + return Math.max(...lis); } diff --git a/typescript/322-Coin-Change.ts b/typescript/322-Coin-Change.ts index 5ef66d52f..74bffaa51 100644 --- a/typescript/322-Coin-Change.ts +++ b/typescript/322-Coin-Change.ts @@ -1,15 +1,15 @@ function coinChange(coins: number[], amount: number): number { - const dp = Array(amount + 1).fill(amount + 1); + const dp = Array(amount + 1).fill(amount + 1); - dp[0] = 0; + dp[0] = 0; - for (let a = 1; a < amount + 1; a++) { - for (const c of coins) { - if (a - c >= 0) { - dp[a] = Math.min(dp[a], 1 + dp[a - c]); - } + for (let a = 1; a < amount + 1; a++) { + for (const c of coins) { + if (a - c >= 0) { + dp[a] = Math.min(dp[a], 1 + dp[a - c]); + } + } } - } - return dp[amount] != amount + 1 ? dp[amount] : -1; + return dp[amount] != amount + 1 ? dp[amount] : -1; } diff --git a/typescript/33-Search-in-Rotated-Sorted-Array.ts b/typescript/33-Search-in-Rotated-Sorted-Array.ts index ad02f99b6..185348293 100644 --- a/typescript/33-Search-in-Rotated-Sorted-Array.ts +++ b/typescript/33-Search-in-Rotated-Sorted-Array.ts @@ -1,18 +1,20 @@ function search(nums: number[], target: number): number { - let left: number = 0; - let right: number = nums.length - 1; + let left: number = 0; + let right: number = nums.length - 1; - while (left <= right) { - let midIdx: number = Math.floor((left + right) / 2); - if (nums[midIdx] === target) return midIdx; + while (left <= right) { + let midIdx: number = Math.floor((left + right) / 2); + if (nums[midIdx] === target) return midIdx; - if (nums[left] <= nums[midIdx]) { - if (nums[left] <= target && target <= nums[midIdx]) right = midIdx - 1; - else left = midIdx + 1; - } else { - if (nums[midIdx] <= target && target <= nums[right]) left = midIdx + 1; - else right = midIdx - 1; + if (nums[left] <= nums[midIdx]) { + if (nums[left] <= target && target <= nums[midIdx]) + right = midIdx - 1; + else left = midIdx + 1; + } else { + if (nums[midIdx] <= target && target <= nums[right]) + left = midIdx + 1; + else right = midIdx - 1; + } } - } - return -1; + return -1; } diff --git a/typescript/338-Counting-Bits.ts b/typescript/338-Counting-Bits.ts index b6e230e11..560f590d8 100644 --- a/typescript/338-Counting-Bits.ts +++ b/typescript/338-Counting-Bits.ts @@ -1,22 +1,22 @@ function countBits(n: number): number[] { - const ans: number[] = []; + const ans: number[] = []; - for (let i = 0; i < n + 1; i++) { - ans.push(hammingWeight(i)); - } + for (let i = 0; i < n + 1; i++) { + ans.push(hammingWeight(i)); + } - return ans; + return ans; } function hammingWeight(n: number): number { - let base2 = n.toString(2).split(''); - let count = 0; + let base2 = n.toString(2).split(''); + let count = 0; - base2.forEach((item) => { - if (item === '1') { - count += 1; - } - }); + base2.forEach((item) => { + if (item === '1') { + count += 1; + } + }); - return count; + return count; } diff --git a/typescript/347-Top-K-Frequent-Elements.ts b/typescript/347-Top-K-Frequent-Elements.ts index a94576870..3cf832492 100644 --- a/typescript/347-Top-K-Frequent-Elements.ts +++ b/typescript/347-Top-K-Frequent-Elements.ts @@ -1,36 +1,36 @@ function topKFrequent(nums: number[], k: number): number[] | undefined { - const hash: { - [key: number]: number; - } = {}; + const hash: { + [key: number]: number; + } = {}; - const freq: number[][] = Array.apply(null, Array(nums.length + 1)).map( - () => [] - ); + const freq: number[][] = Array.apply(null, Array(nums.length + 1)).map( + () => [] + ); - nums.forEach((item) => { - if (hash[item]) { - hash[item]++; - } else { - hash[item] = 1; - } - }); + nums.forEach((item) => { + if (hash[item]) { + hash[item]++; + } else { + hash[item] = 1; + } + }); - Object.keys(hash).forEach((item) => { - const key = Number(item); - const value = hash[item]; - freq[value].push(key); - }); + Object.keys(hash).forEach((item) => { + const key = Number(item); + const value = hash[item]; + freq[value].push(key); + }); - const res: number[] = []; + const res: number[] = []; - for (let i = freq.length - 1; i >= 0; i--) { - const element = freq[i]; - for (let j = 0; j < element.length; j++) { - const second = element[j]; - res.push(Number(second)); - if (res.length == k) { - return res; - } + for (let i = freq.length - 1; i >= 0; i--) { + const element = freq[i]; + for (let j = 0; j < element.length; j++) { + const second = element[j]; + res.push(Number(second)); + if (res.length == k) { + return res; + } + } } - } } diff --git a/typescript/36-Valid-Sudoku.ts b/typescript/36-Valid-Sudoku.ts index b37326047..8cd21e64f 100644 --- a/typescript/36-Valid-Sudoku.ts +++ b/typescript/36-Valid-Sudoku.ts @@ -1,37 +1,41 @@ function isValidSudoku(board: string[][]): boolean { - const rows = {}; - const cols = {}; - const squares = {}; + const rows = {}; + const cols = {}; + const squares = {}; - for (let r = 0; r < 9; r++) { - for (let c = 0; c < 9; c++) { - const num = board[r][c]; + for (let r = 0; r < 9; r++) { + for (let c = 0; c < 9; c++) { + const num = board[r][c]; - if (num === '.') { - continue; - } + if (num === '.') { + continue; + } - const grid = `${Math.floor(r / 3)}${Math.floor(c / 3)}`; + const grid = `${Math.floor(r / 3)}${Math.floor(c / 3)}`; - if (!cols[c]) { - cols[c] = new Set(); - } - if (!rows[r]) { - rows[r] = new Set(); - } - if (!squares[grid]) { - squares[grid] = new Set(); - } + if (!cols[c]) { + cols[c] = new Set(); + } + if (!rows[r]) { + rows[r] = new Set(); + } + if (!squares[grid]) { + squares[grid] = new Set(); + } - if (rows[r].has(num) || cols[c].has(num) || squares[grid].has(num)) { - return false; - } + if ( + rows[r].has(num) || + cols[c].has(num) || + squares[grid].has(num) + ) { + return false; + } - cols[c].add(num); - rows[r].add(num); - squares[grid].add(num); + cols[c].add(num); + rows[r].add(num); + squares[grid].add(num); + } } - } - return true; + return true; } diff --git a/typescript/39-Combination-Sum.ts b/typescript/39-Combination-Sum.ts index 21110ae20..afe98a97e 100644 --- a/typescript/39-Combination-Sum.ts +++ b/typescript/39-Combination-Sum.ts @@ -1,23 +1,23 @@ function combinationSum(candidates: number[], target: number): number[][] { - let res: number[][] = []; + let res: number[][] = []; - function dfs(i: number, cur: number[], total: number) { - if (total == target) { - res.push(cur.slice()); - return; - } - if (i >= candidates.length || total > target) { - return; - } + function dfs(i: number, cur: number[], total: number) { + if (total == target) { + res.push(cur.slice()); + return; + } + if (i >= candidates.length || total > target) { + return; + } - cur.push(candidates[i]); - dfs(i, cur, total + candidates[i]); + cur.push(candidates[i]); + dfs(i, cur, total + candidates[i]); - cur.pop(); - dfs(i + 1, cur, total); - } + cur.pop(); + dfs(i + 1, cur, total); + } - dfs(0, [], 0); + dfs(0, [], 0); - return res; + return res; } diff --git a/typescript/40-Combination-Sum-II.ts b/typescript/40-Combination-Sum-II.ts index 832224b8d..67014894f 100644 --- a/typescript/40-Combination-Sum-II.ts +++ b/typescript/40-Combination-Sum-II.ts @@ -1,32 +1,32 @@ function combinationSum2(candidates: number[], target: number): number[][] { - candidates.sort(); + candidates.sort(); - const res: number[][] = []; + const res: number[][] = []; - function backtrack(cur: number[], pos: number, target: number) { - if (target === 0) { - res.push(cur.slice()); - } - if (target <= 0) { - return; - } - let prev = -1; + function backtrack(cur: number[], pos: number, target: number) { + if (target === 0) { + res.push(cur.slice()); + } + if (target <= 0) { + return; + } + let prev = -1; - for (let i = pos; i < candidates.length; i++) { - if (candidates[i] == prev) { - continue; - } + for (let i = pos; i < candidates.length; i++) { + if (candidates[i] == prev) { + continue; + } - cur.push(candidates[i]); + cur.push(candidates[i]); - backtrack(cur, i + 1, target - candidates[i]); + backtrack(cur, i + 1, target - candidates[i]); - cur.pop(); - prev = candidates[i]; + cur.pop(); + prev = candidates[i]; + } } - } - backtrack([], 0, target); + backtrack([], 0, target); - return res; + return res; } diff --git a/typescript/42-Trapping-Rain-Water.ts b/typescript/42-Trapping-Rain-Water.ts index f79345b21..72d21956b 100644 --- a/typescript/42-Trapping-Rain-Water.ts +++ b/typescript/42-Trapping-Rain-Water.ts @@ -1,23 +1,23 @@ function trap(height: number[]): number { - if (!height) return 0; + if (!height) return 0; - let l = 0; - let r = height.length - 1; - let leftMax = height[l]; - let rightMax = height[r]; - let res = 0; + let l = 0; + let r = height.length - 1; + let leftMax = height[l]; + let rightMax = height[r]; + let res = 0; - while (l < r) { - if (leftMax < rightMax) { - l += 1; - leftMax = Math.max(leftMax, height[l]); - res += leftMax - height[l]; - } else { - r -= 1; - rightMax = Math.max(rightMax, height[r]); - res += rightMax - height[r]; + while (l < r) { + if (leftMax < rightMax) { + l += 1; + leftMax = Math.max(leftMax, height[l]); + res += leftMax - height[l]; + } else { + r -= 1; + rightMax = Math.max(rightMax, height[r]); + res += rightMax - height[r]; + } } - } - return res; + return res; } diff --git a/typescript/43-Multiply-Strings.ts b/typescript/43-Multiply-Strings.ts index 40514b542..35f171121 100644 --- a/typescript/43-Multiply-Strings.ts +++ b/typescript/43-Multiply-Strings.ts @@ -1,21 +1,22 @@ function multiply(num1: string, num2: string): string { - if (num1 === '0' || num2 === '0') { - return '0'; - } + if (num1 === '0' || num2 === '0') { + return '0'; + } - let maxLength: number = num1.length + num2.length; - let result: Array = Array(maxLength).fill(0); - for (let i = num2.length - 1; i >= 0; i--) { - let idx = maxLength - (num2.length - i); + let maxLength: number = num1.length + num2.length; + let result: Array = Array(maxLength).fill(0); + for (let i = num2.length - 1; i >= 0; i--) { + let idx = maxLength - (num2.length - i); - for (let j = num1.length - 1; j >= 0; j--) { - const product = - result[idx] + parseInt(num1.charAt(j)) * parseInt(num2.charAt(i)); - result[idx] = Math.floor(product % 10); - result[idx - 1] = Math.floor(product / 10) + result[idx - 1]; - idx--; + for (let j = num1.length - 1; j >= 0; j--) { + const product = + result[idx] + + parseInt(num1.charAt(j)) * parseInt(num2.charAt(i)); + result[idx] = Math.floor(product % 10); + result[idx - 1] = Math.floor(product / 10) + result[idx - 1]; + idx--; + } } - } - if (result[0] === 0) return result.slice(1).join(''); - else return result.join(''); + if (result[0] === 0) return result.slice(1).join(''); + else return result.join(''); } diff --git a/typescript/46-Permutations.ts b/typescript/46-Permutations.ts index 319a5b17c..bf2416b75 100644 --- a/typescript/46-Permutations.ts +++ b/typescript/46-Permutations.ts @@ -1,25 +1,25 @@ function permute(nums: number[]): number[][] { - const res: number[][] = []; + const res: number[][] = []; - if (nums.length === 1) { - return [nums.slice()]; - } + if (nums.length === 1) { + return [nums.slice()]; + } - for (const i of nums) { - let n = nums.shift()!; + for (const i of nums) { + let n = nums.shift()!; - let perms = permute(nums); + let perms = permute(nums); - for (const perm of perms) { - perm.push(n); - } + for (const perm of perms) { + perm.push(n); + } - perms.forEach((perm) => { - res.push(perm); - }); + perms.forEach((perm) => { + res.push(perm); + }); - nums.push(n); - } + nums.push(n); + } - return res; + return res; } diff --git a/typescript/48-Rotate-Image.ts b/typescript/48-Rotate-Image.ts index c6b46d522..744100d5f 100644 --- a/typescript/48-Rotate-Image.ts +++ b/typescript/48-Rotate-Image.ts @@ -1,20 +1,20 @@ function rotate(matrix: number[][]): void { - let l = 0; - let r = matrix.length - 1; + let l = 0; + let r = matrix.length - 1; - while (l < r) { - for (let i = 0; i < r - l; i++) { - let top = l; - let bottom = r; + while (l < r) { + for (let i = 0; i < r - l; i++) { + let top = l; + let bottom = r; - let topLeft = matrix[top][l + i]; + let topLeft = matrix[top][l + i]; - matrix[top][l + i] = matrix[bottom - i][l]; - matrix[bottom - i][l] = matrix[bottom][r - i]; - matrix[bottom][r - i] = matrix[top + i][r]; - matrix[top + i][r] = topLeft; + matrix[top][l + i] = matrix[bottom - i][l]; + matrix[bottom - i][l] = matrix[bottom][r - i]; + matrix[bottom][r - i] = matrix[top + i][r]; + matrix[top + i][r] = topLeft; + } + r -= 1; + l += 1; } - r -= 1; - l += 1; - } } diff --git a/typescript/49-Group-Anagrams.ts b/typescript/49-Group-Anagrams.ts index 839fbd79e..22e287c6d 100644 --- a/typescript/49-Group-Anagrams.ts +++ b/typescript/49-Group-Anagrams.ts @@ -1,46 +1,46 @@ function groupAnagrams(strs: string[]): string[][] { - const hash: { - [key: string]: string[]; - } = {}; - - strs.forEach((item, index) => { - let doesExist = false; - Object.keys(hash).forEach((key) => { - if (isAnagram(item, key)) { - hash[key].push(item); - doesExist = true; - } + const hash: { + [key: string]: string[]; + } = {}; + + strs.forEach((item, index) => { + let doesExist = false; + Object.keys(hash).forEach((key) => { + if (isAnagram(item, key)) { + hash[key].push(item); + doesExist = true; + } + }); + + if (!doesExist) { + hash[item] = [item]; + } }); - if (!doesExist) { - hash[item] = [item]; - } - }); - - console.log(hash); + console.log(hash); - return [...Object.keys(hash).map((k) => hash[k])]; + return [...Object.keys(hash).map((k) => hash[k])]; } console.log(groupAnagrams(['eat', 'ate', 'dog', 'pog'])); function isAnagram(s: string, t: string) { - if (s.length !== t.length) return false; + if (s.length !== t.length) return false; - var first: Array = s.split(''); - const second = t.split(''); + var first: Array = s.split(''); + const second = t.split(''); - for (let i = 0; i < second.length; i++) { - const element = second[i]; + for (let i = 0; i < second.length; i++) { + const element = second[i]; - let found = first.indexOf(element); + let found = first.indexOf(element); - if (found !== -1) { - first[found] = null; - } else { - return false; + if (found !== -1) { + first[found] = null; + } else { + return false; + } } - } - return true; + return true; } diff --git a/typescript/5-Longest-Palindromic-Substring.ts b/typescript/5-Longest-Palindromic-Substring.ts index 48aa360bb..f81fbd4ab 100644 --- a/typescript/5-Longest-Palindromic-Substring.ts +++ b/typescript/5-Longest-Palindromic-Substring.ts @@ -1,34 +1,34 @@ function longestPalindrome(s: string): string { - let res = ''; - let resLen = 0; + let res = ''; + let resLen = 0; - for (let i = 0; i < s.length; i++) { - let l = i; - let r = i; + for (let i = 0; i < s.length; i++) { + let l = i; + let r = i; - while (l >= 0 && r < s.length && s[l] === s[r]) { - if (r - l + 1 > resLen) { - res = s.slice(l, r + 1); - resLen = r - l + 1; - } + while (l >= 0 && r < s.length && s[l] === s[r]) { + if (r - l + 1 > resLen) { + res = s.slice(l, r + 1); + resLen = r - l + 1; + } - l -= 1; - r += 1; - } + l -= 1; + r += 1; + } - l = i; - r = i + 1; + l = i; + r = i + 1; - while (l >= 0 && r < s.length && s[l] === s[r]) { - if (r - l + 1 > resLen) { - res = s.slice(l, r + 1); - resLen = r - l + 1; - } + while (l >= 0 && r < s.length && s[l] === s[r]) { + if (r - l + 1 > resLen) { + res = s.slice(l, r + 1); + resLen = r - l + 1; + } - l -= 1; - r += 1; + l -= 1; + r += 1; + } } - } - return res; + return res; } diff --git a/typescript/50-Pow.ts b/typescript/50-Pow.ts index 75415b3b1..73b76b94c 100644 --- a/typescript/50-Pow.ts +++ b/typescript/50-Pow.ts @@ -1,12 +1,12 @@ function myPow(x: number, n: number): number { - function helper(x: number, n: number): number { - if (x == 0) return 0; - if (n == 0) return 1; + function helper(x: number, n: number): number { + if (x == 0) return 0; + if (n == 0) return 1; - let res = helper(x * x, Math.floor(n / 2)); - return n % 2 ? x * res : res; - } + let res = helper(x * x, Math.floor(n / 2)); + return n % 2 ? x * res : res; + } - let res = helper(x, Math.abs(n)); - return n >= 0 ? res : 1 / res; + let res = helper(x, Math.abs(n)); + return n >= 0 ? res : 1 / res; } diff --git a/typescript/53-Maximum-Subarray.ts b/typescript/53-Maximum-Subarray.ts index 4a93edc4a..d10eccebb 100644 --- a/typescript/53-Maximum-Subarray.ts +++ b/typescript/53-Maximum-Subarray.ts @@ -1,14 +1,14 @@ function maxSubArray(nums: number[]): number { - let maxSub = nums[0]; - let curSum = 0; + let maxSub = nums[0]; + let curSum = 0; - for (const n of nums) { - if (curSum < 0) { - curSum = 0; + for (const n of nums) { + if (curSum < 0) { + curSum = 0; + } + curSum += n; + maxSub = Math.max(maxSub, curSum); } - curSum += n; - maxSub = Math.max(maxSub, curSum); - } - return maxSub; + return maxSub; } diff --git a/typescript/54-Spiral-Matrix.ts b/typescript/54-Spiral-Matrix.ts index c73a031f9..d15a02e2c 100644 --- a/typescript/54-Spiral-Matrix.ts +++ b/typescript/54-Spiral-Matrix.ts @@ -1,39 +1,39 @@ function spiralOrder(matrix: number[][]): number[] { - const res: number[] = []; - let left = 0; - let right = matrix[0].length; - let top = 0; - let bottom = matrix.length; + const res: number[] = []; + let left = 0; + let right = matrix[0].length; + let top = 0; + let bottom = matrix.length; - while (left < right && top < bottom) { - // get every i in the top row - for (let i = left; i < right; i++) { - res.push(matrix[top][i]); - } - top += 1; + while (left < right && top < bottom) { + // get every i in the top row + for (let i = left; i < right; i++) { + res.push(matrix[top][i]); + } + top += 1; - // get every i in the right column - for (let i = top; i < bottom; i++) { - res.push(matrix[i][right - 1]); - } - right -= 1; + // get every i in the right column + for (let i = top; i < bottom; i++) { + res.push(matrix[i][right - 1]); + } + right -= 1; - if (!(left < right && top < bottom)) { - break; - } + if (!(left < right && top < bottom)) { + break; + } - // get ever i in the bottom row - for (let i = right - 1; i > left - 1; i--) { - res.push(matrix[bottom - 1][i]); - } - bottom -= 1; + // get ever i in the bottom row + for (let i = right - 1; i > left - 1; i--) { + res.push(matrix[bottom - 1][i]); + } + bottom -= 1; - // get evet i in the left column - for (let i = bottom - 1; i > top - 1; i--) { - res.push(matrix[i][left]); + // get evet i in the left column + for (let i = bottom - 1; i > top - 1; i--) { + res.push(matrix[i][left]); + } + left += 1; } - left += 1; - } - return res; + return res; } diff --git a/typescript/543-Diameter-of-Binary-Tree.ts b/typescript/543-Diameter-of-Binary-Tree.ts index cafb501d6..b40c185e1 100644 --- a/typescript/543-Diameter-of-Binary-Tree.ts +++ b/typescript/543-Diameter-of-Binary-Tree.ts @@ -13,18 +13,18 @@ */ function diameterOfBinaryTree(root: TreeNode | null): number { - let res = [0]; + let res = [0]; - function dfs(root: TreeNode | null): number { - if (!root) return -1; - let left = dfs(root.left); - let right = dfs(root.right); + function dfs(root: TreeNode | null): number { + if (!root) return -1; + let left = dfs(root.left); + let right = dfs(root.right); - res[0] = Math.max(res[0], 2 + left + right); + res[0] = Math.max(res[0], 2 + left + right); - return 1 + Math.max(left, right); - } + return 1 + Math.max(left, right); + } - dfs(root); - return res[0]; + dfs(root); + return res[0]; } diff --git a/typescript/567-Permutation-in-String.ts b/typescript/567-Permutation-in-String.ts index b43c85e39..e715e6b8a 100644 --- a/typescript/567-Permutation-in-String.ts +++ b/typescript/567-Permutation-in-String.ts @@ -1,42 +1,42 @@ function checkInclusion(s1: string, s2: string): boolean { - if (s1.length > s2.length) return false; + if (s1.length > s2.length) return false; - const s1Count = Array(26).fill(0); - const s2Count = Array(26).fill(0); + const s1Count = Array(26).fill(0); + const s2Count = Array(26).fill(0); - for (let i = 0; i < s1.length; i++) { - s1Count[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; - s2Count[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; - } + for (let i = 0; i < s1.length; i++) { + s1Count[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; + s2Count[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; + } - let matches = 0; - for (let i = 0; i < 26; i++) { - if (s1Count[i] == s2Count[i]) { - matches += 1; + let matches = 0; + for (let i = 0; i < 26; i++) { + if (s1Count[i] == s2Count[i]) { + matches += 1; + } } - } - let l = 0; - for (let r = s1.length; r < s2.length; r++) { - if (matches == 26) return true; + let l = 0; + for (let r = s1.length; r < s2.length; r++) { + if (matches == 26) return true; - let index = s2[r].charCodeAt(0) - 'a'.charCodeAt(0); - s2Count[index] += 1; - if (s1Count[index] == s2Count[index]) { - matches += 1; - } else if (s1Count[index] + 1 == s2Count[index]) { - matches -= 1; - } + let index = s2[r].charCodeAt(0) - 'a'.charCodeAt(0); + s2Count[index] += 1; + if (s1Count[index] == s2Count[index]) { + matches += 1; + } else if (s1Count[index] + 1 == s2Count[index]) { + matches -= 1; + } - let index2 = s2[l].charCodeAt(0) - 'a'.charCodeAt(0); - s2Count[index2] -= 1; - if (s1Count[index2] == s2Count[index2]) { - matches += 1; - } else if (s1Count[index2] - 1 == s2Count[index2]) { - matches -= 1; + let index2 = s2[l].charCodeAt(0) - 'a'.charCodeAt(0); + s2Count[index2] -= 1; + if (s1Count[index2] == s2Count[index2]) { + matches += 1; + } else if (s1Count[index2] - 1 == s2Count[index2]) { + matches -= 1; + } + l += 1; } - l += 1; - } - return matches == 26; + return matches == 26; } diff --git a/typescript/572-Subtree-of-Another-Tree.ts b/typescript/572-Subtree-of-Another-Tree.ts index 8021fd450..077956a11 100644 --- a/typescript/572-Subtree-of-Another-Tree.ts +++ b/typescript/572-Subtree-of-Another-Tree.ts @@ -13,30 +13,30 @@ */ function isSubtree(root: TreeNode | null, subRoot: TreeNode | null): boolean { - if (subRoot === null) return true; - if (root === null) return false; + if (subRoot === null) return true; + if (root === null) return false; - if (isSameTree(root, subRoot)) { - return true; - } + if (isSameTree(root, subRoot)) { + return true; + } - let left = isSubtree(root.left, subRoot); - let right = isSubtree(root.right, subRoot); + let left = isSubtree(root.left, subRoot); + let right = isSubtree(root.right, subRoot); - return left || right; + return left || right; } function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { - if (p === null && q === null) return true; + if (p === null && q === null) return true; - if ((p === null && q !== null) || (p !== null && q === null)) return false; + if ((p === null && q !== null) || (p !== null && q === null)) return false; - let leftSame = isSameTree(p.left, q.left); - let rightSame = isSameTree(p.right, q.right); + let leftSame = isSameTree(p.left, q.left); + let rightSame = isSameTree(p.right, q.right); - if (p.val === q.val && leftSame && rightSame) { - return true; - } + if (p.val === q.val && leftSame && rightSame) { + return true; + } - return false; + return false; } diff --git a/typescript/62-Unique-Paths.ts b/typescript/62-Unique-Paths.ts index 753a4eadd..b57848baa 100644 --- a/typescript/62-Unique-Paths.ts +++ b/typescript/62-Unique-Paths.ts @@ -1,15 +1,15 @@ function uniquePaths(m: number, n: number): number { - let row = new Array(n).fill(1); + let row = new Array(n).fill(1); - for (let i = 0; i < m - 1; i++) { - let newRow = new Array(n).fill(1); + for (let i = 0; i < m - 1; i++) { + let newRow = new Array(n).fill(1); - for (let j = n - 2; j > -1; j--) { - newRow[j] = newRow[j + 1] + row[j]; - } + for (let j = n - 2; j > -1; j--) { + newRow[j] = newRow[j + 1] + row[j]; + } - row = newRow; - } + row = newRow; + } - return row[0]; + return row[0]; } diff --git a/typescript/647-Palindromic-Substrings.ts b/typescript/647-Palindromic-Substrings.ts index a4956f49d..994ed1d6f 100644 --- a/typescript/647-Palindromic-Substrings.ts +++ b/typescript/647-Palindromic-Substrings.ts @@ -1,25 +1,25 @@ function countSubstrings(s: string): number { - let res = 0; + let res = 0; - for (let i = 0; i < s.length; i++) { - let l = i; - let r = i; + for (let i = 0; i < s.length; i++) { + let l = i; + let r = i; - while (l >= 0 && r < s.length && s[l] === s[r]) { - res += 1; - l -= 1; - r += 1; - } + while (l >= 0 && r < s.length && s[l] === s[r]) { + res += 1; + l -= 1; + r += 1; + } - l = i; - r = i + 1; + l = i; + r = i + 1; - while (l >= 0 && r < s.length && s[l] === s[r]) { - res += 1; - l -= 1; - r += 1; + while (l >= 0 && r < s.length && s[l] === s[r]) { + res += 1; + l -= 1; + r += 1; + } } - } - return res; + return res; } diff --git a/typescript/66-Plus-One.ts b/typescript/66-Plus-One.ts index 3f7848805..c80377f4d 100644 --- a/typescript/66-Plus-One.ts +++ b/typescript/66-Plus-One.ts @@ -1,6 +1,6 @@ function plusOne(digits: number[]): number[] { - return (BigInt(digits.join('')) + BigInt(1)) - .toString() - .split('') - .map((item) => Number(item)); + return (BigInt(digits.join('')) + BigInt(1)) + .toString() + .split('') + .map((item) => Number(item)); } diff --git a/typescript/7-Reverse-Integer.ts b/typescript/7-Reverse-Integer.ts index 49e2774b0..fbc6ca8a8 100644 --- a/typescript/7-Reverse-Integer.ts +++ b/typescript/7-Reverse-Integer.ts @@ -1,23 +1,23 @@ const reverse = (x: number): number => { - const max: number = 2 ** 31 - 1; - const min: number = -(2 ** 31); + const max: number = 2 ** 31 - 1; + const min: number = -(2 ** 31); - let result: number = 0; - while (x !== 0) { - const digit = x % 10; - x = Math.trunc(x / 10); + let result: number = 0; + while (x !== 0) { + const digit = x % 10; + x = Math.trunc(x / 10); - if (result > max / 10 || (result === max / 10 && digit >= max % 10)) { - return 0; - } else if ( - result < min / 10 || - (result === max / 10 && digit <= min % 10) - ) { - return 0; - } else { - result = result * 10 + digit; + if (result > max / 10 || (result === max / 10 && digit >= max % 10)) { + return 0; + } else if ( + result < min / 10 || + (result === max / 10 && digit <= min % 10) + ) { + return 0; + } else { + result = result * 10 + digit; + } } - } - return result; + return result; }; diff --git a/typescript/70-Climbing-Stairs.ts b/typescript/70-Climbing-Stairs.ts index 72cf633a9..f396c4a35 100644 --- a/typescript/70-Climbing-Stairs.ts +++ b/typescript/70-Climbing-Stairs.ts @@ -1,11 +1,11 @@ function climbStairs(n: number): number { - let one = 1; - let two = 1; + let one = 1; + let two = 1; - for (let i = 0; i < n - 1; i++) { - let temp = one; - one = one + two; - two = temp; - } - return one; + for (let i = 0; i < n - 1; i++) { + let temp = one; + one = one + two; + two = temp; + } + return one; } diff --git a/typescript/704-Binary-Search.ts b/typescript/704-Binary-Search.ts index 8e91b4839..7405a0a5c 100644 --- a/typescript/704-Binary-Search.ts +++ b/typescript/704-Binary-Search.ts @@ -1,17 +1,17 @@ function search(nums: number[], target: number): number { - let l = 0, - r = nums.length - 1; + let l = 0, + r = nums.length - 1; - while (l <= r) { - var m = Math.round((l + r) / 2); - if (nums[m] > target) { - r = m - 1; - } else if (nums[m] < target) { - l = m + 1; - } else { - return m; + while (l <= r) { + var m = Math.round((l + r) / 2); + if (nums[m] > target) { + r = m - 1; + } else if (nums[m] < target) { + l = m + 1; + } else { + return m; + } } - } - return -1; + return -1; } diff --git a/typescript/74-Search-a-2D-Matrix.ts b/typescript/74-Search-a-2D-Matrix.ts index daea00e32..1b372e78f 100644 --- a/typescript/74-Search-a-2D-Matrix.ts +++ b/typescript/74-Search-a-2D-Matrix.ts @@ -1,39 +1,39 @@ function searchMatrix(matrix: number[][], target: number): boolean { - const rows = matrix.length; - const columns = matrix[0].length; + const rows = matrix.length; + const columns = matrix[0].length; - let top = 0; - let bot = rows - 1; + let top = 0; + let bot = rows - 1; - while (top <= bot) { - let row = Math.floor((top + bot) / 2); - if (target > matrix[row][columns - 1]) { - top = row + 1; - } else if (target < matrix[row][0]) { - bot = row - 1; - } else { - break; + while (top <= bot) { + let row = Math.floor((top + bot) / 2); + if (target > matrix[row][columns - 1]) { + top = row + 1; + } else if (target < matrix[row][0]) { + bot = row - 1; + } else { + break; + } } - } - if (top > bot) { - return false; - } + if (top > bot) { + return false; + } - let row = Math.floor((top + bot) / 2); - let l = 0; - let r = columns - 1; + let row = Math.floor((top + bot) / 2); + let l = 0; + let r = columns - 1; - while (l <= r) { - let m = Math.floor((l + r) / 2); - if (target > matrix[row][m]) { - l = m + 1; - } else if (target < matrix[row][m]) { - r = m - 1; - } else { - return true; + while (l <= r) { + let m = Math.floor((l + r) / 2); + if (target > matrix[row][m]) { + l = m + 1; + } else if (target < matrix[row][m]) { + r = m - 1; + } else { + return true; + } } - } - return false; + return false; } diff --git a/typescript/746-Min-Cost-Climbing-Stairs.ts b/typescript/746-Min-Cost-Climbing-Stairs.ts index e221f8b09..6051b7e91 100644 --- a/typescript/746-Min-Cost-Climbing-Stairs.ts +++ b/typescript/746-Min-Cost-Climbing-Stairs.ts @@ -1,9 +1,9 @@ function minCostClimbingStairs(cost: number[]): number { - cost.push(0); + cost.push(0); - for (let i = cost.length - 3; i > -1; i--) { - cost[i] += Math.min(cost[i + 1], cost[i + 2]); - } + for (let i = cost.length - 3; i > -1; i--) { + cost[i] += Math.min(cost[i + 1], cost[i + 2]); + } - return Math.min(cost[0], cost[1]); + return Math.min(cost[0], cost[1]); } diff --git a/typescript/78-Subsets.ts b/typescript/78-Subsets.ts index 6192016eb..d897e01b9 100644 --- a/typescript/78-Subsets.ts +++ b/typescript/78-Subsets.ts @@ -1,20 +1,20 @@ function subsets(nums: number[]): number[][] { - let res: number[][] = []; - let subset: number[] = []; - function dfs(i: number) { - if (i >= nums.length) { - res.push(subset.slice()); - return; - } + let res: number[][] = []; + let subset: number[] = []; + function dfs(i: number) { + if (i >= nums.length) { + res.push(subset.slice()); + return; + } - subset.push(nums[i]); - dfs(i + 1); + subset.push(nums[i]); + dfs(i + 1); - subset.pop(); - dfs(i + 1); - } + subset.pop(); + dfs(i + 1); + } - dfs(0); + dfs(0); - return res; + return res; } diff --git a/typescript/853-Car-Fleet.ts b/typescript/853-Car-Fleet.ts index d5af3ff7b..292e0d11e 100644 --- a/typescript/853-Car-Fleet.ts +++ b/typescript/853-Car-Fleet.ts @@ -1,25 +1,25 @@ function carFleet(target: number, position: number[], speed: number[]): number { - const combined = position - .map((item, index) => { - return [item, speed[index]]; - }) - .sort((a, b) => a[0] - b[0]); + const combined = position + .map((item, index) => { + return [item, speed[index]]; + }) + .sort((a, b) => a[0] - b[0]); - const stack: number[] = []; + const stack: number[] = []; - for (let i = combined.length - 1; i > -1; i--) { - const p = combined[i][0]; - const s = combined[i][1]; + for (let i = combined.length - 1; i > -1; i--) { + const p = combined[i][0]; + const s = combined[i][1]; - stack.push((target - p) / s); + stack.push((target - p) / s); - if ( - stack.length >= 2 && - stack[stack.length - 1] <= stack[stack.length - 2] - ) { - stack.pop(); + if ( + stack.length >= 2 && + stack[stack.length - 1] <= stack[stack.length - 2] + ) { + stack.pop(); + } } - } - return stack.length; + return stack.length; } diff --git a/typescript/875-Koko-Eating-Bananas.ts b/typescript/875-Koko-Eating-Bananas.ts index 24babca4c..f8242d4c9 100644 --- a/typescript/875-Koko-Eating-Bananas.ts +++ b/typescript/875-Koko-Eating-Bananas.ts @@ -1,21 +1,21 @@ function minEatingSpeed(piles: number[], h: number): number { - let l = 1; - let r = Math.max(...piles); - let res = r; + let l = 1; + let r = Math.max(...piles); + let res = r; - while (l <= r) { - let k = Math.floor((l + r) / 2); - let hours = 0; - for (const p of piles) { - hours += Math.ceil(p / k); + while (l <= r) { + let k = Math.floor((l + r) / 2); + let hours = 0; + for (const p of piles) { + hours += Math.ceil(p / k); + } + if (hours <= h) { + res = Math.min(res, k); + r = k - 1; + } else { + l = k + 1; + } } - if (hours <= h) { - res = Math.min(res, k); - r = k - 1; - } else { - l = k + 1; - } - } - return res; + return res; } diff --git a/typescript/9-Palindrome-Number.ts b/typescript/9-Palindrome-Number.ts index e64dcb22f..808ef3dca 100644 --- a/typescript/9-Palindrome-Number.ts +++ b/typescript/9-Palindrome-Number.ts @@ -1,13 +1,13 @@ var isPalindrome = (x: number) => { - // Creates array from int characters - // 121 -> [1,2,1] - let arr = Array.from(String(x), Number); + // Creates array from int characters + // 121 -> [1,2,1] + let arr = Array.from(String(x), Number); - // Uses two pointer - for (let i = 0; i < arr.length; i++) { - if (arr[i] !== arr[arr.length - 1 - i]) { - return false; + // Uses two pointer + for (let i = 0; i < arr.length; i++) { + if (arr[i] !== arr[arr.length - 1 - i]) { + return false; + } } - } - return true; + return true; }; diff --git a/typescript/90-Subsets-II.ts b/typescript/90-Subsets-II.ts index 69f382244..bd898a7ad 100644 --- a/typescript/90-Subsets-II.ts +++ b/typescript/90-Subsets-II.ts @@ -1,26 +1,26 @@ function subsetsWithDup(nums: number[]): number[][] { - let res: number[][] = []; - nums.sort(); + let res: number[][] = []; + nums.sort(); - function backtrack(i: number, subset: number[]) { - if (i == nums.length) { - res.push(subset.slice()); - return; - } + function backtrack(i: number, subset: number[]) { + if (i == nums.length) { + res.push(subset.slice()); + return; + } - subset.push(nums[i]); - backtrack(i + 1, subset); + subset.push(nums[i]); + backtrack(i + 1, subset); - subset.pop(); + subset.pop(); - while (i + 1 < nums.length && nums[i] == nums[i + 1]) { - i += 1; - } + while (i + 1 < nums.length && nums[i] == nums[i + 1]) { + i += 1; + } - backtrack(i + 1, subset); - } + backtrack(i + 1, subset); + } - backtrack(0, []); + backtrack(0, []); - return res; + return res; } diff --git a/typescript/91-Decode-Ways.ts b/typescript/91-Decode-Ways.ts index 358385bbf..4e59fcf02 100644 --- a/typescript/91-Decode-Ways.ts +++ b/typescript/91-Decode-Ways.ts @@ -1,20 +1,20 @@ function numDecodings(s: string): number { - let dp = { - [s.length]: 1, - }; + let dp = { + [s.length]: 1, + }; - for (let i = s.length - 1; i > -1; i--) { - if (s[i] == '0') { - dp[i] = 0; - } else { - dp[i] = dp[i + 1]; + for (let i = s.length - 1; i > -1; i--) { + if (s[i] == '0') { + dp[i] = 0; + } else { + dp[i] = dp[i + 1]; + } + if ( + i + 1 < s.length && + (s[i] == '1' || (s[i] == '2' && '0123456'.includes(s[i + 1]))) + ) { + dp[i] += dp[i + 2]; + } } - if ( - i + 1 < s.length && - (s[i] == '1' || (s[i] == '2' && '0123456'.includes(s[i + 1]))) - ) { - dp[i] += dp[i + 2]; - } - } - return dp[0]; + return dp[0]; }