├── .gitignore
├── Collections_JAVA.png
├── README.md
├── Sort_comparison.png
└── src
├── AAAAAAA_Testing.java
├── AddDigits.java
├── AddTwoNumber.java
├── AllNodesDistanceKInBinaryTree.java
├── AllPathsFromSourceToTarget.java
├── ArithmeticSlices.java
├── ArrayPartition.java
├── AverageLevelsBinaryTree.java
├── BalancedBinaryTree.java
├── BaseballGame.java
├── BattleshipsInBoard.java
├── BeautifulArrangement.java
├── BestTimeBuyAndSellStock.java
├── BestTimeToBuyAndSellStockWithTransactionFee.java
├── BinaryNumberWithAlternatingBits.java
├── BinaryTreeInorderTraversal.java
├── BinaryTreePaths.java
├── BinaryTreePruning.java
├── BinaryTreeTilt.java
├── BinaryTreeZigzagLevelOrderTraversal.java
├── ClimbStairs.java
├── CombinationSum.java
├── Combinations.java
├── ComplexNumMultiplication.java
├── Complexity
├── Complexity_backup
├── ConstructStringFromBTree.java
├── Contest104
└── Solution.java
├── Contest105
├── Solution.java
└── TreeNode.java
├── Contest92
├── PrimePalindrome.java
├── ShortestPathAllKeys.java
├── SmallestSubstree.java
└── TransposeMatrix.java
├── Contest93
├── AdvantageShuffle.java
├── BinaryGap.java
├── MinRefuelStops.java
└── ReorderedPowerOf2.java
├── Contest94
├── KokoEatingBananas.java
├── LeafSimilar.java
├── LenLongestFibSubseq.java
└── RobotSim.java
├── ConvertBSTToGreaterTree.java
├── ConvertSortedArrayToBinarySearchTree.java
├── ConvertSortedListToBST.java
├── CountNumbersWithUniqueDigits.java
├── CountSmaller.java
├── CountingBits.java
├── CustomSortingString.java
├── DailyTemperatures.java
├── DesignLinkedList.java
├── DetectCapital.java
├── DiameterOfBinaryTree.java
├── DistributeCandies.java
├── EmployeeImportance.java
├── EncodeAndDecodeTinyurl.java
├── FindAllDuplicatesInArray.java
├── FindBottomLeftTreeValue.java
├── FindLargestValueEachTreeRow.java
├── FindLongestChain.java
├── FindModeInBST.java
├── FindNumberOfLIS.java
├── FindTheDifference.java
├── FizzBuzz.java
├── FizzBuzzMultiThreading.java
├── FizzBuzzThread.java
├── FlippingAnImage.java
├── FourSum.java
├── GenerateParentheses.java
├── GoatLatin.java
├── HammingDistance.java
├── HouseRobber.java
├── ImplementStrStr.java
├── IncreasingTriplet.java
├── IntegerBreak.java
├── InvertBinaryTree.java
├── IsSubtree.java
├── IslandPerimeter.java
├── JewelsAndStones.java
├── JudgeRouteCircle.java
├── KeyboardRow.java
├── KeysAndRooms.java
├── KickStart_Oct
├── A-large-practice.in
├── A.java
├── A_old.java
├── B-small-practice.in
├── B-small.in
├── B.java
└── FileIO.java
├── LargestTriangleArea.java
├── LetterCasePermutation.java
├── LevelOrderBottom.java
├── ListNode.java
├── LongestContinuousIncreasingSubsequence.java
├── LongestIncreasingSubsequence.java
├── LongestSubstring.java
├── LongestUncommonSubsequence1.java
├── LongestUnivaluePath.java
├── LowestCommonAncestor.java
├── MajorityElement.java
├── MaxAreaOfIsland.java
├── MaxBinaryTree.java
├── MaxConsecutiveOnes.java
├── MaxIncreaseKeepCitySkyline.java
├── MaxProfit.java
├── MaxSubArray.java
├── MaximumDepthBinaryTree.java
├── MedianFinder.java
├── Merge2BTree.java
├── MinCostClimbingStairs.java
├── MinDepth.java
├── MinimumDeleteSum.java
├── MinimumMovesToEqualArray.java
├── MinimumMovesToEqualArrayII.java
├── MostFrequentSubtreeSum.java
├── MoveZeroes.java
├── MyCircularDeque.java
├── MyCircularQueue2.java
├── NQueens.java
├── NextGreaterElementI.java
├── NimGame.java
├── NonDecreasingArray.java
├── NumArray.java
├── NumOfLineToWriteString.java
├── NumberComplement.java
├── NumberThread.java
├── OptimalDivision.java
├── PalindromicSubstrings.java
├── PartitionLabels.java
├── PathSum.java
├── PathSumIII.java
├── PeakIndexInMountain.java
├── Permutations.java
├── PopulatingNextRightPointers.java
├── PopulatingNextRightPointers2.java
├── PreorderTraversal.java
├── PrimeNumberOfSetBits.java
├── QueueReconstructionByHeight.java
├── RangeSumQueryMutable.java
├── RecoverBinarySearchTree.java
├── ReshapMatrix.java
├── ReverseBits.java
├── ReverseString.java
├── ReverseWordsInString.java
├── SameTree.java
├── ScoreOfParentheses.java
├── Search2DMatrix.java
├── SearchBST.java
├── SecondMinNodeInBTree.java
├── SelfDividingNum.java
├── ShortestDistanceToCharacter.java
├── SingleElementInSortedArray.java
├── SingleNumber.java
├── SingleNumberII.java
├── SingleNumberIII.java
├── Solution.java
├── SortCharactersByFrequency.java
├── StringToIntegerAtoi.java
├── SubdomainVisitCount.java
├── Subsets.java
├── SubsetsII.java
├── SudokuSolver.java
├── SumOfDistancesInTree.java
├── SumOfLeftLeaves.java
├── SymmetricTree.java
├── TaskScheduler.java
├── ToLowerCase.java
├── ToeplitzMatrix.java
├── TreeNode.java
├── TrimBinarySearchTree.java
├── TwoSum.java
├── TwoSumIVInputBST.java
├── UniqueBinarySearchTrees.java
├── UniqueBinarySearchTreesII.java
├── UniqueMorseCodeWords.java
├── ValidSudoku.java
├── constructBTFromPreorderPostorder.java
├── kthLargestElement.java
├── longestPalindromeSubString.java
└── testHashSet.java
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled class file
2 | *.class
3 |
4 | # Log file
5 | *.log
6 |
7 | # BlueJ files
8 | *.ctxt
9 |
10 | # Mobile Tools for Java (J2ME)
11 | .mtj.tmp/
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.nar
17 | *.ear
18 | *.zip
19 | *.tar.gz
20 | *.rar
21 |
22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
23 | hs_err_pid*
24 |
--------------------------------------------------------------------------------
/Collections_JAVA.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trunghieu-tran/LeetCode-Solutions-And-Data-Structure-Analysis/88ddc5c250f5bfbf273c484076d788e06146260f/Collections_JAVA.png
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode Solutions in Java #
2 | A collection of LeetCode novel solutions that is implemented in Java. It would support you to solve the problems from easy to hard by the simplest ways.
3 |
4 | ## Solutions LeeCode ##
5 | | # | Problem | Difficulty | Source code | Solution |
6 | |---| ------- | ---------- | ----------- | -------- |
7 | | 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | Medium | [Java](https://github.com/saodem74/LeetCode-Solutions-Java/blob/master/src/TwoSum.java) | 1. Hash O(n) and O(n) space.
2. Sort and search with two points O(n) and O(1) space. |
8 | | 2 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | Medium | [Java](https://github.com/saodem74/LeetCode-Solutions-Java/blob/master/src/AddTwoNumber.java) | Take care of the carry from lower digit. |
9 | |---| To-be-updated soon | ---------- | ----------- | -------- |
10 |
11 | ## Big O performance ##
12 | Below are the Big O performance of common functions of different Java Collections.
13 |
14 |
15 | List | Add | Remove | Get | Contains | Next | Data Structure
16 | ---------------------|------|--------|------|----------|------|---------------
17 | ArrayList | O(1) | O(n) | O(1) | O(n) | O(1) | Array
18 | LinkedList | O(1) | O(1) | O(n) | O(n) | O(1) | Linked List
19 |
20 |
21 |
22 | Set | Add | Remove | Contains | Next | Size | Data Structure
23 | ----------------------|----------|----------|----------|----------|------|-------------------------
24 | HashSet | O(1) | O(1) | O(1) | O(h/n) | O(1) | Hash Table
25 | LinkedHashSet | O(1) | O(1) | O(1) | O(1) | O(1) | Hash Table + Linked List
26 | EnumSet | O(1) | O(1) | O(1) | O(1) | O(1) | Bit Vector
27 | TreeSet | O(log n) | O(log n) | O(log n) | O(log n) | O(1) | Red-black tree
28 | ConcurrentSkipListSet | O(log n) | O(log n) | O(log n) | O(1) | O(n) | Skip List
29 |
30 | * Note: h is the table capacity
31 |
32 |
33 | Queue | Offer | Peak | Poll | Remove | Size | Data Structure
34 | ------------------------|----------|------|----------|--------|------|---------------
35 | PriorityQueue | O(log n) | O(1) | O(log n) | O(n) | O(1) | Priority Heap
36 | LinkedList | O(1) | O(1) | O(1) | O(1) | O(1) | Array
37 | ArrayDequeue | O(1) | O(1) | O(1) | O(n) | O(1) | Linked List
38 | ConcurrentLinkedQueue | O(1) | O(1) | O(1) | O(n) | O(n) | Linked List
39 | ArrayBlockingQueue | O(1) | O(1) | O(1) | O(n) | O(1) | Array
40 | PriorirityBlockingQueue | O(log n) | O(1) | O(log n) | O(n) | O(1) | Priority Heap
41 | SynchronousQueue | O(1) | O(1) | O(1) | O(n) | O(1) | None!
42 | DelayQueue | O(log n) | O(1) | O(log n) | O(n) | O(1) | Priority Heap
43 | LinkedBlockingQueue | O(1) | O(1) | O(1) | O(n) | O(1) | Linked List
44 |
45 |
46 |
47 | Map | Get | ContainsKey | Next | Data Structure
48 | ----------------------|----------|-------------|----------|-------------------------
49 | HashMap | O(1) | O(1) | O(h / n) | Hash Table
50 | LinkedHashMap | O(1) | O(1) | O(1) | Hash Table + Linked List
51 | IdentityHashMap | O(1) | O(1) | O(h / n) | Array
52 | WeakHashMap | O(1) | O(1) | O(h / n) | Hash Table
53 | EnumMap | O(1) | O(1) | O(1) | Array
54 | TreeMap | O(log n) | O(log n) | O(log n) | Red-black tree
55 | ConcurrentHashMap | O(1) | O(1) | O(h / n) | Hash Tables
56 | ConcurrentSkipListMap | O(log n) | O(log n) | O(1) | Skip List
57 |
58 | ## JAVA Collections Framework ##
59 |
60 |
61 |
62 | Source: Suryaprakash R.
63 |
64 | ## Sort Algorithm Comparison ##
65 |
66 |
67 |
68 | Source: MCN Professionals
69 | ## Contributors ##
70 | Hieu Tran (trantrunghieu7492@gmail.com)
71 |
--------------------------------------------------------------------------------
/Sort_comparison.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trunghieu-tran/LeetCode-Solutions-And-Data-Structure-Analysis/88ddc5c250f5bfbf273c484076d788e06146260f/Sort_comparison.png
--------------------------------------------------------------------------------
/src/AAAAAAA_Testing.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 9/30/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class AAAAAAA_Testing {
8 | public static void main(String args[]) {
9 | System.out.println(~0 << 2);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/AddDigits.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/3/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class AddDigits {
8 | public int addDigits(int num) {
9 | return 1 + (num - 1) % 9;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/AddTwoNumber.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/25/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class AddTwoNumber {
8 |
9 | public class ListNode {
10 | int val;
11 | ListNode next;
12 | ListNode(int x) { val = x; }
13 | }
14 |
15 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
16 | ListNode result = new ListNode(0);
17 | ListNode curr = result;
18 | int carry = 0;
19 | while (true) {
20 | int tmp = l1.val + l2.val + carry;
21 | carry = tmp / 10;
22 | curr.val = tmp % 10;
23 |
24 | if (l1.next == null || l2.next == null) break;
25 | l1 = l1.next;
26 | l2 = l2.next;
27 | ListNode newNode = new ListNode(0);
28 | curr.next = newNode;
29 | curr = newNode;
30 | }
31 | while (l1.next != null) {
32 | l1 = l1.next;
33 | int tmp = l1.val + carry;
34 | carry = tmp / 10;
35 | ListNode newNode = new ListNode(tmp % 10);
36 | curr.next = newNode;
37 | curr = newNode;
38 | }
39 |
40 | while (l2.next != null) {
41 | l2 = l2.next;
42 | int tmp = l2.val + carry;
43 | carry = tmp / 10;
44 | ListNode newNode = new ListNode(tmp % 10);
45 | curr.next = newNode;
46 | curr = newNode;
47 | }
48 | if (carry > 0) {
49 | ListNode newNode = new ListNode(carry);
50 | curr.next = newNode;
51 | }
52 | return result;
53 | }
54 |
55 | public static void main(String[] args) {
56 | int c = 97;
57 | System.out.println((char) c);
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/AllNodesDistanceKInBinaryTree.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.HashMap;
3 | import java.util.List;
4 | import java.util.Map;
5 |
6 | /**
7 | * @author Harry Tran on 7/11/18.
8 | * @project Leetcode
9 | * @email trunghieu.tran@utdallas.edu
10 | * @organization UTDallas
11 | */
12 | public class AllNodesDistanceKInBinaryTree {
13 |
14 | Map parents = new HashMap<>();
15 |
16 | private void traverse(TreeNode n) {
17 | if (n.left != null) {
18 | parents.put(n.left.val, n);
19 | traverse(n.left);
20 | }
21 |
22 | if (n.right != null) {
23 | parents.put(n.right.val, n);
24 | traverse(n.right);
25 | }
26 | }
27 |
28 | private void finding(TreeNode n, int last, List res, int K) {
29 | System.out.println(n.val);
30 | if (K == 0) {
31 | res.add(n.val);
32 | return;
33 | }
34 | // solving its children
35 | if (n.left != null && last != n.left.val) {
36 | finding(n.left, n.val, res, K - 1);
37 | }
38 | if (n.right != null && last != n.right.val) {
39 | finding(n.right, n.val, res, K - 1);
40 | }
41 | // Parents
42 | TreeNode p = parents.getOrDefault(n.val, null);
43 | if (p != null && last != p.val) {
44 | finding(p, n.val, res, K - 1);
45 | }
46 | }
47 |
48 | public List distanceK(TreeNode root, TreeNode target, int K) {
49 | List res = new ArrayList<>();
50 | traverse(root);
51 | finding(target, -1, res, K);
52 | return res;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/AllPathsFromSourceToTarget.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | /**
4 | * @author Harry Tran on 6/30/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class AllPathsFromSourceToTarget {
10 | private void dfs(int node, int[][] graph, Stack trace,
11 | List> result) {
12 | if (node == graph.length - 1) {
13 | result.add(new ArrayList<>(trace));
14 | return;
15 | }
16 |
17 | for (int i = 0; i < graph[node].length; ++i) {
18 | int nextNode = graph[node][i];
19 |
20 | trace.push(nextNode);
21 |
22 | dfs(nextNode, graph, trace, result);
23 |
24 | trace.pop();
25 | }
26 |
27 | }
28 | public List> allPathsSourceTarget(int[][] graph) {
29 | List> res = new ArrayList<>();
30 | Stack trace = new Stack<>();
31 |
32 | trace.push(0);
33 | dfs(0, graph, trace, res);
34 | return res;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/ArithmeticSlices.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/4/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ArithmeticSlices {
8 | public int numberOfArithmeticSlices(int[] A) {
9 | int len = A.length;
10 | int i = 0;
11 | int res = 0;
12 |
13 | while (i < len - 2) {
14 | int j = i + 1;
15 | int dis = A[j] - A[i];
16 |
17 | while (j < len && A[j] - A[j - 1] == dis) ++j;
18 |
19 | int tmp = j - i;
20 | if (tmp >= 3) {
21 | int n = tmp - 2;
22 | res += (n + 1) * n / 2;
23 | }
24 | i = j - 1;
25 | }
26 | return res;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/ArrayPartition.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | /**
3 | * @author Harry Tran on 6/29/18.
4 | * @project Leetcode
5 | * @email trunghieu.tran@utdallas.edu
6 | * @organization UTDallas
7 | */
8 | public class ArrayPartition {
9 | public int arrayPairSum(int[] nums) {
10 | int res = 0;
11 | Arrays.sort(nums);
12 | for (int i = 0; i < nums.length; i+=2) {
13 | res += nums[i];
14 | }
15 | return res;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/AverageLevelsBinaryTree.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.HashMap;
3 | import java.util.List;
4 |
5 | /**
6 | * @author Harry Tran on 7/1/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class AverageLevelsBinaryTree {
12 | public class TreeNode {
13 | int val;
14 | TreeNode left;
15 | TreeNode right;
16 | TreeNode(int x) { val = x; }
17 | }
18 |
19 | private void dfs(TreeNode node, int level, HashMap countNode, HashMap sumNode) {
20 | countNode.put(level, countNode.getOrDefault(level, 0) + 1);
21 | sumNode.put(level, sumNode.getOrDefault(level, 0L) + (long)node.val);
22 |
23 | if (node.left != null) dfs(node.left, level + 1, countNode, sumNode);
24 | if (node.right != null) dfs(node.right, level + 1, countNode, sumNode);
25 | }
26 |
27 | public List averageOfLevels(TreeNode root) {
28 | if (root == null) {
29 | return new ArrayList<>();
30 | }
31 | HashMap countNode = new HashMap<>();
32 | HashMap sumNode = new HashMap<>();
33 | dfs(root, 0, countNode, sumNode);
34 |
35 | List res = new ArrayList<>();
36 | for (int i = 0; i < countNode.size(); ++i)
37 | res.add((double) sumNode.get(i) / (double)countNode.get(i));
38 | return res;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/BalancedBinaryTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/11/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class BalancedBinaryTree {
8 | public class TreeNode {
9 | int val;
10 | TreeNode left;
11 | TreeNode right;
12 | TreeNode(int x) { val = x; }
13 | }
14 |
15 | boolean res = true;
16 |
17 | private int traverse(TreeNode node) {
18 | if (node == null) return 0;
19 | int ileft = traverse(node.left);
20 | int iright = traverse(node.right);
21 | if (Math.abs(ileft - iright) > 1) {
22 | res = false;
23 | }
24 | return Math.max(ileft, iright) + 1;
25 | }
26 |
27 | public boolean isBalanced(TreeNode root) {
28 | int i = traverse(root);
29 | return res;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/BaseballGame.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 |
3 | /**
4 | * @author Harry Tran on 6/30/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class BaseballGame {
10 | public int calPoints(String[] ops) {
11 | ArrayList points = new ArrayList<>();
12 | for (String str : ops) {
13 | int currSize = points.size();
14 | if (str.equals("+")) {
15 | points.add(points.get(currSize - 1) + points.get(currSize - 2));
16 | } else if (str.equals("D")) {
17 | points.add(points.get(currSize - 1) * 2);
18 | } else if (str.equals("C")) {
19 | points.remove(currSize - 1);
20 | } else {
21 | int point = Integer.parseInt(str);
22 | points.add(point);
23 | }
24 | }
25 | int sum = 0;
26 | for (int i : points) sum += i;
27 | return sum;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/BattleshipsInBoard.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/30/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class BattleshipsInBoard {
8 | public int countBattleships(char[][] board) {
9 | int height = board.length;
10 | int width = board[0].length;
11 |
12 | int res = 0;
13 | for (int i = 0; i < height; ++i)
14 | for (int j = 0; j < width; ++j)
15 | if (board[i][j] == 'X') {
16 | boolean ok1 = i == 0 || board[i - 1][j] != 'X';
17 | boolean ok2 = j == 0 || board[i][j - 1] != 'X';
18 | if (ok1 && ok2) ++res;
19 | }
20 | return res;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/BeautifulArrangement.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/5/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class BeautifulArrangement {
8 |
9 | private int getBit(int num, int i) {
10 | return (num >> i) & 1;
11 | }
12 |
13 | private int onBit(int num, int i) {
14 | return num | (1 << i);
15 | }
16 |
17 | int res = 0;
18 |
19 | private void recursion(int pos, int status, int N) {
20 | if (pos == N) {
21 | ++res;
22 | return;
23 | }
24 | for (int i = 0; i < N; ++i)
25 | if (getBit(status, i) == 0) {
26 | int numI = i + 1;
27 | int posI = pos + 1;
28 | if (numI % posI == 0 || posI % numI == 0)
29 | recursion(pos + 1, onBit(status, i), N);
30 | }
31 | }
32 |
33 | public int countArrangement(int N) {
34 | if (N == 0) return 1;
35 | recursion(0, 0, N);
36 | return res;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/BestTimeBuyAndSellStock.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/18/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class BestTimeBuyAndSellStock {
8 | public int maxProfit(int[] prices) {
9 | int n = prices.length;
10 |
11 | if (n <= 1) return 0;
12 | int res = 0;
13 | for (int i = 1; i < n; ++i) {
14 | if (prices[i] > prices[i - 1])
15 | res += prices[i] - prices[i - 1];
16 | }
17 |
18 | return res;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/BestTimeToBuyAndSellStockWithTransactionFee.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/21/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class BestTimeToBuyAndSellStockWithTransactionFee {
8 | public int maxProfit(int[] prices, int fee) {
9 | int len = prices.length;
10 | if (len <= 1) return 0;
11 | int[][] dp = new int[len][2];
12 | // dp[i][0] - best profit with buying 1 stock until i-th
13 | // dp[i][1] - best profit with selling all stock until i-th
14 | // dp[0][0] = dp[0][1] = 0;
15 | dp[1][0] = - Math.min(prices[0], prices[1]);
16 | dp[1][1] = Math.max(0, prices[1] - prices[0] + fee);
17 |
18 | for (int i = 2; i < len; ++i) {
19 | dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
20 | dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);
21 | System.out.println(Integer.toString(dp[i][0]) + " " + Integer.toString(dp[i][1]));
22 | }
23 | return Math.max(dp[len - 1][0], dp[len - 1][1]);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/BinaryNumberWithAlternatingBits.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/1/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class BinaryNumberWithAlternatingBits {
8 | public boolean hasAlternatingBits(int n) {
9 | int x = n ^ (n / 2);
10 | System.out.println(x);
11 | int res = x & (n + 1);
12 | System.out.println(res);
13 | System.out.println(7 & 8);
14 | if (res == 0) return true;
15 | else return false;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/BinaryTreeInorderTraversal.java:
--------------------------------------------------------------------------------
1 | import java.util.LinkedList;
2 | import java.util.List;
3 |
4 | /**
5 | * @author Harry Tran on 7/10/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class BinaryTreeInorderTraversal {
11 | public class TreeNode {
12 | int val;
13 | TreeNode left;
14 | TreeNode right;
15 | TreeNode(int x) { val = x; }
16 | }
17 |
18 | private void traverse(TreeNode node, List res) {
19 | if (node == null) return;
20 | traverse(node.left, res);
21 | res.add(node.val);
22 | traverse(node.right, res);
23 | }
24 |
25 | public List inorderTraversal(TreeNode root) {
26 | List res = new LinkedList<>();
27 | if (root == null) return res;
28 | traverse(root, res);
29 | return res;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/BinaryTreePaths.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | /**
5 | * @author Harry Tran on 7/12/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class BinaryTreePaths {
11 | List res = new ArrayList<>();
12 |
13 | private void traverse(TreeNode n, StringBuilder curr) {
14 | if (n.left != null) {
15 | StringBuilder tmp = new StringBuilder(curr);
16 | tmp.append("->").append(n.left.val);
17 | traverse(n.left, tmp);
18 | }
19 |
20 | if (n.right != null) {
21 | StringBuilder tmp = new StringBuilder(curr);
22 | tmp.append("->").append(n.right.val);
23 | traverse(n.right, tmp);
24 | }
25 | if (n.left == null && n.right == null) {
26 | res.add(curr.toString());
27 | }
28 | }
29 |
30 | public List binaryTreePaths(TreeNode root) {
31 | if (root == null) return res;
32 | StringBuilder curr = new StringBuilder();
33 | curr.append(root.val);
34 | traverse(root, curr);
35 | return res;
36 | }
37 |
38 |
39 |
40 | public static void sss(StringBuilder s) {
41 | if (s.toString().length() >= 10) return;
42 | s.append("abc");
43 | sss(s);
44 | }
45 | public static void main(String[] args) {
46 | StringBuilder tmp = new StringBuilder();
47 | BinaryTreePaths.sss(tmp);
48 | System.out.println(tmp.toString());
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/BinaryTreePruning.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/30/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class BinaryTreePruning {
8 |
9 | public class TreeNode {
10 | int val;
11 | TreeNode left;
12 | TreeNode right;
13 | TreeNode(int x) { val = x; }
14 | }
15 |
16 | private boolean isOK(TreeNode node) {
17 | boolean res = false;
18 | if (node.left != null) {
19 | if (isOK(node.left)) res = true;
20 | else
21 | node.left = null;
22 | }
23 | if (node.right != null) {
24 | if (isOK(node.right)) res = true;
25 | else
26 | node.right = null;
27 | }
28 | res |= (node.val == 1);
29 | return res;
30 | }
31 |
32 | public TreeNode pruneTree(TreeNode root) {
33 | if (isOK(root)) return root;
34 | else return null;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/BinaryTreeTilt.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class BinaryTreeTilt {
8 | int sumTilt = 0;
9 |
10 | private int sum(TreeNode n) {
11 | if (n == null) return 0;
12 | int l = sum(n.left);
13 | int r = sum(n.right);
14 | sumTilt += Math.abs(l - r);
15 | return l + r + n.val;
16 | }
17 | public int findTilt(TreeNode root) {
18 | if (root == null) return 0;
19 | sum(root);
20 | return sumTilt;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/BinaryTreeZigzagLevelOrderTraversal.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.Arrays;
3 | import java.util.Collections;
4 | import java.util.List;
5 |
6 | /**
7 | * @author Harry Tran on 7/12/18.
8 | * @project Leetcode
9 | * @email trunghieu.tran@utdallas.edu
10 | * @organization UTDallas
11 | */
12 | public class BinaryTreeZigzagLevelOrderTraversal {
13 |
14 |
15 |
16 |
17 | public List> zigzagLevelOrder(TreeNode root) {
18 | List> res = new ArrayList<>();
19 | if (root != null) {
20 | List currLevel = new ArrayList<>();
21 | List first = new ArrayList<>();
22 | first.add(root.val);
23 | res.add(first);
24 |
25 | currLevel.add(root);
26 | int level = 0;
27 |
28 | while (currLevel.size() > 0) {
29 | List tmp = new ArrayList<>();
30 | List newCurr = new ArrayList<>();
31 |
32 | for (int i = 0; i < currLevel.size(); ++i) {
33 | TreeNode curr = currLevel.get(i);
34 | if (curr.left != null) {
35 | newCurr.add(curr.left);
36 | tmp.add(curr.left.val);
37 | }
38 | if (curr.right != null) {
39 | newCurr.add(curr.right);
40 | tmp.add(curr.right.val);
41 | }
42 | }
43 |
44 | currLevel = newCurr;
45 |
46 | if (++level % 2 == 1) {
47 | Collections.reverse(tmp);
48 | }
49 | if (tmp.size() > 0) {
50 | res.add(tmp);
51 | }
52 | }
53 | }
54 | return res;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/ClimbStairs.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/17/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ClimbStairs {
8 | public int climbStairs(int n) {
9 | int[] f = new int[n + 2];
10 | f[1] = 1;
11 | f[2] = 2;
12 | for (int i = 3; i <= n; ++i)
13 | f[i] = f[i - 1] + f[i - 2];
14 | return f[n];
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/CombinationSum.java:
--------------------------------------------------------------------------------
1 | import javafx.util.Pair;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * @author Harry Tran on 7/4/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class CombinationSum {
12 |
13 | // Map, List>> map = new HashMap<>();
14 | //
15 | // private List> getCombinationSum(int[] candidates, int target, int pos, ArrayList curr) {
16 | // Pair p = new Pair<>(target, pos);
17 | //
18 | // if (map.containsKey(p)) return map.get(p);
19 | //
20 | //
21 | // for (int i = 0; i <= target / candidates[pos]; ++i) {
22 | // int tmp = i * candidates[pos];
23 | // for (int j = 0; j < i; ++j) curr.add(candidates[pos]);
24 | //
25 | // for (int j = 0; j < i; ++j) curr.remove(curr.size() - 1);
26 | // }
27 | // }
28 | //
29 | // public List> combinationSum(int[] candidates, int target) {
30 | // if (candidates.length == 0) {
31 | // return new ArrayList<>();
32 | // }
33 | // Arrays.sort(candidates);
34 | // return getCombinationSum(candidates, target, 0, new ArrayList<>());
35 | // }
36 |
37 |
38 |
39 | // === ver 1
40 |
41 | List> res = new ArrayList<>();
42 | HashMap, Boolean> map = new HashMap<>();
43 |
44 | private boolean getCombination(int[] candidates, int pos, int target, ArrayList curr) {
45 | if (target == 0) {
46 | res.add(new ArrayList<>(curr));
47 | map.put(new Pair<>(pos, target), true);
48 | return true;
49 | }
50 | if (pos == candidates.length) {
51 | map.put(new Pair<>(pos, target), false);
52 | return false;
53 | }
54 | if (target < candidates[pos]) {
55 | map.put(new Pair<>(pos, target), false);
56 | return false;
57 | }
58 |
59 | boolean solved = false;
60 | for (int i = 0; i <= target / candidates[pos]; ++i) {
61 | int tmp = i * candidates[pos];
62 |
63 | boolean needSolved = map.getOrDefault(new Pair<>(pos + 1, target - tmp), true);
64 | if (!needSolved) continue;
65 |
66 | for (int j = 0; j < i; ++j) curr.add(candidates[pos]);
67 | solved |= getCombination(candidates, pos + 1, target - tmp, curr);
68 | for (int j = 0; j < i; ++j) curr.remove(curr.size() - 1);
69 | }
70 | map.put(new Pair<>(pos, target), solved);
71 | return solved;
72 | }
73 |
74 | public List> combinationSum(int[] candidates, int target) {
75 | if (candidates.length == 0) {
76 | return new ArrayList<>();
77 | }
78 | Arrays.sort(candidates);
79 | getCombination(candidates, 0, target, new ArrayList<>());
80 | return res;
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/Combinations.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.Arrays;
3 | import java.util.Collections;
4 | import java.util.List;
5 | import java.util.stream.Collectors;
6 |
7 | /**
8 | * @author Harry Tran on 7/5/18.
9 | * @project Leetcode
10 | * @email trunghieu.tran@utdallas.edu
11 | * @organization UTDallas
12 | */
13 | public class Combinations {
14 |
15 |
16 | private int getBit(int num, int i) {
17 | return (num >> i) & 1;
18 | }
19 |
20 | private int onBit(int num, int i) {
21 | return num | (1 << i);
22 | }
23 | private void recursion(int pos, int last, int n, int k, int status, int[] curr) {
24 | if (pos == k) {
25 | res.add(Arrays.stream(curr).boxed().collect(Collectors.toList()));
26 | return;
27 | }
28 |
29 | for (int i = last + 1; i <= n; ++i)
30 | if (getBit(status, i - 1) == 0) {
31 | curr[pos] = i;
32 | recursion(pos + 1, i, n, k, onBit(status, i - 1), curr);
33 | }
34 | }
35 |
36 | private void recursion2(int pos, int cnt, int n, int k, int[] curr) {
37 | if (cnt == k) {
38 | // res.add(new ArrayList<>(curr));
39 | res.add(Arrays.stream(curr).boxed().collect(Collectors.toList()));
40 | return;
41 | }
42 |
43 | if (pos == n) return;
44 | if (n - pos < k - cnt) return;
45 |
46 | recursion2(pos + 1, cnt, n, k, curr);
47 |
48 | // curr.set(cnt, pos + 1);
49 | curr[cnt] = pos + 1;
50 | recursion2(pos + 1, cnt + 1, n, k, curr);
51 | }
52 |
53 | private List> res = new ArrayList<>();
54 | public List> combine(int n, int k) {
55 | if (n == 0 || k > n) return res;
56 | if (k == 0) {
57 | res.add(new ArrayList<>());
58 | return res;
59 | }
60 | int[] curr = new int[k];
61 | // List curr = Arrays.asList(new Integer[k]);
62 | // recursion(0, 0, n, k, 0, curr);
63 | recursion2(0, 0, n, k, curr);
64 | return res;
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/ComplexNumMultiplication.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/30/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ComplexNumMultiplication {
8 | public String complexNumberMultiply(String a, String b) {
9 | String[] tmpa = a.split("\\+");
10 | String[] tmpb = b.split("\\+");
11 |
12 | int a1 = Integer.parseInt(tmpa[0]);
13 | int b1 = Integer.parseInt(tmpa[1].split("i")[0]);
14 |
15 | int a2 = Integer.parseInt(tmpb[0]);
16 | int b2 = Integer.parseInt(tmpb[1].split("i")[0]);
17 |
18 | int newa = a1 * a2 - b1 * b2;
19 | int newb = a1 * b2 + b1 * a2;
20 |
21 | return Integer.toString(newa) + "+" + Integer.toString(newb) + "i";
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/Complexity:
--------------------------------------------------------------------------------
1 | Below are the Big O performance of common functions of different Java Collections.
2 |
3 |
4 | List | Add | Remove | Get | Contains | Next | Data Structure
5 | ---------------------|------|--------|------|----------|------|---------------
6 | ArrayList | O(1) | O(n) | O(1) | O(n) | O(1) | Array
7 | LinkedList | O(1) | O(1) | O(n) | O(n) | O(1) | Linked List
8 |
9 |
10 |
11 | Set | Add | Remove | Contains | Next | Size | Data Structure
12 | ----------------------|----------|----------|----------|----------|------|-------------------------
13 | HashSet | O(1) | O(1) | O(1) | O(h/n) | O(1) | Hash Table
14 | LinkedHashSet | O(1) | O(1) | O(1) | O(1) | O(1) | Hash Table + Linked List
15 | EnumSet | O(1) | O(1) | O(1) | O(1) | O(1) | Bit Vector
16 | TreeSet | O(log n) | O(log n) | O(log n) | O(log n) | O(1) | Red-black tree
17 | CopyOnWriteArraySet | O(n) | O(n) | O(n) | O(1) | O(1) | Array
18 | ConcurrentSkipListSet | O(log n) | O(log n) | O(log n) | O(1) | O(n) | Skip List
19 |
20 |
21 |
22 | Queue | Offer | Peak | Poll | Remove | Size | Data Structure
23 | ------------------------|----------|------|----------|--------|------|---------------
24 | PriorityQueue | O(log n) | O(1) | O(log n) | O(n) | O(1) | Priority Heap
25 | LinkedList | O(1) | O(1) | O(1) | O(1) | O(1) | Array
26 | ArrayDequeue | O(1) | O(1) | O(1) | O(n) | O(1) | Linked List
27 | ConcurrentLinkedQueue | O(1) | O(1) | O(1) | O(n) | O(n) | Linked List
28 | ArrayBlockingQueue | O(1) | O(1) | O(1) | O(n) | O(1) | Array
29 | PriorirityBlockingQueue | O(log n) | O(1) | O(log n) | O(n) | O(1) | Priority Heap
30 | SynchronousQueue | O(1) | O(1) | O(1) | O(n) | O(1) | None!
31 | DelayQueue | O(log n) | O(1) | O(log n) | O(n) | O(1) | Priority Heap
32 | LinkedBlockingQueue | O(1) | O(1) | O(1) | O(n) | O(1) | Linked List
33 |
34 |
35 |
36 | Map | Get | ContainsKey | Next | Data Structure
37 | ----------------------|----------|-------------|----------|-------------------------
38 | HashMap | O(1) | O(1) | O(h / n) | Hash Table
39 | LinkedHashMap | O(1) | O(1) | O(1) | Hash Table + Linked List
40 | IdentityHashMap | O(1) | O(1) | O(h / n) | Array
41 | WeakHashMap | O(1) | O(1) | O(h / n) | Hash Table
42 | EnumMap | O(1) | O(1) | O(1) | Array
43 | TreeMap | O(log n) | O(log n) | O(log n) | Red-black tree
44 | ConcurrentHashMap | O(1) | O(1) | O(h / n) | Hash Tables
45 | ConcurrentSkipListMap | O(log n) | O(log n) | O(1) | Skip List
--------------------------------------------------------------------------------
/src/Complexity_backup:
--------------------------------------------------------------------------------
1 | Below are the Big O performance of common functions of different Java Collections.
2 |
3 |
4 | List | Add | Remove | Get | Contains | Next | Data Structure
5 | ---------------------|------|--------|------|----------|------|---------------
6 | ArrayList | O(1) | O(n) | O(1) | O(n) | O(1) | Array
7 | LinkedList | O(1) | O(1) | O(n) | O(n) | O(1) | Linked List
8 | CopyOnWriteArrayList | O(n) | O(n) | O(1) | O(n) | O(1) | Array
9 |
10 |
11 |
12 | Set | Add | Remove | Contains | Next | Size | Data Structure
13 | ----------------------|----------|----------|----------|----------|------|-------------------------
14 | HashSet | O(1) | O(1) | O(1) | O(h/n) | O(1) | Hash Table
15 | LinkedHashSet | O(1) | O(1) | O(1) | O(1) | O(1) | Hash Table + Linked List
16 | EnumSet | O(1) | O(1) | O(1) | O(1) | O(1) | Bit Vector
17 | TreeSet | O(log n) | O(log n) | O(log n) | O(log n) | O(1) | Red-black tree
18 | CopyOnWriteArraySet | O(n) | O(n) | O(n) | O(1) | O(1) | Array
19 | ConcurrentSkipListSet | O(log n) | O(log n) | O(log n) | O(1) | O(n) | Skip List
20 |
21 |
22 |
23 | Queue | Offer | Peak | Poll | Remove | Size | Data Structure
24 | ------------------------|----------|------|----------|--------|------|---------------
25 | PriorityQueue | O(log n) | O(1) | O(log n) | O(n) | O(1) | Priority Heap
26 | LinkedList | O(1) | O(1) | O(1) | O(1) | O(1) | Array
27 | ArrayDequeue | O(1) | O(1) | O(1) | O(n) | O(1) | Linked List
28 | ConcurrentLinkedQueue | O(1) | O(1) | O(1) | O(n) | O(n) | Linked List
29 | ArrayBlockingQueue | O(1) | O(1) | O(1) | O(n) | O(1) | Array
30 | PriorirityBlockingQueue | O(log n) | O(1) | O(log n) | O(n) | O(1) | Priority Heap
31 | SynchronousQueue | O(1) | O(1) | O(1) | O(n) | O(1) | None!
32 | DelayQueue | O(log n) | O(1) | O(log n) | O(n) | O(1) | Priority Heap
33 | LinkedBlockingQueue | O(1) | O(1) | O(1) | O(n) | O(1) | Linked List
34 |
35 |
36 |
37 | Map | Get | ContainsKey | Next | Data Structure
38 | ----------------------|----------|-------------|----------|-------------------------
39 | HashMap | O(1) | O(1) | O(h / n) | Hash Table
40 | LinkedHashMap | O(1) | O(1) | O(1) | Hash Table + Linked List
41 | IdentityHashMap | O(1) | O(1) | O(h / n) | Array
42 | WeakHashMap | O(1) | O(1) | O(h / n) | Hash Table
43 | EnumMap | O(1) | O(1) | O(1) | Array
44 | TreeMap | O(log n) | O(log n) | O(log n) | Red-black tree
45 | ConcurrentHashMap | O(1) | O(1) | O(h / n) | Hash Tables
46 | ConcurrentSkipListMap | O(log n) | O(log n) | O(1) | Skip List
--------------------------------------------------------------------------------
/src/ConstructStringFromBTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ConstructStringFromBTree {
8 | public String tree2str(TreeNode t) {
9 | if (t == null) return "";
10 |
11 | StringBuilder res = new StringBuilder();
12 |
13 | res.append(t.val);
14 |
15 | if (t.left == null && t.right == null) return res.toString();
16 |
17 | if (t.right == null) {
18 | return res.append("(").append(tree2str(t.left)).append(")").toString();
19 | }
20 | return res.append("(").append(tree2str(t.left)).append(")(").append(tree2str(t.right)).append(")").toString();
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/Contest104/Solution.java:
--------------------------------------------------------------------------------
1 | package Contest104;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * @author Harry Tran on 9/29/18.
8 | * @project Leetcode
9 | * @email trunghieu.tran@utdallas.edu
10 | * @organization UTDallas
11 | */
12 | public class Solution {
13 | public List wordSubsets(String[] A, String[] B) {
14 | int[] cntB = new int[26];
15 | for (String s : B) {
16 | int[] cntTemp = new int[26];
17 | for (char c : s.toCharArray()) {
18 | cntTemp[c - 'a']++;
19 | }
20 | for (int i = 0; i < 26; ++i)
21 | cntB[i] = Math.max(cntB[i], cntTemp[i]);
22 | }
23 | List res = new ArrayList<>();
24 | for (String s : A) {
25 | int[] cntTemp = new int[26];
26 | for (char c : s.toCharArray()) {
27 | cntTemp[c - 'a']++;
28 | }
29 | boolean ok = true;
30 | for (int i = 0; i < 26; ++i)
31 | ok &= cntTemp[i] >= cntB[i];
32 | if (ok) res.add(s);
33 | }
34 | return res;
35 | }
36 |
37 | int[][][] f;
38 |
39 | private int find(int i, int j, boolean turnMouse, int[][] graph) {
40 | if (i == 0) return 1;
41 | if (i == j) return 2;
42 |
43 | if (turnMouse) {
44 | if (f[i][j][0] != 0) return f[i][j][0];
45 |
46 | boolean hasHole = false;
47 | for (int x : graph[i]) {
48 | hasHole |= (x == 0);
49 | }
50 | if (hasHole) {
51 | f[i][j][0] = 1;
52 | return 1;
53 | }
54 |
55 | boolean[] tmp = new boolean[3];
56 | for (int x : graph[i]) {
57 | if (x == j) continue;
58 | int rr = find(x, j, false, graph);
59 | tmp[rr] = true;
60 | }
61 | f[i][j][0] = 3;
62 | if (tmp[1] && !tmp[0] && !tmp[2]) f[i][j][0] = 1;
63 | if (tmp[2] && !tmp[0] && !tmp[1]) f[i][j][0] = 2;
64 |
65 | return f[i][j][0];
66 | } else {
67 | if (f[i][j][1] != 0) return f[i][j][1];
68 |
69 | boolean meet = false;
70 | for (int x : graph[j]) {
71 | meet |= (x == i);
72 | }
73 | if (meet) {
74 | f[i][j][1] = 2;
75 | return 2;
76 | }
77 |
78 | boolean[] tmp = new boolean[3];
79 | for (int x : graph[j]) {
80 | if (x == 0) continue;
81 | int rr = find(i, x, true, graph);
82 | tmp[rr] = true;
83 | }
84 | f[i][j][1] = 3;
85 | if (tmp[1] && !tmp[0] && !tmp[2]) f[i][j][1] = 1;
86 | if (tmp[2] && !tmp[0] && !tmp[1]) f[i][j][1] = 2;
87 |
88 | return f[i][j][1];
89 | }
90 | }
91 |
92 | public int catMouseGame(int[][] graph) {
93 | int n = graph.length;
94 | f = new int[n][n][2];
95 | // f[i][j] : mouse at i, cat at j
96 | int resM = find(1, 2, true, graph);
97 | if (resM == 3) return 0;
98 | else return resM;
99 | }
100 |
101 | public static void main(String[] args) {
102 | System.out.println("hi");
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/src/Contest105/Solution.java:
--------------------------------------------------------------------------------
1 | package Contest105;
2 | import java.util.HashMap;
3 | import java.util.Map;
4 |
5 |
6 | /**
7 | * @author Harry Tran on 10/6/18.
8 | * @project Leetcode
9 | * @email trunghieu.tran@utdallas.edu
10 | * @organization UTDallas
11 | */
12 | public class Solution {
13 |
14 | public static void main(String[] args) {
15 | //["CBTInserter","insert","insert","get_root"]
16 | //[[[1,2,3,4,5,6]],[7],[8],[]]
17 | TreeNode root = new TreeNode(1);
18 | TreeNode n2 = new TreeNode(2);
19 | TreeNode n3 = new TreeNode(3);
20 | TreeNode n4 = new TreeNode(4);
21 | TreeNode n5 = new TreeNode(5);
22 | TreeNode n6 = new TreeNode(6);
23 | root.setChildren(n2, n3);
24 | n2.setChildren(n4,n5);
25 | n3.setChildren(n6, null);
26 | Solution sl = new Solution(root);
27 | System.out.println(sl.insert(7));
28 | System.out.println(sl.insert(8));
29 | System.out.println("DONE");
30 | }
31 |
32 | Map nChild;
33 | Map level;
34 | Map parent;
35 | TreeNode root;
36 |
37 | private int getPower(int a, int b) {
38 | return (int) Math.pow(a, b);
39 | }
40 |
41 | public Solution(TreeNode root) {
42 | this.root = root;
43 | nChild = new HashMap<>();
44 | level = new HashMap<>();
45 | parent = new HashMap<>();
46 | init(root);
47 | }
48 |
49 | private void init(TreeNode node) {
50 | int c = 1;
51 | int l = 1;
52 | if (node.left != null) {
53 | parent.put(node.left, node);
54 | init(node.left);
55 | c += nChild.get(node.left);
56 | l = 1 + level.get(node.left);
57 |
58 | if (node.right != null) {
59 | parent.put(node.right, node);
60 | init(node.right);
61 | c += nChild.get(node.right);
62 | }
63 | }
64 | nChild.put(node, c);
65 | level.put(node, l);
66 | }
67 |
68 | public int insert(int v) {
69 | return insertTo(root, v);
70 | }
71 |
72 | private int insertTo(TreeNode node, int v) {
73 | if (node.left == null) {
74 | TreeNode newN = new TreeNode(v);
75 | nChild.put(newN, 1);
76 | level.put(newN, 1);
77 | parent.put(newN, node);
78 |
79 | node.left = newN;
80 |
81 | TreeNode p = newN;
82 | boolean inc = true;
83 | while (p != null) {
84 | TreeNode par = parent.getOrDefault(p, null);
85 | if (par == null) break;
86 | nChild.put(par, nChild.get(par) + 1);
87 | if (inc) {
88 | int levelP = level.get(par);
89 | if (levelP == level.get(p)) {
90 | level.put(par, levelP + 1);
91 | } else inc = false;
92 | }
93 | p = par;
94 | }
95 |
96 | return node.val;
97 | }
98 | if (node.right == null) {
99 | TreeNode newN = new TreeNode(v);
100 | nChild.put(newN, 1);
101 | level.put(newN, 1);
102 | parent.put(newN, node);
103 |
104 | node.right = newN;
105 |
106 | TreeNode p = newN;
107 | while (p != null) {
108 | TreeNode par = parent.getOrDefault(p, null);
109 | if (par == null) break;
110 | nChild.put(par, nChild.get(par) + 1);
111 | p = par;
112 | }
113 |
114 | return node.val;
115 | }
116 |
117 | int childLeft = getPower(2, level.get(node.left)) - 1;
118 | int childRight = getPower(2, level.get(node.right)) - 1;
119 |
120 | if (childLeft > nChild.get(node.left)) {
121 | return insertTo(node.left, v);
122 | }
123 | if (childRight > nChild.get(node.right)) {
124 | return insertTo(node.right, v);
125 | }
126 | return insertTo(node.left, v);
127 | }
128 |
129 | public TreeNode get_root() {
130 | return this.root;
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/src/Contest105/TreeNode.java:
--------------------------------------------------------------------------------
1 | package Contest105;
2 |
3 | /**
4 | * @author Harry Tran on 10/6/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class TreeNode {
10 | int val;
11 | TreeNode left;
12 | TreeNode right;
13 | TreeNode(int x) { val = x; }
14 | public void setChildren(TreeNode left, TreeNode right) {this.left = left; this.right = right;}
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/Contest92/PrimePalindrome.java:
--------------------------------------------------------------------------------
1 | package Contest92;
2 |
3 | /**
4 | * @author Harry Tran on 7/7/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class PrimePalindrome {
10 | private boolean isPrime(int n) {
11 | if (n < 2) return false;
12 | for (long i = 2; i*i <= n; i++) {
13 | if (n % i == 0) {
14 | return false;
15 | }
16 | }
17 | return true;
18 | }
19 |
20 | private boolean isPalindrome(int n) {
21 | String str = Integer.toString(n);
22 | return isPalindromeStr(str);
23 | }
24 |
25 | public boolean isPalindromeStr(String str) {
26 | int length = str.length();
27 | int forward = 0;
28 | int backward = length - 1;
29 | while (backward > forward) {
30 | char forwardChar = str.charAt(forward++);
31 | char backwardChar = str.charAt(backward--);
32 | if (forwardChar != backwardChar)
33 | return false;
34 | }
35 | return true;
36 | }
37 |
38 | public int primePalindrome(int N) {
39 | while (true) {
40 | if (isPalindrome(N))
41 | if (isPrime(N)) return N;
42 | ++N;
43 | }
44 | }
45 |
46 | public static void main(String[] args) {
47 | PrimePalindrome p = new PrimePalindrome();
48 | System.out.println(p.primePalindrome(100000));
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/Contest92/ShortestPathAllKeys.java:
--------------------------------------------------------------------------------
1 | package Contest92;
2 |
3 | import javafx.util.Pair;
4 |
5 | import java.util.*;
6 |
7 | /**
8 | * @author Harry Tran on 7/7/18.
9 | * @project Leetcode
10 | * @email trunghieu.tran@utdallas.edu
11 | * @organization UTDallas
12 | */
13 | public class ShortestPathAllKeys {
14 |
15 | int[][][] f = new int[33][33][66];
16 | HashMap map = new HashMap<>();
17 | int done;
18 | private boolean isOk(int x, int y, String[] grid) {
19 | if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length()) return false;
20 | return grid[x].charAt(y) != '#';
21 | }
22 |
23 | private int getBit(int num, int i) {
24 | return (num >> i) & 1;
25 | }
26 |
27 | private int onBit(int num, int i) {
28 | return num | (1 << i);
29 | }
30 |
31 | int[] hh = {-1, 0, 0, 1};
32 | int[] cc = {0, -1, 1, 0};
33 |
34 | private void dfs(int x, int y, int status, String[] grid) {
35 | // int[] : x, y, status
36 | Queue queue = new LinkedList<>();
37 | HashMap inqueue = new HashMap<>();
38 |
39 | Integer[] tmp = new Integer[]{x, y, status};
40 | queue.add(tmp);
41 | inqueue.put(tmp, true);
42 |
43 | while (!queue.isEmpty()) {
44 | Integer[] curr = queue.poll();
45 | x = curr[0];
46 | y = curr[1];
47 | status = curr[2];
48 | inqueue.put(curr, false);
49 |
50 | for (int k = 0; k < 4; ++k) {
51 | int xx = x + hh[k];
52 | int yy = y + cc[k];
53 | if (!isOk(xx, yy, grid)) continue;
54 | char chr = grid[xx].charAt(yy);
55 | if ('a' <= chr && chr <= 'z') {
56 | int bit = map.get(chr);
57 | int newStatus = onBit(status, bit);
58 | Integer[] tmpNext = new Integer[]{xx, yy, newStatus};
59 | if (f[xx][yy][newStatus] > f[x][y][status] + 1) {
60 | f[xx][yy][newStatus] = f[x][y][status] + 1;
61 | if (!inqueue.getOrDefault(tmpNext, false)) {
62 | inqueue.put(tmpNext, true);
63 | queue.add(tmpNext);
64 | }
65 | }
66 |
67 | } else
68 | if ('A' <= chr && chr <= 'Z') {
69 | int bit = map.get(Character.toLowerCase(chr));
70 | if (getBit(status, bit) == 0) continue;
71 | Integer[] tmpNext = new Integer[]{xx, yy, status};
72 | if (f[xx][yy][status] > f[x][y][status] + 1) {
73 | f[xx][yy][status] = f[x][y][status] + 1;
74 | if (!inqueue.getOrDefault(tmpNext, false)) {
75 | inqueue.put(tmpNext, true);
76 | queue.add(tmpNext);
77 | }
78 | }
79 |
80 |
81 | }
82 | else if (chr == '.' || chr == '@') {
83 | Integer[] tmpNext = new Integer[]{xx, yy, status};
84 | if (f[xx][yy][status] > f[x][y][status] + 1) {
85 | f[xx][yy][status] = f[x][y][status] + 1;
86 | if (!inqueue.getOrDefault(tmpNext, false)) {
87 | inqueue.put(tmpNext, true);
88 | queue.add(tmpNext);
89 | }
90 | }
91 | }
92 | }
93 | }
94 |
95 | }
96 |
97 | public int shortestPathAllKeys(String[] grid) {
98 | for (int i = 0; i < 33; ++i)
99 | for (int j = 0; j < 33; ++j)
100 | for (int k = 0; k < 66; ++k)
101 | f[i][j][k] = 1000000000;
102 | int x = 0, y = 0;
103 | int cc = 0;
104 | for (int i = 0; i < grid.length; ++i)
105 | for (int j = 0; j < grid[0].length(); ++j) {
106 | char chr = grid[i].charAt(j);
107 | if (chr == '@') {
108 | x = i;
109 | y = j;
110 | f[x][y][0] = 0;
111 | }
112 | if ('a' <= chr && chr <= 'z') {
113 | map.put(chr, cc++);
114 | }
115 | }
116 |
117 | done = (1 << cc) - 1;
118 | dfs(x, y, 0, grid);
119 |
120 |
121 | int res = -1;
122 | for (int i = 0; i < grid.length; ++i)
123 | for (int j = 0; j < grid[0].length(); ++j)
124 | if (f[i][j][done] != 1000000000) {
125 | if (res == -1) res = f[i][j][done];
126 | else res = Math.min(res, f[i][j][done]);
127 | }
128 | return res;
129 | }
130 |
131 | public static void main(String[] args) {
132 | ShortestPathAllKeys sp = new ShortestPathAllKeys();
133 | String[] grid = new String[]{"@...a",".###A","b.BCc"};
134 | System.out.println(sp.shortestPathAllKeys(grid));
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/src/Contest92/SmallestSubstree.java:
--------------------------------------------------------------------------------
1 | package Contest92;
2 |
3 | import java.util.HashMap;
4 |
5 | /**
6 | * @author Harry Tran on 7/7/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class SmallestSubstree {
12 |
13 | public class TreeNode {
14 | int val;
15 | TreeNode left;
16 | TreeNode right;
17 | TreeNode(int x) { val = x; }
18 | }
19 |
20 | HashMap fDeep = new HashMap<>();
21 | HashMap mapDeep = new HashMap<>();
22 |
23 | TreeNode res = null;
24 | int deepest = -1;
25 | int cDeepest = 0;
26 | boolean found = false;
27 |
28 | private void traverse(TreeNode node, int level) {
29 | mapDeep.put(node, level);
30 |
31 | if (node.left != null) {
32 | traverse(node.left, level + 1);
33 | }
34 | if (node.right != null) {
35 | traverse(node.right, level + 1);
36 | }
37 |
38 | if (level > deepest) {
39 | deepest = level;
40 | cDeepest = 1;
41 | } else
42 | if (level == deepest) {
43 | ++cDeepest;
44 | }
45 | }
46 |
47 | private void traverse2(TreeNode node) {
48 | if (found) return;
49 |
50 | int level = mapDeep.getOrDefault(node, 0);
51 | int cc = 0;
52 | if (level == deepest) {
53 | fDeep.put(node, 1);
54 | cc++;
55 | }
56 | else {
57 | if (node.left != null) {
58 | traverse2(node.left);
59 | cc += fDeep.getOrDefault(node.left, 0);
60 | }
61 |
62 | if (found) return;
63 |
64 | if (node.right != null) {
65 | traverse2(node.right);
66 | cc += fDeep.getOrDefault(node.right, 0);
67 | }
68 |
69 | if (found) return;
70 | }
71 | System.out.println(node.val);
72 | System.out.println(cc);
73 | System.out.println();
74 | if (cc == cDeepest) {
75 | found = true;
76 | res = node;
77 | }
78 | }
79 |
80 | public TreeNode subtreeWithAllDeepest(TreeNode root) {
81 | traverse(root, 0);
82 | System.out.println(cDeepest);
83 | System.out.println(deepest);
84 | System.out.println("---");
85 | traverse2(root);
86 | return res;
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/Contest92/TransposeMatrix.java:
--------------------------------------------------------------------------------
1 | package Contest92;
2 |
3 | /**
4 | * @author Harry Tran on 7/7/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class TransposeMatrix {
10 | public int[][] transpose(int[][] A) {
11 | int h = A.length;
12 | int w = A[0].length;
13 | int[][] res = new int[w][h];
14 |
15 | for (int i = 0; i < h; ++i)
16 | for (int j = 0; j < w; ++j)
17 | res[j][i] = A[i][j];
18 | return res;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/Contest93/AdvantageShuffle.java:
--------------------------------------------------------------------------------
1 | package Contest93;
2 |
3 | import java.lang.reflect.Array;
4 | import java.util.Arrays;
5 | import java.util.Collections;
6 |
7 | /**
8 | * @author Harry Tran on 7/14/18.
9 | * @project Leetcode
10 | * @email trunghieu.tran@utdallas.edu
11 | * @organization UTDallas
12 | */
13 | public class AdvantageShuffle {
14 | public int[] advantageCount(int[] A, int[] B) {
15 | int len = A.length;
16 | Arrays.sort(A);
17 |
18 | int[] res = new int[len];
19 | boolean[] marked = new boolean[len];
20 | Arrays.fill(marked, false);
21 | Arrays.fill(res, -1);
22 |
23 | int ii = 0;
24 | for (int i = 0; i < len; ++i) {
25 | int l = 0;
26 | int r = len - 1;
27 | int best = -1;
28 | while (l <= r) {
29 | int mid = (l + r) / 2;
30 | if (A[mid] > B[i]) {
31 | best = mid;
32 | r = mid -1;
33 | } else {
34 | l = mid + 1;
35 | }
36 | }
37 | if (best != -1) {
38 | while (best < len && marked[best]) best++;
39 | if (best < len) {
40 | marked[best] = true;
41 | res[i] = A[best];
42 | } else {
43 | while (ii < len && marked[ii]) ++ii;
44 | res[i] = A[ii];
45 | marked[ii] = true;
46 | }
47 | } else {
48 | while (ii < len && marked[ii]) ++ii;
49 | res[i] = A[ii];
50 | marked[ii] = true;
51 | }
52 | }
53 | return res;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/Contest93/BinaryGap.java:
--------------------------------------------------------------------------------
1 | package Contest93;
2 |
3 | /**
4 | * @author Harry Tran on 7/14/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class BinaryGap {
10 | public int binaryGap(int N) {
11 | if (N == 0) return 0;
12 | String b = Integer.toBinaryString(N);
13 | int max = 0;
14 | for (int i = 0; i < b.length() - 1; ++i)
15 | if (b.charAt(i) == '1') {
16 | int j = i + 1;
17 | while (j < b.length() && b.charAt(j) == '0') ++j;
18 | if (j < b.length())
19 | max = Math.max(j - i, max);
20 | }
21 | return max;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/Contest93/MinRefuelStops.java:
--------------------------------------------------------------------------------
1 | package Contest93;
2 |
3 | import javafx.util.Pair;
4 |
5 | import java.util.*;
6 |
7 | /**
8 | * @author Harry Tran on 7/14/18.
9 | * @project Leetcode
10 | * @email trunghieu.tran@utdallas.edu
11 | * @organization UTDallas
12 | */
13 | public class MinRefuelStops {
14 |
15 | public int minRefuelStops(int target, int startFuel, int[][] stations) {
16 | if (stations.length == 0) {
17 | if (target <= startFuel) return 0;
18 | return -1;
19 | }
20 | if (startFuel >= target) return 0;
21 |
22 | PriorityQueue q = new PriorityQueue<>(Collections.reverseOrder());
23 | int res = 0, lastPos = 0;
24 | for (int[] station : stations) {
25 | int pos = station[0];
26 | int fuel = station[1];
27 |
28 | startFuel -= (pos - lastPos);
29 |
30 | while (!q.isEmpty() && startFuel < 0) {
31 | startFuel += q.poll();
32 | res++;
33 | }
34 | if (startFuel < 0) return -1;
35 | q.offer(fuel);
36 | lastPos = pos;
37 | }
38 |
39 | startFuel -= target - lastPos;
40 | while (!q.isEmpty() && startFuel < 0) {
41 | startFuel += q.poll();
42 | ++res;
43 | }
44 | if (startFuel < 0) return -1;
45 | return res;
46 | }
47 | public int minRefuelStops_N2(int target, int startFuel, int[][] stations) {
48 | if (stations.length == 0) {
49 | if (target <= startFuel) return 0;
50 | return -1;
51 | }
52 |
53 | if (startFuel >= target) return 0;
54 |
55 | int len = stations.length;
56 | long[] f = new long[len + 1]; // f[i] - furthest position using i refuel
57 |
58 | Arrays.fill(f, startFuel);
59 | for (int j = 0; j < len; ++j) {
60 | for (int i = j + 1; i >= 1; --i) {
61 | if (f[i - 1] >= stations[j][0]) {
62 | if (f[i] < f[i - 1] + stations[j][1]) {
63 | f[i] = f[i - 1] + stations[j][1];
64 | }
65 | } else break;
66 | }
67 | }
68 | for (int i = 0; i <= len; ++i)
69 | if (f[i] >= target) return i;
70 | return -1;
71 | }
72 |
73 | public int minRefuelStops2(int target, int startFuel, int[][] stations) {
74 | if (stations.length == 0) {
75 | if (target <= startFuel) return 0;
76 | return -1;
77 | }
78 | HashMap, Integer> f = new HashMap<>();
79 | Queue> queue = new LinkedList<>();
80 | HashMap, Boolean> inq = new HashMap<>();
81 |
82 | Pair stp = new Pair<>(-1, startFuel);
83 | f.put(stp, 0);
84 | queue.add(stp);
85 | inq.put(stp, true);
86 |
87 | while (!queue.isEmpty()) {
88 | Pair curr = queue.poll();
89 | inq.put(curr, false);
90 |
91 | int val = f.get(curr);
92 | int station = curr.getKey();
93 | int fuel = curr.getValue();
94 | int pos = station == -1 ? 0 : stations[station][0];
95 |
96 | for (int i = station + 1; i < stations.length; ++i) {
97 | int newPos = stations[i][0];
98 | if (newPos - pos <= fuel) {
99 | Pair newP = new Pair<>(i, fuel - newPos + pos);
100 | if (!f.containsKey(newP) || f.get(newP) > val) {
101 | f.put(newP, val);
102 | if (!inq.getOrDefault(newP, false)) {
103 | queue.add(newP);
104 | inq.put(newP, true);
105 | }
106 | }
107 | if (fuel + pos < target) {
108 | int newFuel = fuel - newPos + pos + stations[i][1];
109 | Pair newP2 = new Pair<>(i, newFuel);
110 | if (!f.containsKey(newP2) || f.get(newP2) > val + 1) {
111 | f.put(newP2, val + 1);
112 | if (!inq.getOrDefault(newP2, false)) {
113 | queue.add(newP2);
114 | inq.put(newP2, true);
115 | }
116 | }
117 | }
118 | }
119 | }
120 | }
121 |
122 | int res = -1;
123 | for (Pair p : f.keySet()) {
124 | int i = p.getKey();
125 | int pos = 0;
126 | if (i != -1)
127 | pos = stations[p.getKey()][0];
128 | int fuel = p.getValue();
129 | int val = f.get(p);
130 |
131 | if (pos + fuel >= target) {
132 | if (res == -1 || res > val) res = val;
133 | }
134 | }
135 | return res;
136 | }
137 |
138 | public static void main(String[] args) {
139 | MinRefuelStops ms = new MinRefuelStops();
140 | // int target = 100;
141 | // int fuel = 10;
142 | // int[][] st = {{10, 60}, {20, 30}, {30, 30}, {60, 40}};
143 | // int target = 100;
144 | // int fuel = 50;
145 | // int[][] st = {{25,25},{50,50}};
146 |
147 | // int target = 100;
148 | // int fuel = 1;
149 | // int[][] st = {{10, 100}};
150 |
151 | int target = 1000000;
152 | int fuel = 8663;
153 | int[][] st = {{31,195796},{42904,164171},{122849,139112},{172890,121724},{182747,90912},{194124,112994},{210182,101272},{257242,73097},{284733,108631},{369026,25791},{464270,14596},{470557,59420},{491647,192483},{516972,123213},{577532,184184},{596589,143624},{661564,154130},{705234,100816},{721453,122405},{727874,6021},{728786,19444},{742866,2995},{807420,87414},{922999,7675},{996060,32691}};
154 | // int target = 1000;
155 | // int fuel = 83;
156 | // int[][] st = {{25,27},{36,187},{140,186},{378,6},{492,202},{517,89},{579,234},{673,86},{808,53},{954,49}};
157 | System.out.println(ms.minRefuelStops(target, fuel, st));
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/src/Contest93/ReorderedPowerOf2.java:
--------------------------------------------------------------------------------
1 | package Contest93;
2 |
3 | import java.util.ArrayList;
4 |
5 | /**
6 | * @author Harry Tran on 7/14/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class ReorderedPowerOf2 {
12 |
13 | private boolean isMatch(int N, long x) {
14 | //System.out.println(Integer.toString(N) + " " + Long.toString(x));
15 | int[] c = new int[10];
16 | while (N > 0) {
17 | c[N % 10]++;
18 | N /= 10;
19 | }
20 | while (x > 0) {
21 | long mod = x;
22 | mod = mod % 10;
23 | c[(int) mod]--;
24 | x /= 10;
25 | }
26 | for (int i = 0; i < 10; ++i)
27 | if (c[i] != 0) return false;
28 | //System.out.println(x);
29 | return true;
30 | }
31 |
32 | public boolean reorderedPowerOf2(int N) {
33 | ArrayList data = new ArrayList<>();
34 | double x = 2.0;
35 | for (int i = 0; i < 40; ++i) {
36 | long tmp = (long) Math.pow(x, (double) i);
37 | data.add(tmp);
38 | }
39 | for (int i = 0; i < data.size(); ++i) {
40 | if (isMatch(N, data.get(i))) return true;
41 | }
42 | return false;
43 | }
44 |
45 | public static void main(String[] args) {
46 | ReorderedPowerOf2 r = new ReorderedPowerOf2();
47 | System.out.println(r.reorderedPowerOf2(123456789));
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/Contest94/KokoEatingBananas.java:
--------------------------------------------------------------------------------
1 | package Contest94;
2 |
3 | /**
4 | * @author Harry Tran on 7/21/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class KokoEatingBananas {
10 | // 1 <= piles.length <= 10^4
11 | // piles.length <= H <= 10^9
12 | // 1 <= piles[i] <= 10^9
13 |
14 | private boolean isOK(int[] piles, int H, int val) {
15 | int cc = 0;
16 | for (int i = 0; i < piles.length; ++i) {
17 | cc += piles[i] / val;
18 | if (piles[i] % val != 0) ++cc;
19 | }
20 | return cc <= H;
21 | }
22 |
23 | public int minEatingSpeed(int[] piles, int H) {
24 | int vmax = Integer.MAX_VALUE - 2;
25 | int vmin = 1;
26 |
27 | int res = vmax;
28 | while (vmin <= vmax) {
29 | int mid = (vmax + vmin) / 2;
30 | if (isOK(piles, H, mid)) {
31 | res = mid;
32 | vmax = mid - 1;
33 | } else vmin = mid + 1;
34 | }
35 | return res;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/Contest94/LeafSimilar.java:
--------------------------------------------------------------------------------
1 | package Contest94;
2 |
3 |
4 | import java.util.ArrayList;
5 | import java.util.Arrays;
6 |
7 | /**
8 | * @author Harry Tran on 7/21/18.
9 | * @project Leetcode
10 | * @email trunghieu.tran@utdallas.edu
11 | * @organization UTDallas
12 | */
13 | public class LeafSimilar {
14 | public class TreeNode {
15 | int val;
16 | TreeNode left;
17 | TreeNode right;
18 | TreeNode(int x) { val = x; }
19 | }
20 |
21 | private void traverse(TreeNode n, ArrayList res) {
22 | if (n == null) return;
23 |
24 | if (n.left == null && n.right == null) {
25 | res.add(n.val);
26 | return;
27 | }
28 |
29 | traverse(n.left, res);
30 | traverse(n.right, res);
31 | }
32 |
33 | public boolean leafSimilar(TreeNode root1, TreeNode root2) {
34 | ArrayList r1 = new ArrayList<>();
35 | ArrayList r2 = new ArrayList<>();
36 | traverse(root1, r1);
37 | traverse(root2, r2);
38 | if (r1.size() != r2.size()) return false;
39 | for (int i = 0; i < r1.size(); ++i)
40 | if (r1.get(i) != r2.get(i)) return false;
41 | return true;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/Contest94/LenLongestFibSubseq.java:
--------------------------------------------------------------------------------
1 | package Contest94;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * @author Harry Tran on 7/21/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class LenLongestFibSubseq {
12 | public int lenLongestFibSubseq(int[] A) {
13 | int n = A.length;
14 | int[][] f = new int[n][n];
15 |
16 | for (int i = 0; i < n - 1; ++i)
17 | for (int j = i + 1; j < n; ++j)
18 | f[i][j] = 2;
19 |
20 | int res = 0;
21 | for (int j = 2; j < n; ++j)
22 | for (int i = 1; i < j; ++i) {
23 | int k = Arrays.binarySearch(A, 0, i, A[j] - A[i]);
24 | if (k < 0) continue;
25 | f[i][j] = Math.max(f[i][j], f[k][i] + 1);
26 | res = Math.max(res, f[i][j]);
27 | }
28 |
29 | return res;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/Contest94/RobotSim.java:
--------------------------------------------------------------------------------
1 | package Contest94;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.HashMap;
6 |
7 | /**
8 | * @author Harry Tran on 7/21/18.
9 | * @project Leetcode
10 | * @email trunghieu.tran@utdallas.edu
11 | * @organization UTDallas
12 | */
13 | public class RobotSim {
14 |
15 | int res = 0;
16 | HashMap> mapX = new HashMap<>();
17 | HashMap> mapY = new HashMap<>();
18 | int dir = 2;
19 | int cx = 0, cy = 0;
20 |
21 | private int changeDir(int cmd, int dir) {
22 | if (cmd == -2) {
23 | if (dir == 2) return 0;
24 | if (dir == 0) return 1;
25 | if (dir == 1) return 3;
26 | return 2;
27 | } else {
28 | if (dir == 2) return 3;
29 | if (dir == 3) return 1;
30 | if (dir == 1) return 0;
31 | return 2;
32 | }
33 | }
34 |
35 | private int findMinBiggerVal(int val, ArrayList arr) {
36 | int l = 0;
37 | int r = arr.size() - 1;
38 | int res = -1;
39 | while (l <= r) {
40 | int mid = (l + r) / 2;
41 | if (arr.get(mid) > val) {
42 | res = mid;
43 | r = mid - 1;
44 | } else l = mid + 1;
45 | }
46 | return res;
47 | }
48 |
49 | private int findMaxSmallerVal(int val, ArrayList arr) {
50 | int l = 0;
51 | int r = arr.size() - 1;
52 | int res = -1;
53 | while (l <= r) {
54 | int mid = (l + r) / 2;
55 | if (arr.get(mid) < val) {
56 | res = mid;
57 | l = mid + 1;
58 | } else r = mid - 1;
59 | }
60 | return res;
61 | }
62 |
63 | private void go(int cmd) {
64 | if (dir == 2) {
65 | ArrayList arr = mapX.getOrDefault(cx, null);
66 | if (arr == null) {
67 | cy += cmd;
68 | } else {
69 | int id = findMinBiggerVal(cy, arr);
70 | if (id == -1) {
71 | cy += cmd;
72 | } else {
73 | cy += Math.min(cmd, arr.get(id) - cy - 1);
74 | }
75 | }
76 |
77 | }
78 | if (dir == 1) {
79 | ArrayList arr = mapX.getOrDefault(cx, null);
80 | if (arr == null) {
81 | cy -= cmd;
82 | } else {
83 | int id = findMaxSmallerVal(cy, arr);
84 | if (id == -1) {
85 | cy -= cmd;
86 | } else {
87 | cy -= Math.min(cmd, cy - arr.get(id) - 1);
88 | }
89 | }
90 | }
91 | if (dir == 0) {
92 | ArrayList arr = mapY.getOrDefault(cy, null);
93 | if (arr == null) {
94 | cx -= cmd;
95 | } else {
96 | int id = findMaxSmallerVal(cx, arr);
97 | if (id == -1) {
98 | cx -= cmd;
99 | } else {
100 | cx -= Math.min(cmd, cx - arr.get(id) - 1);
101 | }
102 | }
103 | }
104 |
105 | if (dir == 3) {
106 | ArrayList arr = mapY.getOrDefault(cy, null);
107 | if (arr == null) {
108 | cx += cmd;
109 | } else {
110 | int id = findMinBiggerVal(cx, arr);
111 | if (id == -1) {
112 | cx += cmd;
113 | } else {
114 | cx += Math.min(cmd, arr.get(id) - cx - 1);
115 | }
116 | }
117 | }
118 |
119 | res = Math.max(res, cx * cx + cy * cy);
120 | }
121 |
122 | public int robotSim(int[] commands, int[][] obstacles) {
123 |
124 | for (int[] ob : obstacles) {
125 | int xx = ob[0];
126 | int yy = ob[1];
127 | if (mapX.containsKey(xx))
128 | mapX.get(xx).add(yy);
129 | else {
130 | ArrayList tmp = new ArrayList<>();
131 | tmp.add(yy);
132 | mapX.put(xx, tmp);
133 | }
134 |
135 | if (mapY.containsKey(yy))
136 | mapY.get(yy).add(xx);
137 | else {
138 | ArrayList tmp = new ArrayList<>();
139 | tmp.add(xx);
140 | mapY.put(yy, tmp);
141 | }
142 | }
143 |
144 | for (int key : mapX.keySet()) {
145 | Collections.sort(mapX.get(key));
146 | }
147 |
148 | for (int key : mapY.keySet()) {
149 | Collections.sort(mapY.get(key));
150 | }
151 |
152 |
153 |
154 | for (int cmd : commands) {
155 | if (cmd < 0) {
156 | dir = changeDir(cmd, dir);
157 | } else {
158 | go(cmd);
159 | }
160 | }
161 | return res;
162 | }
163 |
164 | public static void main(String[] args) {
165 | RobotSim ts = new RobotSim();
166 | int[] cmds = {-2, 8,3,7, -1};
167 | int[][] obs = {{-4,-1},{1,-1},{1,4},{5,0},{4,5},{-2,-1},{2,-5},{5,1},{-3,-1},{5,-3}};
168 | System.out.println(ts.robotSim(cmds, obs));
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/src/ConvertBSTToGreaterTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ConvertBSTToGreaterTree {
8 |
9 | int sum = 0;
10 | public TreeNode convertBST(TreeNode root) {
11 | if (root == null) return root;
12 | convertBST(root.right);
13 | root.val += sum;
14 | sum = root.val;
15 | convertBST(root.left);
16 | return root;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/ConvertSortedArrayToBinarySearchTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ConvertSortedArrayToBinarySearchTree {
8 |
9 | private void maker(int i, int j, TreeNode n, int[] nums) {
10 | if (i == j) {
11 | n.val = nums[i];
12 | return;
13 | }
14 | if ((j - i) % 2 == 0) {
15 | TreeNode left = new TreeNode(0);
16 | TreeNode right = new TreeNode(0);
17 | n.left = left;
18 | n.right = right;
19 | int mid = (j + i) / 2;
20 | n.val = nums[mid];
21 | maker(i, mid - 1, left, nums);
22 | maker(mid + 1, j, right, nums);
23 | } else {
24 | int mid = (i + j + 1) / 2;
25 | n.val = nums[mid];
26 |
27 | TreeNode left = new TreeNode(0);
28 | n.left = left;
29 | maker(i, mid - 1, left, nums);
30 |
31 | if (mid + 1 <= j) {
32 | TreeNode right = new TreeNode(0);
33 | n.right = right;
34 | maker(mid + 1, j, right, nums);
35 | }
36 | }
37 | }
38 |
39 | public TreeNode sortedArrayToBST(int[] nums) {
40 | TreeNode res = new TreeNode(0);
41 | if (nums.length > 0) maker(0, nums.length -1, res, nums);
42 | return res;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/ConvertSortedListToBST.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ConvertSortedListToBST {
8 | ListNode currHead;
9 | public TreeNode sortedListToBST(ListNode head) {
10 | if (head == null) return null;
11 | ListNode ln = head;
12 | int cc = 0;
13 | while (ln.next != null) {
14 | ++cc;
15 | ln = ln.next;
16 | }
17 | currHead = head;
18 | return maker(0, cc);
19 | }
20 |
21 | private TreeNode maker(int l, int r) {
22 | if (l == r) {
23 | TreeNode tn = new TreeNode(currHead.val);
24 | currHead = currHead.next;
25 | return tn;
26 | }
27 | int mid = (r + l + 1) / 2;
28 | TreeNode tmp = new TreeNode(0);
29 |
30 | tmp.left = maker(l, mid - 1);
31 |
32 | tmp.val= currHead.val;
33 | currHead = currHead.next;
34 |
35 | if (mid + 1 <= r) {
36 | tmp.right = maker(mid + 1, r);
37 | }
38 | return tmp;
39 | }
40 |
41 | public static void main(String[] args) {
42 | int[] arr = {-10,-3,0,5,9};
43 | ListNode head = new ListNode(arr[0]);
44 | ListNode last = head;
45 | for (int i = 1; i < arr.length; ++i) {
46 | ListNode tmp = new ListNode(arr[i]);
47 | last.next = tmp;
48 | last = tmp;
49 | }
50 | ConvertSortedListToBST c = new ConvertSortedListToBST();
51 | TreeNode res = c.sortedListToBST(head);
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/CountNumbersWithUniqueDigits.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/15/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class CountNumbersWithUniqueDigits {
8 |
9 | private int getBit(int num, int i) {
10 | return (num >> i) & 1;
11 | }
12 |
13 | private int onBit(int num, int i) {
14 | return num | (1 << i);
15 | }
16 |
17 | int[][][] f;
18 | int n;
19 | private int count(int pos, int status, int bigger0) {
20 | if (pos == n) {
21 | return 1;
22 | }
23 | if (f[pos][status][bigger0] != -1) return f[pos][status][bigger0];
24 |
25 | int res = 0;
26 |
27 | if (bigger0 == 1) {
28 | if (getBit(status, 0) == 0) {
29 | res += count(pos + 1, onBit(status, 0), 1);
30 | }
31 | } else {
32 | res += count(pos + 1, status, 0);
33 | }
34 |
35 | for (int i = 1; i < 10; ++i) {
36 | if (getBit(status, i) == 0) {
37 | res += count(pos + 1, onBit(status, i), 1);
38 | }
39 | }
40 |
41 | f[pos][status][bigger0] = res;
42 | return res;
43 | }
44 |
45 | public int countNumbersWithUniqueDigits(int n) {
46 | f = new int[n + 1][1024][2];
47 | for (int i = 0; i < n + 1; ++i)
48 | for (int j = 0; j < 1024; ++j)
49 | for (int k = 0; k < 2; ++k)
50 | f[i][j][k] = -1;
51 | this.n = n;
52 | return count(0, 0, 0);
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/CountSmaller.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.Arrays;
3 | import java.util.List;
4 |
5 | /**
6 | * @author Harry Tran on 7/24/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class CountSmaller {
12 |
13 | public class TreeNode {
14 | int val;
15 | int sum;
16 | TreeNode left;
17 | TreeNode right;
18 | TreeNode(int x, int y) { val = x; sum = y ;}
19 | }
20 |
21 | private int get(TreeNode node, int val) {
22 | node.sum++;
23 | int res = 0;
24 | if (val >= node.val) {
25 | if (val > node.val) res++;
26 | if (node.left != null) res += node.left.sum;
27 | if (node.right != null) {
28 | res += get(node.right, val);
29 | } else {
30 | node.right = new TreeNode(val, 1);
31 | }
32 | } else {
33 | if (node.left == null) {
34 | node.left = new TreeNode(val, 1);
35 | } else {
36 | res += get(node.left, val);
37 | }
38 | }
39 | return res;
40 | }
41 |
42 | public List countSmaller(int[] nums) {
43 | int n = nums.length;
44 | if (n == 0) return new ArrayList<>();
45 |
46 | Integer[] res = new Integer[n];
47 | TreeNode root = new TreeNode(nums[n - 1], 1);
48 | res[n - 1] = 0;
49 |
50 | for (int i = n - 2; i >= 0; --i) {
51 | res[i] = get(root, nums[i]);
52 | }
53 | return Arrays.asList(res);
54 | }
55 |
56 | public static void main(String[] args) {
57 | int[] nums = {5,2,6,1};
58 | CountSmaller cs = new CountSmaller();
59 | List res = cs.countSmaller(nums);
60 | for (int i = 0; i < res.size(); ++i)
61 | System.out.println(res.get(i));
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/CountingBits.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/30/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class CountingBits {
8 | public int[] countBits(int num) {
9 | int[] res = new int[num + 1];
10 | for (int i = 0; i <= num; ++i)
11 | res[i] = Integer.bitCount(i);
12 | return res;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/CustomSortingString.java:
--------------------------------------------------------------------------------
1 | import javafx.util.Pair;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.Comparator;
6 |
7 | /**
8 | * @author Harry Tran on 6/30/18.
9 | * @project Leetcode
10 | * @email trunghieu.tran@utdallas.edu
11 | * @organization UTDallas
12 | */
13 | public class CustomSortingString {
14 | public String customSortString_2(String S, String T) {
15 | int[] count = new int[26];
16 | for (char chr : T.toCharArray()) {
17 | count[chr - 'a']++;
18 | }
19 | ArrayList> list = new ArrayList<>();
20 | int lenS = S.length();
21 | for (int i = 0; i < lenS; ++i)
22 | list.add(new Pair<>(i, S.charAt(i)));
23 | // list.sort(Comparator.comparingInt(Pair::getKey));
24 | Collections.sort(list, new Comparator>() {
25 | @Override
26 | public int compare(Pair o1, Pair o2) {
27 | return o1.getKey().compareTo(o2.getKey());
28 | }
29 | });
30 |
31 | StringBuilder res = new StringBuilder();
32 |
33 | for (Pair p : list) {
34 | System.out.println(Integer.toString(p.getKey()) + " " + p.getValue());
35 | char c = p.getValue();
36 | for (int i = 0; i < count[c - 'a']; ++i)
37 | res.append(c);
38 | count[c - 'a'] = 0;
39 | }
40 | for (char ch = 'a'; ch <= 'z'; ++ch)
41 | if (count[ch - 'a'] > 0) {
42 | for (int i = 0; i < count[ch - 'a']; ++i)
43 | res.append(ch);
44 | }
45 | return res.toString();
46 | }
47 |
48 | public String customSortString(String S, String T) {
49 | int[] count = new int[26];
50 | for (char chr : T.toCharArray()) {
51 | count[chr - 'a']++;
52 | }
53 |
54 | StringBuilder res = new StringBuilder();
55 | for (char chr : S.toCharArray()) {
56 | int pos = chr - 'a';
57 | for (int i = 0; i < count[pos]; ++i)
58 | res.append(chr);
59 | count[pos] = 0;
60 | }
61 |
62 | for (int i = 0; i < 26; ++i)
63 | if (count[i] > 0) {
64 | for (int j = 0; j < count[i]; ++j)
65 | res.append((char) (i + 'a'));
66 | }
67 | return res.toString();
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/DailyTemperatures.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/4/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class DailyTemperatures {
8 | public int[] dailyTemperatures(int[] temperatures) {
9 | int len = temperatures.length;
10 |
11 | if (len == 0) return new int[0];
12 |
13 | int[] next = new int[len];
14 |
15 | next[len - 1] = 0;
16 | for (int i = len - 2; i >= 0; i--) {
17 | int j = i + 1;
18 |
19 | while (j < len && j != 0 && temperatures[i] >= temperatures[j]) j = next[j];
20 |
21 | if (j == 0) next[i] = 0;
22 | else next[i] = j;
23 |
24 | next[i] = j;
25 | }
26 |
27 | int[] res = new int[len];
28 | for (int i = 0; i < len; ++i)
29 | if (next[i] != 0) res[i] = next[i] - i;
30 | return res;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/DesignLinkedList.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 10/4/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class DesignLinkedList {
8 | public static void main(String[] args) {
9 | DesignLinkedList obj = new DesignLinkedList();
10 | int param_1 = obj.get(1);
11 | obj.addAtHead(1);
12 | obj.addAtTail(3);
13 | obj.addAtIndex(1,2);
14 | int x = obj.get(1);
15 | obj.deleteAtIndex(1);
16 | int y = obj.get(1);
17 | }
18 | class LinkedListNode {
19 | int val;
20 | LinkedListNode next;
21 | LinkedListNode(int val) {
22 | this.val = val;
23 | }
24 | }
25 | LinkedListNode head, tail;
26 | int n;
27 |
28 | /** Initialize your data structure here. */
29 | public DesignLinkedList() {
30 | head = null;
31 | tail = head;
32 | n = 0;
33 | }
34 |
35 | /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
36 | public int get(int index) {
37 | if (index >= n || index < 0) return -1;
38 | LinkedListNode curr = head;
39 | for (int i = 0; i < index; ++i) {
40 | curr = curr.next;
41 | }
42 | return curr.val;
43 | }
44 |
45 | /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
46 | public void addAtHead(int val) {
47 | ++n;
48 | LinkedListNode newN = new LinkedListNode(val);
49 | if (head == null) {
50 | head = newN;
51 | tail = head;
52 | } else {
53 | newN.next = head;
54 | head = newN;
55 | }
56 | }
57 |
58 | /** Append a node of value val to the last element of the linked list. */
59 | public void addAtTail(int val) {
60 | ++n;
61 | LinkedListNode newN = new LinkedListNode(val);
62 | if (tail == null) {
63 | head = newN;
64 | tail = head;
65 | } else {
66 | tail.next = newN;
67 | tail = newN;
68 | }
69 | }
70 |
71 | /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
72 | public void addAtIndex(int index, int val) {
73 | if (index > n || index < 0) return;
74 | if (index == 0) {
75 | addAtHead(val);
76 | return;
77 | }
78 | if (index == n) {
79 | addAtTail(val);
80 | return;
81 | }
82 |
83 | ++n;
84 | LinkedListNode newN = new LinkedListNode(val);
85 | LinkedListNode curr = head;
86 | LinkedListNode last = null;
87 | for (int i = 0; i < index; ++i) {
88 | last = curr;
89 | curr = curr.next;
90 | }
91 | newN.next = curr;
92 | last.next = newN;
93 | }
94 |
95 | /** Delete the index-th node in the linked list, if the index is valid. */
96 | public void deleteAtIndex(int index) {
97 | if (index >= n || 0 > index) return;
98 | --n;
99 | if (n == 0) {
100 | head = null;
101 | tail = null;
102 | return;
103 | }
104 |
105 | if (index == 0) {
106 | head = head.next;
107 | return;
108 | }
109 |
110 | LinkedListNode curr = head;
111 | LinkedListNode last = null;
112 | for (int i = 0; i < index; ++i) {
113 | last = curr;
114 | curr = curr.next;
115 | }
116 | last.next = curr.next;
117 | if (index == n) {
118 | tail = last;
119 | }
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/src/DetectCapital.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/5/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class DetectCapital {
8 | public boolean detectCapitalUse(String word) {
9 | boolean allCap = Character.isUpperCase(word.charAt(0));
10 | boolean firstCap = allCap;
11 | boolean noCap = !allCap;
12 |
13 | int len = word.length();
14 | for (int i = 1; i < len; ++i) {
15 | boolean isLower = Character.isLowerCase(word.charAt(i));
16 | allCap &= !isLower;
17 | firstCap &= isLower;
18 | noCap &= isLower;
19 |
20 | if ((!allCap) && (!firstCap) && (!noCap)) return false;
21 | }
22 | return true;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/DiameterOfBinaryTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class DiameterOfBinaryTree {
8 |
9 | int res = 0;
10 | private int maxHeight(TreeNode n) {
11 | int l = (n.left != null) ? maxHeight(n.left) + 1 : 0;
12 | int r = (n.right != null) ? maxHeight(n.right) + 1 : 0;
13 |
14 | res = Math.max(res, l + r);
15 | return Math.max(l, r);
16 | }
17 | public int diameterOfBinaryTree(TreeNode root) {
18 | if (root == null) return 0;
19 | maxHeight(root);
20 | return res;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/DistributeCandies.java:
--------------------------------------------------------------------------------
1 | import java.util.HashSet;
2 | import java.util.Set;
3 |
4 | /**
5 | * @author Harry Tran on 6/30/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class DistributeCandies {
11 | public int distributeCandies_2(int[] candies) {
12 | int numC = candies.length;
13 | Set setC = new HashSet<>();
14 | for (int i = 0; i < numC; ++i)
15 | setC.add(candies[i]);
16 |
17 | return (setC.size() > numC / 2) ? numC / 2 : setC.size();
18 | }
19 | public int distributeCandies(int[] candies) {
20 | int numC = candies.length;
21 | int half = numC / 2;
22 | boolean[] marked = new boolean[200001];
23 | int cnt = 0;
24 | for (int i = 0; i < numC && cnt < half; ++i) {
25 | int ii = 100000 + candies[i];
26 | if (!marked[ii]) {
27 | marked[ii] = true;
28 | cnt++;
29 | }
30 | }
31 | return (cnt > half) ? half : cnt;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/EmployeeImportance.java:
--------------------------------------------------------------------------------
1 | import java.util.Comparator;
2 | import java.util.HashMap;
3 | import java.util.List;
4 |
5 | /**
6 | * @author Harry Tran on 7/5/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class EmployeeImportance {
12 |
13 | // Employee info
14 | class Employee {
15 | // It's the unique id of each node;
16 | // unique id of this employee
17 | public int id;
18 | // the importance value of this employee
19 | public int importance;
20 | // the id of direct subordinates
21 | public List subordinates;
22 | };
23 |
24 | HashMap map = new HashMap<>();
25 |
26 | private int getImportance_recursive(int id) {
27 | Employee e = map.get(id);
28 | int res = e.importance;
29 | int nSub = e.subordinates.size();
30 | for (int i = 0; i < nSub; ++i)
31 | res += getImportance_recursive(e.subordinates.get(i));
32 | return res;
33 | }
34 |
35 | public int getImportance(List employees, int id) {
36 | for (Employee e : employees)
37 | map.put(e.id, e);
38 | return getImportance_recursive(id);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/EncodeAndDecodeTinyurl.java:
--------------------------------------------------------------------------------
1 | import java.util.HashMap;
2 |
3 | /**
4 | * @author Harry Tran on 6/30/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class EncodeAndDecodeTinyurl {
10 | private HashMap data = new HashMap<>();
11 |
12 | // Encodes a URL to a shortened URL.
13 | public String encode(String longUrl) {
14 | int hashNum = longUrl.hashCode();
15 | String str = "http://tinyurl.com/" + Integer.toString(hashNum);
16 | data.put(hashNum, longUrl);
17 | return str;
18 | }
19 |
20 | // Decodes a shortened URL to its original URL.
21 | public String decode(String shortUrl) {
22 | String[] tmp = shortUrl.split("/");
23 | int hashNum = Integer.parseInt(tmp[3]);
24 | return data.get(hashNum);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/FindAllDuplicatesInArray.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | /**
5 | * @author Harry Tran on 6/30/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class FindAllDuplicatesInArray {
11 | public List findDuplicates(int[] nums) {
12 | ArrayList res = new ArrayList<>();
13 | // [4,3,2,7,8,2,3,1]
14 | /*
15 | ix = 3;
16 | [4,3,2,-7,8,2,3,1]
17 | idx = 2
18 | [4,3,-2,-7,8,2,3,1]
19 | idx = 1
20 | [4,-3,-2,-7,8,2,3,1]
21 | idx = 6
22 | [4,-3,-2,-7,8,2,-3,1]
23 | idx = 7
24 | [4,-3,-2,-7,8,2,-3,-1]
25 | idx = 1
26 | [4,-3,-2,-7,8,2,-3,-1] => add to res ...
27 | */
28 | int leng = nums.length;
29 | for (int i = 0; i < leng; ++i) {
30 | int idx = Math.abs(nums[i]) - 1;
31 | if (nums[idx] < 0) res.add(idx + 1);
32 | else
33 | nums[idx] *= -1;
34 | }
35 | return res;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/FindBottomLeftTreeValue.java:
--------------------------------------------------------------------------------
1 | import java.util.HashMap;
2 |
3 | /**
4 | * @author Harry Tran on 7/3/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class FindBottomLeftTreeValue {
10 | public class TreeNode {
11 | int val;
12 | TreeNode left;
13 | TreeNode right;
14 | TreeNode(int x) { val = x; }
15 | }
16 |
17 | HashMap map = new HashMap<>();
18 |
19 | private int dfs(TreeNode node, int level) {
20 | if (node == null) return level - 1;
21 |
22 | if (!map.containsKey(level)) {
23 | map.put(level, node);
24 | }
25 |
26 | return Math.max(dfs(node.left, level + 1), dfs(node.right, level + 1));
27 | }
28 | public int findBottomLeftValue(TreeNode root) {
29 | int height = dfs(root, 0);
30 | return map.get(height).val;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/FindLargestValueEachTreeRow.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.HashMap;
3 | import java.util.List;
4 |
5 | /**
6 | * @author Harry Tran on 7/4/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class FindLargestValueEachTreeRow {
12 |
13 | public class TreeNode {
14 | int val;
15 | TreeNode left;
16 | TreeNode right;
17 | TreeNode(int x) { val = x; }
18 | }
19 |
20 | HashMap mapResult = new HashMap<>();
21 |
22 | private void dfs(TreeNode node, int level) {
23 | mapResult.put(level, Math.max(node.val, mapResult.getOrDefault(level, Integer.MIN_VALUE)));
24 | if (node.left != null) dfs(node.left, level + 1);
25 | if (node.right != null) dfs(node.right, level + 1);
26 | }
27 |
28 | public List largestValues(TreeNode root) {
29 | if (root == null) return new ArrayList<>();
30 | dfs(root, 0);
31 | int height = mapResult.size();
32 | List res = new ArrayList<>();
33 | for (int i = 0; i < height; ++i)
34 | res.add(mapResult.get(i));
35 | return res;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/FindLongestChain.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 | import java.util.Comparator;
3 |
4 | /**
5 | * @author Harry Tran on 7/21/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class FindLongestChain {
11 | public int findLongestChain(int[][] pairs) {
12 | Arrays.sort(pairs, Comparator.comparingInt(o -> o[1]));
13 | int res = 0;
14 | int last = Integer.MIN_VALUE;
15 | int len = pairs.length;
16 | for (int i = 0; i < len; ++i)
17 | if (pairs[i][0] > last) {
18 | last = pairs[i][1];
19 | ++res;
20 | }
21 | return res;
22 | }
23 | public int findLongestChain2(int[][] pairs) {
24 | java.util.Arrays.sort(pairs, new java.util.Comparator() {
25 | @Override
26 | public int compare(int[] o1, int[] o2) {
27 | if (o1[0] != o2[0]) return o1[0] - o2[0];
28 | return o1[1] - o2[1];
29 | }
30 | });
31 | int len = pairs.length;
32 | // for (int i = 0; i < len; ++i) System.out.println(Integer.toString(pairs[i][0]) + " " + Integer.toString(pairs[i][1]));
33 |
34 | int[] f = new int[len];
35 | f[0] = 1;
36 | int res = 1;
37 | for (int i = 1; i < len; ++i) {
38 | f[i] = 1;
39 | for (int j = 0; j < i; ++j)
40 | if (pairs[j][1] < pairs[i][0]) {
41 | f[i] = Math.max(f[i], f[j] + 1);
42 | }
43 | res = Math.max(res, f[i]);
44 | }
45 | return res;
46 | }
47 |
48 | public static void main(String[] args) {
49 | int[][] pairs = {{9,10},{9,10},{4,5},{-9,-3},{-9,1},{0,3},{6,10},{-5,-4},{-7,-6}};
50 | FindLongestChain flc = new FindLongestChain();
51 | System.out.println(flc.findLongestChain(pairs));
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/FindModeInBST.java:
--------------------------------------------------------------------------------
1 | import com.sun.tools.javac.util.ArrayUtils;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * @author Harry Tran on 7/12/18.
8 | * @project Leetcode
9 | * @email trunghieu.tran@utdallas.edu
10 | * @organization UTDallas
11 | */
12 | public class FindModeInBST {
13 | List list = new ArrayList<>();
14 | int cnt = 0;
15 | int currVal = 19920704, c = -1;
16 | private void finding(TreeNode n) {
17 | if (n == null) return;
18 |
19 | finding(n.left);
20 |
21 | if (n.val == currVal) {
22 | ++c;
23 | } else {
24 | c = 1;
25 | currVal = n.val;
26 | }
27 |
28 | if (c > cnt) {
29 | cnt = c;
30 | list.clear();
31 | list.add(currVal);
32 |
33 | } else if (c == cnt) {
34 | list.add(currVal);
35 | }
36 |
37 |
38 | finding(n.right);
39 | }
40 |
41 | public int[] findMode(TreeNode root) {
42 | if (root == null) return new int[0];
43 |
44 | finding(root);
45 | int[] res = new int[list.size()];
46 | for (int i = 0; i < list.size(); ++i)
47 | res[i] = list.get(i);
48 | return res;
49 | }
50 |
51 | public static void main(String[] args) {
52 | TreeNode n0 = new TreeNode(1);
53 | TreeNode n1 = new TreeNode(2);
54 | TreeNode n2 = new TreeNode(2);
55 | n0.right = n1;
56 | n1.left = n2;
57 |
58 | FindModeInBST f = new FindModeInBST();
59 | f.findMode(n0);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/FindNumberOfLIS.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/21/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class FindNumberOfLIS {
8 | public int findNumberOfLIS(int[] nums) {
9 | int n = nums.length;
10 | if (n == 0) return 0;
11 |
12 | int[] f = new int[n]; // f[i] - longest sub-sequence ending at i
13 | int[] cnt = new int[n]; // cnt[i] - num of longest;
14 |
15 | f[0] = 1;
16 | cnt[0] = 1;
17 |
18 | int maxL = 1;
19 | int c = 1;
20 | for (int i = 1; i < n; ++i) {
21 | f[i] = 1;
22 | cnt[i] = 1;
23 | for (int j = 0; j < i; ++j)
24 | if (nums[j] < nums[i]) {
25 | if (f[j] + 1 > f[i]) {
26 | f[i] = f[j] + 1;
27 | cnt[i] = cnt[j];
28 | } else
29 | if (f[j] + 1 == f[i]) {
30 | cnt[i] += cnt[j];
31 | }
32 | }
33 | if (f[i] > maxL) {
34 | maxL = f[i];
35 | c = cnt[i];
36 | } else
37 | if (f[i] == maxL) {
38 | c += cnt[i];
39 | }
40 | }
41 | return c;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/FindTheDifference.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/10/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class FindTheDifference {
8 | public char findTheDifference(String s, String t) {
9 | int[] cnt = new int[26];
10 | for (char c : t.toCharArray())
11 | cnt[c - 'a']++;
12 | for (char c : s.toCharArray())
13 | cnt[c - 'a']--;
14 |
15 | for (int i = 0; i < 26; ++i)
16 | if (cnt[i] < 0) return (char) (i + 48);
17 | return 'a';
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/FizzBuzz.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | /**
5 | * @author Harry Tran on 6/30/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class FizzBuzz {
11 | public List fizzBuzz(int n) {
12 | List res = new ArrayList<>();
13 | for (int i = 1; i <= n; ++i)
14 | if (i % 3 != 0 && i % 5 != 0) res.add(Integer.toString(i));
15 | else
16 | if (i % 3 == 0 && i % 5 == 0) res.add("FizzBuzz");
17 | else
18 | if (i % 3 == 0) res.add("Fizz");
19 | else res.add("Buzz");
20 |
21 | return res;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/FizzBuzzMultiThreading.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | /**
5 | * @author Harry Tran on 10/5/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 |
11 | public class FizzBuzzMultiThreading {
12 |
13 | public static void main(String[] args) {
14 | List res = FizzBuzzMultiThreading.fizzBuzz(15);
15 | System.out.println("hi");
16 | for (String s : res) System.out.println(s);
17 | }
18 |
19 | public static List fizzBuzz(int n) {
20 | List res = new ArrayList<>();
21 | Thread[] threads = {new FizzBuzzThread(true, true, n, "FizzBuzz", res),
22 | new FizzBuzzThread(true, false, n, "Fizz", res),
23 | new FizzBuzzThread(false, true, n, "Buzz", res),
24 | new NumberThread(false, false, n, res)};
25 | for (Thread thread : threads) {
26 | thread.start();
27 | }
28 | return res;
29 | }
30 | }
--------------------------------------------------------------------------------
/src/FizzBuzzThread.java:
--------------------------------------------------------------------------------
1 | import java.util.List;
2 |
3 | /**
4 | * @author Harry Tran on 10/5/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class FizzBuzzThread extends Thread{
10 | private static Object lock = new Object();
11 | protected static int current = 1;
12 | protected static List res;
13 | private int max;
14 | private boolean div3, div5;
15 | private String toPrint;
16 |
17 | public FizzBuzzThread(boolean div3, boolean div5, int max, String toPrint, List res) {
18 | this.div3 = div3;
19 | this.div5 = div5;
20 | this.max = max;
21 | this.toPrint = toPrint;
22 | this.res = res;
23 | }
24 |
25 | public void addToRes() {
26 | res.add(toPrint);
27 | }
28 |
29 | public void run() {
30 | while (true) {
31 | synchronized(lock) {
32 | if (current > max) return;
33 | if ((current % 3 == 0) == div3 &&
34 | (current % 5 == 0) == div5) {
35 | addToRes();
36 | ++current;
37 | }
38 | }
39 | }
40 | }
41 | }
--------------------------------------------------------------------------------
/src/FlippingAnImage.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/27/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class FlippingAnImage {
8 | public int[][] flipAndInvertImage(int[][] A) {
9 | int lengthA = A.length;
10 | for (int i = 0; i < lengthA; ++i) {
11 | int left = 0;
12 | int right = A[i].length - 1;
13 | int tmp;
14 | while (left < right) {
15 | tmp = A[i][left];
16 | A[i][left] = 1 - A[i][right];
17 | A[i][right] = 1 - tmp;
18 | left++;
19 | right--;
20 | }
21 | if (left == right) A[i][left] = 1 - A[i][left];
22 | }
23 | return A;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/FourSum.java:
--------------------------------------------------------------------------------
1 | import javafx.util.Pair;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * @author Harry Tran on 10/20/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class FourSum {
12 | public List> fourSum(int[] nums, int target) {
13 | Arrays.sort(nums);
14 | Map>> map = new HashMap<>();
15 | int n = nums.length;
16 | for (int i = 0; i < n; ++i) {
17 | for (int j = i + 1; j < n; ++j) {
18 | int val = nums[i] + nums[j];
19 | if (!map.containsKey(val)) {
20 | map.put(val, new ArrayList<>());
21 | }
22 | map.get(val).add(new Pair<>(i, j));
23 | }
24 | }
25 |
26 | List> res = new ArrayList<>();
27 | for (int i = 0; i < n; ++i) {
28 | for (int j = i + 1; j < n; ++j) {
29 | int val = target - nums[i] - nums[j];
30 |
31 | if (map.containsKey(val)) {
32 | List> pairs = map.get(val);
33 | for (Pair p : pairs) {
34 |
35 | if (i == p.getKey() || i == p.getValue() ||
36 | j == p.getKey() || j == p.getValue()) continue;
37 | List r = Arrays.asList(nums[p.getKey()], nums[p.getValue()], nums[i], nums[j]);
38 | Collections.sort(r);
39 | res.add(r);
40 | }
41 | }
42 | }
43 | }
44 |
45 | Collections.sort(res, new Comparator>() {
46 |
47 | public int compare(List l1, List l2) {
48 | for (int i = 0; i < l1.size(); ++i)
49 | if (!Objects.equals(l1.get(i), l2.get(i)))
50 | return l1.get(i) - l2.get(i);
51 | return 0;
52 | }
53 |
54 | });
55 | for (List l : res) {
56 | for (int x : l)
57 | System.out.print(Integer.toString(x) + " ");
58 | System.out.println();
59 | }
60 | List> ans = new ArrayList<>();
61 | for (int i = 0; i < res.size(); ++i) {
62 | // // [98,218,352,389]
63 | // if (res.get(i).get(0) == 98 && res.get(i).get(1) == 218 ) {
64 | // for (int x : res.get(i))
65 | // System.out.print(x);
66 | // System.out.println();
67 | // }
68 | if (i == 0 || ans.isEmpty() || compare2List(res.get(i), ans.get(ans.size() - 1)) != 0) {
69 | ans.add(res.get(i));
70 | }
71 | }
72 | return ans;
73 | }
74 | public int compare2List(List l1, List l2) {
75 | for (int i = 0; i < l1.size(); ++i)
76 | if (!Objects.equals(l1.get(i), l2.get(i)))
77 | if (l1.get(i) < l2.get(i)) return -1;
78 | else return 1;
79 | // return l1.get(i) - l2.get(i);
80 | return 0;
81 | }
82 |
83 | public static void main(String[] args) {
84 | FourSum f = new FourSum();
85 | int[] arr = {-493,-470,-464,-453,-451,-446,-445,-407,-406,-393,-328,-312,-307,-303,-259,-253,-252,-243,-221,-193,-126,-126,-122,-117,-106,-105,-101,-71,-20,-12,3,4,20,20,54,84,98,111,148,149,152,171,175,176,211,218,227,331,352,389,410,420,448,485};
86 | int target = 1057;
87 | List> res = f.fourSum(arr, target);
88 | for (List l : res) {
89 | for (int x : l) System.out.print(Integer.toString(x) + " ");
90 | System.out.println();
91 | }
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/src/GenerateParentheses.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | /**
5 | * @author Harry Tran on 7/5/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class GenerateParentheses {
11 | List res = new ArrayList<>();
12 |
13 | private void recursion(int i, int nOpening, int n, char[] curr) {
14 | if (i == n * 2) {
15 | if (nOpening == 0) res.add(new String(curr));
16 | return;
17 | }
18 |
19 | if (nOpening < n) {
20 | curr[i] = '(';
21 | recursion(i + 1, nOpening + 1, n, curr);
22 | }
23 |
24 | if (nOpening > 0) {
25 | curr[i] = ')';
26 | recursion(i + 1, nOpening - 1, n, curr);
27 | }
28 | }
29 |
30 | public List generateParenthesis(int n) {
31 | char[] curr = new char[n * 2];
32 | recursion(0, 0, n, curr);
33 | return res;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/GoatLatin.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.Arrays;
3 | import java.util.HashSet;
4 |
5 | /**
6 | * @author Harry Tran on 7/1/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class GoatLatin {
12 | public String toGoatLatin(String S) {
13 | if (S.length() == 0) return S;
14 |
15 | HashSet vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
16 |
17 | String[] str = S.split(" ");
18 | StringBuilder res = new StringBuilder();
19 | for (int i = 0; i < str.length; ++i) {
20 | char chr = str[i].charAt(0);
21 | if (vowels.contains(chr)) {
22 | str[i] += "ma";
23 | } else {
24 | str[i] = str[i].substring(1, str[i].length()) + chr + "ma";
25 | }
26 | for (int j = 0; j < i + 1; ++j) str[i] += "a";
27 |
28 | if (i != 0) res.append(" ").append(str[i]);
29 | else res.append(str[i]);
30 | }
31 | return res.toString();
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/HammingDistance.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/27/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class HammingDistance {
8 | public int hammingDistance(int x, int y) {
9 | x = x^y;
10 | return Integer.bitCount(x);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/HouseRobber.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/21/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class HouseRobber {
8 | public int rob(int[] nums) {
9 | int len = nums.length;
10 | if (len == 0) return 0;
11 | if (len == 1) return nums[0];
12 | if (len == 2) return Math.max(nums[0], nums[1]);
13 | int[] f = new int[len];
14 | // f[i] - max value obtained when visiting the i-th house
15 | f[0] = nums[0];
16 | f[1] = Math.max(nums[0], nums[1]);
17 | for (int i = 2; i < len; ++i)
18 | f[i] = Math.max(f[i - 1], f[i - 2] + nums[i]);
19 | return f[len - 1];
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/ImplementStrStr.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/5/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ImplementStrStr {
8 | public int strStr(String haystack, String needle) {
9 | return haystack.indexOf(needle);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/IncreasingTriplet.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/21/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class IncreasingTriplet {
8 | public boolean increasingTriplet(int[] nums) {
9 | int n = nums.length;
10 | if (n < 3) return false;
11 | int v1 = nums[0];
12 | int v2 = 0;
13 | boolean v2Found = false;
14 | for (int i = 1; i < n; ++i) {
15 | if (v2Found) {
16 | if (nums[i] > v2) return true;
17 | if (nums[i] > v1)
18 | v2 = nums[i];
19 | else
20 | v1 = nums[i];
21 | } else {
22 | if (nums[i] > v1) {
23 | v2 = nums[i];
24 | v2Found = true;
25 | } else v1 = nums[i];
26 | }
27 | }
28 | return false;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/IntegerBreak.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/21/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class IntegerBreak {
8 |
9 | public int integerBreak(int n) {
10 | if (n == 2) return 1;
11 | if (n == 3) return 2;
12 | if (n == 4) return 4;
13 |
14 | double res = n;
15 | for (int i = 0; i <= n / 3; ++i) {
16 | int x = i * 3;
17 | int y = n - x;
18 | if (y % 2 != 0) continue;
19 | double t2 = Math.pow(2.0, y / 2);
20 | double t3 = Math.pow(3.0, i);
21 | res = Math.max(res, (int) t2 * t3);
22 | }
23 | return (int) res;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/InvertBinaryTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/1/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class InvertBinaryTree {
8 | public class TreeNode {
9 | int val;
10 | TreeNode left;
11 | TreeNode right;
12 | TreeNode(int x) { val = x; }
13 | }
14 |
15 | public TreeNode invertTree(TreeNode root) {
16 | if (root == null) return null;
17 | TreeNode tmp = new TreeNode(root.val);
18 | tmp.left = invertTree(root.right);
19 | tmp.right = invertTree(root.left);
20 | return tmp;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/IsSubtree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class IsSubtree {
8 |
9 |
10 | private boolean isSame(TreeNode s, TreeNode t) {
11 | if (s == null && t == null) return true;
12 | if (s == null) return false;
13 | if (t == null) return false;
14 | return s.val == t.val && isSame(s.left, t.left) && isSame(s.right, t.right);
15 | };
16 |
17 | public boolean isSubtree(TreeNode s, TreeNode t) {
18 | if (s == null && t == null) return true;
19 | if (s == null) return false;
20 | if (t == null) return false;
21 | return isSubtree(s.left, t) || isSubtree(s.right, t) || isSame(s, t);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/IslandPerimeter.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/30/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class IslandPerimeter {
8 |
9 | public int islandPerimeter(int[][] grid) {
10 | int[] h = {-1, 0, 0, 1};
11 | int[] c = {0, -1, 1, 0};
12 |
13 | int res = 0;
14 | int height = grid.length;
15 | int width = grid[0].length;
16 |
17 | for (int i = 0; i < height; ++i)
18 | for (int j = 0; j < width; ++j)
19 | if (grid[i][j] == 1) {
20 | for (int k = 0; k < 4; ++k) {
21 | int newi = i + h[k];
22 | int newj = j + c[k];
23 | if (newi < 0 || newi >= height || newj < 0 || newj >= width) ++res;
24 | else res += 1 - grid[newi][newj];
25 | }
26 | }
27 | return res;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/JewelsAndStones.java:
--------------------------------------------------------------------------------
1 | import java.util.HashSet;
2 |
3 | /**
4 | * @author Harry Tran on 6/27/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class JewelsAndStones {
10 | public int numJewelsInStones(String J, String S) {
11 | int res = 0;
12 | int lengthJ = J.length();
13 | int marked[] = new int[128];
14 |
15 | for (int i = 0; i < lengthJ; ++i) {
16 | marked[J.charAt(i)] = 1;
17 | }
18 |
19 | int lengthS = S.length();
20 | for (int i = 0; i < lengthS; ++i) {
21 | if (marked[S.charAt(i)]==1) ++res;
22 | }
23 | return res;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/JudgeRouteCircle.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/27/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class JudgeRouteCircle {
8 | public boolean judgeCircle(String moves) {
9 | int x = 0, y = 0;
10 | for (char chr : moves.toCharArray()) {
11 | if (chr == 'L') --x;
12 | else
13 | if (chr =='R') ++x;
14 | else
15 | if (chr == 'U') ++y;
16 | else --y;
17 | }
18 | return (x == 0 && y == 0);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/KeyboardRow.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 |
3 | /**
4 | * @author Harry Tran on 6/30/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class KeyboardRow {
10 | public String[] findWords(String[] words) {
11 | String[] rows = new String[]{
12 | "qwertyuiopQWERTYUIOP",
13 | "asdfghjklASDFGHJKL",
14 | "zxcvbnmZXCVBNM"
15 | };
16 |
17 | ArrayList result = new ArrayList<>();
18 | for (String str : words) {
19 | int row = 0;
20 | if (rows[1].indexOf(str.charAt(0)) != -1)
21 | row = 1;
22 | else
23 | if (rows[2].indexOf(str.charAt(0)) != -1)
24 | row = 2;
25 |
26 | boolean isOk = true;
27 | for (int i = 1; i < str.length(); ++i)
28 | if (rows[row].indexOf(str.charAt(i)) == -1) {
29 | isOk = false;
30 | break;
31 | }
32 | if (isOk) result.add(str);
33 | }
34 |
35 | return result.toArray(new String[result.size()]);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/KeysAndRooms.java:
--------------------------------------------------------------------------------
1 | import java.util.List;
2 |
3 | /**
4 | * @author Harry Tran on 6/30/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class KeysAndRooms {
10 |
11 | private void traverse(int curr, boolean[] marked, List> rooms) {
12 | for (int i = 0; i < rooms.get(curr).size(); ++i) {
13 | int next = rooms.get(curr).get(i);
14 | if (!marked[next]) {
15 | marked[next] = true;
16 | traverse(next, marked, rooms);
17 | }
18 | }
19 | }
20 | public boolean canVisitAllRooms(List> rooms) {
21 | int start = 0;
22 | boolean[] marked = new boolean[rooms.size()];
23 | marked[0] = true;
24 | traverse(0, marked, rooms);
25 | for (int i = 0; i < rooms.size(); ++i)
26 | if (!marked[i]) return false;
27 | return true;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/KickStart_Oct/A.java:
--------------------------------------------------------------------------------
1 | package KickStart_Oct;
2 |
3 | import java.io.*;
4 | import java.lang.reflect.Array;
5 | import java.util.*;
6 |
7 | /**
8 | * @author Harry Tran on 10/21/18.
9 | * @project Leetcode
10 | * @email trunghieu.tran@utdallas.edu
11 | * @organization UTDallas
12 | */
13 | public class A {
14 | public static String input = "/Study/Leetcode/src/KickStart_Oct/A-large-practice.in";
15 | public static String output = "/Study/Leetcode/src/KickStart_Oct/A-large.out";
16 |
17 | private static long process(int N, int[] a) {
18 | Arrays.sort(a);
19 | long res = 0;
20 | for (int i = 0; i < N; ++i) {
21 | Map map = new HashMap<>();
22 | for (int j = i + 1; j < N; ++j) {
23 | long tmp = (long)(a[i] * a[j]);
24 | boolean found = false;
25 | if (tmp <= 200000) {
26 | int key = (int) tmp;
27 | if (map.containsKey(key)) {
28 | res += (long)map.get(key);
29 | found = true;
30 | }
31 | }
32 | if (!found && a[i] > 0 && a[j] % a[i] == 0) {
33 | int key = a[j] / a[i];
34 | if (map.containsKey(key)) {
35 | res += (long) map.get(key);
36 | }
37 | }
38 | map.put(a[j], map.getOrDefault(a[j], 0) + 1);
39 | }
40 | }
41 | return res;
42 | }
43 |
44 | private static String template(int i, long res) {
45 | return "Case #" + Integer.toString(i) + ": " + Long.toString(res) + "\n";
46 | }
47 |
48 | public static void loadTest() {
49 | String data = readStringFromFile(input);
50 | String[] lines = data.split("\\n");
51 | int nTest = Integer.parseInt(lines[0]);
52 | int i = 0;
53 | int cc = 0;
54 | StringBuilder result = new StringBuilder();
55 | while (--nTest >= 0) {
56 | // Do something with test
57 | int n = Integer.parseInt(lines[++i]);
58 | int[] a = new int[n];
59 | String[] A = lines[++i].split(" ");
60 | for (int j = 0; j < n; ++j) {
61 | a[j] = Integer.parseInt(A[j]);
62 | }
63 | // Run
64 | long res = process(n, a);
65 | result.append(template(++cc, res));
66 | }
67 | writeStringToFile(output, result.toString());
68 | }
69 | public static String readStringFromFile(String inputFile) {
70 | try {
71 | BufferedInputStream in = new BufferedInputStream(new FileInputStream(inputFile));
72 | byte[] bytes = new byte[(int) new File(inputFile).length()];
73 | in.read(bytes);
74 | in.close();
75 | return new String(bytes);
76 | }
77 | catch (Exception e) {
78 | //e.printStackTrace();
79 | return null;
80 | }
81 | }
82 | public static void writeStringToFile(String outputFile, String data) {
83 | BufferedWriter writer = null;
84 | try
85 | {
86 | writer = new BufferedWriter( new FileWriter(outputFile));
87 | writer.write(data);
88 |
89 | }
90 | catch ( IOException e)
91 | {
92 | System.out.println("Writing error!!!");
93 | }
94 | finally
95 | {
96 | try
97 | {
98 | if ( writer != null)
99 | writer.close( );
100 | }
101 | catch ( IOException e)
102 | {
103 | System.out.println("Closing file error!!!");
104 | }
105 | }
106 | }
107 |
108 | public static void main(String[] args) {
109 | A.loadTest();
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/src/KickStart_Oct/A_old.java:
--------------------------------------------------------------------------------
1 | package KickStart_Oct;
2 |
3 | import java.io.*;
4 |
5 | /**
6 | * @author Harry Tran on 10/20/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class A_old {
12 |
13 | public static String input = "/Study/Leetcode/src/KickStart_Oct/A-large-practice.in";
14 | public static String output = "/Study/Leetcode/src/KickStart_Oct/A-large.out";
15 |
16 | private static int process(String A, String B, int L) {
17 | char[] a = A.toCharArray();
18 | char[] b = B.toCharArray();
19 |
20 | int res = 0;
21 | for (int i = 0; i < L; ++i)
22 | for (int j = i; j < L; ++j) {
23 | int le = j - i + 1;
24 |
25 | int[] count = new int[26];
26 | for (int k = i; k <= j; ++k) count[a[k] - 'A']++;
27 |
28 | boolean ok = false;
29 | for (int i2 = 0; i2 < L - le + 1; ++i2) {
30 | int[] count2 = new int[26];
31 |
32 | for (int j2 = i2; j2 <= i2 + le - 1; ++j2)
33 | count2[b[j2] - 'A']++;
34 |
35 | boolean found = true;
36 | for (int j2 = 0; j2 < 26; ++j2)
37 | if (count2[j2] != count[j2]) {
38 | found = false;
39 | break;
40 | }
41 |
42 | if (found) {
43 | ok = true;
44 | break;
45 | }
46 | }
47 | if (ok) ++res;
48 | }
49 | return res;
50 | }
51 |
52 | private static String template(int i, int res) {
53 | return "Case #" + Integer.toString(i) + ": " + Integer.toString(res) + "\n";
54 | }
55 |
56 | public static void loadTest() {
57 | String data = FileIO.readStringFromFile(input);
58 | String[] lines = data.split("\\n");
59 | int nTest = Integer.parseInt(lines[0]);
60 | int i = 0;
61 | int cc = 0;
62 | StringBuilder result = new StringBuilder();
63 | while (--nTest >= 0) {
64 | // Do something with test
65 | int L = Integer.parseInt(lines[++i]);
66 | String A = lines[++i];
67 | String B = lines[++i];
68 | int res = process(A, B, L);
69 | result.append(template(++cc, res));
70 | }
71 | FileIO.writeStringToFile(output, result.toString());
72 | }
73 |
74 |
75 |
76 | public static void main(String[] args) {
77 | A_old.loadTest();
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/KickStart_Oct/B-small.in:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/trunghieu-tran/LeetCode-Solutions-And-Data-Structure-Analysis/88ddc5c250f5bfbf273c484076d788e06146260f/src/KickStart_Oct/B-small.in
--------------------------------------------------------------------------------
/src/KickStart_Oct/B.java:
--------------------------------------------------------------------------------
1 | package KickStart_Oct;
2 |
3 | import javafx.util.Pair;
4 |
5 | import java.io.*;
6 | import java.util.ArrayList;
7 | import java.util.Collections;
8 | import java.util.Comparator;
9 | import java.util.List;
10 |
11 | /**
12 | * @author Harry Tran on 10/21/18.
13 | * @project Leetcode
14 | * @email trunghieu.tran@utdallas.edu
15 | * @organization UTDallas
16 | */
17 | public class B {
18 | public static String input = "/Study/Leetcode/src/KickStart_Oct/B-small-practice.in";
19 | public static String output = "/Study/Leetcode/src/KickStart_Oct/B-small.out";
20 |
21 | private static String template(int i, long res) {
22 | return "Case #" + Integer.toString(i) + ": " + Long.toString(res) + "\n";
23 | }
24 |
25 |
26 | public static long process(int n, int q, int[] l, int[] r, int[] k) {
27 | List > qs = new ArrayList<>();
28 | for (int i = 0; i < q; ++i) {
29 | qs.add(new Pair<>(k[i], i + 1));
30 | }
31 | Collections.sort(qs, new Comparator>() {
32 | @Override
33 | public int compare(Pair o1, Pair o2) {
34 | return o1.getKey() - o2.getKey();
35 | }
36 | });
37 |
38 | // for (Pair p : qs)
39 | // System.out.println(Integer.toString(p.getKey()) + " " + Integer.toString(p.getValue()));
40 |
41 | List> a = new ArrayList<>();
42 | for (int i = 0; i < n; ++i) {
43 | a.add(new Pair<>(l[i], 1));
44 | a.add(new Pair<>(r[i], -1));
45 | }
46 | Collections.sort(a, new Comparator>() {
47 | @Override
48 | public int compare(Pair o1, Pair o2) {
49 | if (o1.getKey().intValue() == o2.getKey().intValue())
50 | return o2.getValue() - o1.getValue();
51 | else
52 | return o1.getKey() - o2.getKey();
53 | }
54 | });
55 |
56 | // for (int i = 0; i < a.size(); ++i) {
57 | // System.out.print("(" + Integer.toString(a.get(i).getKey()) + " " + Integer.toString(a.get(i).getValue()) + ")");
58 | // }
59 | // System.out.println("\n");
60 |
61 | long res = 0;
62 | int j = 0; // for question
63 | int curr = 1;
64 | int opening = 1;
65 | int last = a.get(a.size() - 1).getKey();
66 |
67 | while (j < q && qs.get(j).getKey() <= curr) {
68 | res += (long)last * qs.get(j).getValue();
69 | ++j;
70 | }
71 |
72 | for (int i = a.size() - 2; i >= 0; --i) {
73 | if (j == q) break;
74 | if (a.get(i).getKey() < last) {
75 | if (opening > 0) {
76 | int first = a.get(i).getKey() + 1;
77 | long numStud = (long)(opening * (last - first));
78 | while (j < q && numStud + curr >= qs.get(j).getKey()) {
79 | int ll = first;
80 | int rr = last - 1;
81 | int pos = -1;
82 | while (ll <= rr) {
83 | int mid = (ll + rr) / 2;
84 | long xx = (long)((last - mid) * opening) + curr;
85 | if (xx >= qs.get(j).getKey()) {
86 | pos = mid;
87 | ll = mid + 1;
88 | } else rr = mid - 1;
89 | }
90 | if (pos == -1) System.out.println(-1);
91 | res += (long) (pos * qs.get(j).getValue());
92 | ++j;
93 | }
94 | curr += numStud;
95 | }
96 |
97 | last = a.get(i).getKey();
98 |
99 | if (a.get(i).getValue() < 0) opening++;
100 | curr += opening;
101 | while (j < q && curr >= qs.get(j).getKey()) {
102 | res += (long) last * qs.get(j).getValue();
103 | ++j;
104 | }
105 |
106 | if (a.get(i).getValue() > 0) {
107 | opening--;
108 | }
109 | } else {
110 | last = a.get(i).getKey();
111 | if (a.get(i).getValue() < 0) {
112 | curr++;
113 | opening++;
114 | }
115 | while (j < q && curr >= qs.get(j).getKey()) {
116 | res += (long) (last * qs.get(j).getValue());
117 | ++j;
118 | }
119 | if (a.get(i).getValue() > 0) {
120 | opening--;
121 | }
122 | }
123 | }
124 |
125 | return res;
126 | }
127 |
128 | public static void loadTest() {
129 | String data = readStringFromFile(input);
130 | String[] lines = data.split("\\n");
131 | int nTest = Integer.parseInt(lines[0]);
132 | int i = 0;
133 | int cc = 0;
134 | StringBuilder result = new StringBuilder();
135 | while (--nTest >= 0) {
136 | // Do something with test
137 | String[] line0 = lines[++i].split(" ");
138 | String[] line1 = lines[++i].split(" ");
139 | String[] line2 = lines[++i].split(" ");
140 | String[] line3 = lines[++i].split(" ");
141 |
142 | int n = Integer.parseInt(line0[0]);
143 | int q = Integer.parseInt(line0[1]);
144 |
145 | int[] l = new int[n + 3];
146 | int[] r = new int[n + 3];
147 | int[] k = new int[q + 3];
148 | long[] x = new long[n + 3];
149 | long[] y = new long[n + 3];
150 | long[] z = new long[q + 3];
151 |
152 | x[0] = Long.parseLong(line1[0]);
153 | x[1] = Long.parseLong(line1[1]);
154 | long a1 = Long.parseLong(line1[2]);
155 | long b1 = Long.parseLong(line1[3]);
156 | long c1 = Long.parseLong(line1[4]);
157 | long m1 = Long.parseLong(line1[5]);
158 |
159 | y[0] = Long.parseLong(line2[0]);
160 | y[1] = Long.parseLong(line2[1]);
161 | long a2 = Long.parseLong(line2[2]);
162 | long b2 = Long.parseLong(line2[3]);
163 | long c2 = Long.parseLong(line2[4]);
164 | long m2 = Long.parseLong(line2[5]);
165 |
166 | z[0] = Long.parseLong(line3[0]);
167 | z[1] = Long.parseLong(line3[1]);
168 | long a3 = Long.parseLong(line3[2]);
169 | long b3 = Long.parseLong(line3[3]);
170 | long c3 = Long.parseLong(line3[4]);
171 | long m3 = Long.parseLong(line3[5]);
172 |
173 | for (int ii = 2; ii < n; ++ii) {
174 | x[ii] = (a1 * x[ii - 1] + b1 * x[ii - 2] + c1) % m1;
175 | y[ii] = (a2 * y[ii - 1] + b2 * y[ii - 2] + c2) % m2;
176 | }
177 | for (int ii = 2; ii < q; ++ii) {
178 | z[ii] = (a3 * z[ii - 1] + b3 * z[ii - 2] + c3) % m3;
179 | }
180 |
181 | for (int ii = 0; ii < n; ++ii) {
182 | l[ii] = (int)(Math.min(x[ii], y[ii]) + 1);
183 | r[ii] = (int)(Math.max(x[ii], y[ii]) + 1);
184 | }
185 |
186 | for (int ii = 0; ii < q; ++ii) {
187 | k[ii] = (int)(z[ii] + 1);
188 | }
189 | // Run
190 | long res = process(n, q, l, r, k);
191 | result.append(template(++cc, res));
192 | }
193 | writeStringToFile(output, result.toString());
194 | }
195 | public static String readStringFromFile(String inputFile) {
196 | try {
197 | BufferedInputStream in = new BufferedInputStream(new FileInputStream(inputFile));
198 | byte[] bytes = new byte[(int) new File(inputFile).length()];
199 | in.read(bytes);
200 | in.close();
201 | return new String(bytes);
202 | }
203 | catch (Exception e) {
204 | //e.printStackTrace();
205 | return null;
206 | }
207 | }
208 | public static void writeStringToFile(String outputFile, String data) {
209 | BufferedWriter writer = null;
210 | try
211 | {
212 | writer = new BufferedWriter( new FileWriter(outputFile));
213 | writer.write(data);
214 |
215 | }
216 | catch ( IOException e)
217 | {
218 | System.out.println("Writing error!!!");
219 | }
220 | finally
221 | {
222 | try
223 | {
224 | if ( writer != null)
225 | writer.close( );
226 | }
227 | catch ( IOException e)
228 | {
229 | System.out.println("Closing file error!!!");
230 | }
231 | }
232 | }
233 |
234 | public static void main(String[] args) {
235 | B.loadTest();
236 | }
237 | }
238 |
--------------------------------------------------------------------------------
/src/KickStart_Oct/FileIO.java:
--------------------------------------------------------------------------------
1 | package KickStart_Oct;
2 | import java.io.*;
3 | import java.util.*;
4 |
5 | /**
6 | * @author Harry Tran on 5/23/18.
7 | * @project RecoverJSName
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class FileIO {
12 | public static String readStringFromFile(String inputFile) {
13 | try {
14 | BufferedInputStream in = new BufferedInputStream(new FileInputStream(inputFile));
15 | byte[] bytes = new byte[(int) new File(inputFile).length()];
16 | in.read(bytes);
17 | in.close();
18 | return new String(bytes);
19 | }
20 | catch (Exception e) {
21 | //e.printStackTrace();
22 | return null;
23 | }
24 | }
25 | public static void writeStringToFile(String outputFile, String data) {
26 | BufferedWriter writer = null;
27 | try
28 | {
29 | writer = new BufferedWriter( new FileWriter(outputFile));
30 | writer.write(data);
31 |
32 | }
33 | catch ( IOException e)
34 | {
35 | System.out.println("Writing error!!!");
36 | }
37 | finally
38 | {
39 | try
40 | {
41 | if ( writer != null)
42 | writer.close( );
43 | }
44 | catch ( IOException e)
45 | {
46 | System.out.println("Closing file error!!!");
47 | }
48 | }
49 | }
50 | public static ArrayList getAllSubdirectoryFromDirectory(String dir) {
51 | ArrayList res = new ArrayList<>();
52 | File file = new File(dir);
53 | String[] directories = file.list(new FilenameFilter() {
54 | @Override
55 | public boolean accept(File current, String name) {
56 | return new File(current, name).isDirectory();
57 | }
58 | });
59 | for (String str : directories) {
60 | res.add(dir + str + "/");
61 | }
62 | return res;
63 | }
64 |
65 | public static Set getAllFilesFromDirectory(String dir) {
66 | Set res = new HashSet<>();
67 | File root = new File(dir);
68 | try {
69 | File[] fs = root.listFiles();
70 | for (File f : fs)
71 | if (!f.isDirectory())
72 | res.add(f.getName());
73 | } catch (Exception e) {
74 | System.out.println(e.getMessage());
75 | }
76 | return res;
77 | }
78 |
79 | public static ArrayList getAllSubdirectoryFromDirectoryWithNumber(String dir, int num) {
80 | ArrayList res = new ArrayList<>();
81 | File file = new File(dir);
82 | String[] directories = file.list(new FilenameFilter() {
83 | @Override
84 | public boolean accept(File current, String name) {
85 | return new File(current, name).isDirectory();
86 | }
87 | });
88 |
89 | int cc = 0;
90 | for (String str : directories) {
91 | res.add(dir + str + "/");
92 | if (++cc >= num) break;
93 |
94 | }
95 | return res;
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/src/LargestTriangleArea.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/15/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class LargestTriangleArea {
8 | private double getArea(int[] p1, int[] p2, int[] p3) {
9 | return Math.abs(0.5 * (p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1])));
10 | }
11 | public double largestTriangleArea(int[][] points) {
12 | double res = 0.0;
13 |
14 | int len = points.length;
15 | for (int i = 0; i < len - 2; ++i)
16 | for (int j = i + 1; j < len - 1; ++j)
17 | for (int k = j + 1; k < len; ++k)
18 | res = Math.max(res, getArea(points[i], points[j], points[k]));
19 | return res;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/LetterCasePermutation.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | /**
5 | * @author Harry Tran on 7/2/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class LetterCasePermutation {
11 |
12 | private void finding(int pos, String curr, String S, ArrayList res) {
13 | if (pos == S.length()) {
14 | res.add(curr);
15 | return;
16 | }
17 |
18 | char chr = S.charAt(pos);
19 |
20 | if (Character.isDigit(chr)) finding(pos + 1, curr + chr, S, res);
21 | else {
22 | finding(pos + 1, curr + Character.toUpperCase(chr), S, res);
23 | finding(pos + 1, curr + Character.toLowerCase(chr), S, res);
24 | }
25 | }
26 | public List letterCasePermutation(String S) {
27 | ArrayList res = new ArrayList<>();
28 | finding(0, "", S, res);
29 | return res;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/LevelOrderBottom.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayDeque;
2 | import java.util.ArrayList;
3 | import java.util.List;
4 |
5 | /**
6 | * @author Harry Tran on 7/12/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class LevelOrderBottom {
12 | public List> levelOrderBottom(TreeNode root) {
13 | // List> res = new ArrayList<>();
14 |
15 | ArrayDeque> res = new ArrayDeque<>();
16 | if (root != null) {
17 | List list = new ArrayList<>();
18 | list.add(root);
19 |
20 | List first = new ArrayList<>();
21 | first.add(root.val);
22 | res.addFirst(first);
23 |
24 | while (list.size() > 0) {
25 | List newList = new ArrayList<>();
26 | List varList = new ArrayList<>();
27 |
28 | for (int i = 0; i < list.size(); ++i) {
29 | TreeNode left = list.get(i).left;
30 | TreeNode right = list.get(i).right;
31 | if (left != null) {
32 | newList.add(left);
33 | varList.add(left.val);
34 | }
35 | if (right != null) {
36 | newList.add(right);
37 | varList.add(right.val);
38 | }
39 | }
40 |
41 | list = newList;
42 | if (list.size() > 0) {
43 | res.addFirst(varList);
44 | }
45 | }
46 | }
47 | return new ArrayList<>(res);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/ListNode.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ListNode {
8 | int val;
9 | ListNode next;
10 | ListNode(int x) { val = x; }
11 | }
12 |
--------------------------------------------------------------------------------
/src/LongestContinuousIncreasingSubsequence.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/21/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class LongestContinuousIncreasingSubsequence {
8 | public int findLengthOfLCIS(int[] nums) {
9 | int n = nums.length;
10 | if (n == 0) return 0;
11 | int res = 1;
12 | int i = 0;
13 | while (i < n) {
14 | int j = i + 1;
15 | while (j < n && nums[j] > nums[j - 1]) ++j;
16 | res = Math.max(res, j - i);
17 | i = j;
18 | }
19 | return res;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/LongestIncreasingSubsequence.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 |
3 | /**
4 | * @author Harry Tran on 7/21/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class LongestIncreasingSubsequence {
10 | public int lengthOfLIS(int[] nums) {
11 | int len = nums.length;
12 | if (len == 0) return 0;
13 |
14 | int[] val = new int[len]; // val[i] - last value of the sub-sequence of length = i
15 | int size = 1;
16 | val[0] = nums[0];
17 |
18 | for (int i = 1; i < len; ++i) {
19 | int k = Arrays.binarySearch(val, 0, size, nums[i]);
20 | // if k < 0, we have index: -1, -2, -3 .... .
21 | // Thus, to recover the real index, k = -(k + 1)
22 | if (k < 0) {
23 | k = -(k + 1);
24 | }
25 | val[k] = nums[i];
26 | if (k == size) {
27 | ++size;
28 | }
29 | }
30 | return size;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/LongestSubstring.java:
--------------------------------------------------------------------------------
1 | import java.util.HashMap;
2 |
3 | /**
4 | * @author Harry Tran on 6/25/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class LongestSubstring {
10 | public int lengthOfLongestSubstring(String s) {
11 | HashMap map = new HashMap<>();
12 | int res = 0;
13 | for (int i = 0, j = 0; j < s.length(); ++j) {
14 | if (map.containsKey(s.charAt(j))) {
15 | i = Math.max(i, map.get(s.charAt(j)) + 1);
16 | }
17 | map.put(s.charAt(j), j);
18 | res = Math.max(res, j - i + 1);
19 | }
20 | return res;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/LongestUncommonSubsequence1.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/1/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class LongestUncommonSubsequence1 {
8 | public int findLUSlength(String a, String b) {
9 | return a.equals(b) ? -1 : Math.max(a.length(), b.length());
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/LongestUnivaluePath.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class LongestUnivaluePath {
8 |
9 | int res = 0;
10 | private int findLongestPathSubtreeContainsItself(TreeNode n) {
11 | int tmp1 = 0;
12 | int tmp2 = 0;
13 | if (n.left != null) {
14 | int x = findLongestPathSubtreeContainsItself(n.left);
15 | if (n.val == n.left.val)
16 | tmp1 = x + 1;
17 | }
18 | if (n.right != null) {
19 | int x = findLongestPathSubtreeContainsItself(n.right);
20 | if (n.val == n.right.val)
21 | tmp2 = x + 1;
22 | }
23 | res = Math.max(res, tmp1 + tmp2);
24 | return Math.max(tmp1, tmp2);
25 | }
26 |
27 | public int longestUnivaluePath(TreeNode root) {
28 | if (root != null)
29 | findLongestPathSubtreeContainsItself(root);
30 | return res;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/LowestCommonAncestor.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class LowestCommonAncestor {
8 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
9 | if (p.val < root.val && q.val < root.val) return lowestCommonAncestor(root.left, p, q);
10 | if (p.val > root.val && q.val > root.val) return lowestCommonAncestor(root.right, p, q);
11 | return root;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/MajorityElement.java:
--------------------------------------------------------------------------------
1 | import java.util.HashMap;
2 | import java.util.Map;
3 |
4 | /**
5 | * @author Harry Tran on 7/4/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class MajorityElement {
11 | public int majorityElement(int[] nums) {
12 | Map map = new HashMap<>();
13 | int len = nums.length;
14 | for (int i = 0; i < len; ++i)
15 | map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
16 | for (int key : map.keySet())
17 | if (map.get(key) > len / 2) return key;
18 | return 0;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/MaxAreaOfIsland.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/2/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class MaxAreaOfIsland {
8 | private static int height = 0;
9 | private static int width = 0;
10 | private static boolean[][] marked;
11 | private static int[] h = {-1, 0, 0, 1};
12 | private static int[] c = {0, -1, 1, 0};
13 |
14 | private boolean isOk(int i, int j) {
15 | return (0 <= i && i < height && 0 <= j && j < width && !marked[i][j]);
16 | }
17 |
18 | private int BFS(int i, int j, int[][] grid) {
19 | int cnt = 1;
20 | for (int k = 0; k < 4; ++k) {
21 | int ii = h[k] + i;
22 | int jj = c[k] + j;
23 | if (!isOk(ii, jj)) continue;
24 | marked[ii][jj] = true;
25 | if (grid[ii][jj] == 1) {
26 | cnt += BFS(ii, jj, grid);
27 | }
28 | }
29 | return cnt;
30 | }
31 |
32 | public int maxAreaOfIsland(int[][] grid) {
33 | height = grid.length;
34 | width = grid[0].length;
35 | marked = new boolean[height][width];
36 |
37 | int res = 0;
38 | for (int i = 0; i < height; ++i)
39 | for (int j = 0; j < width; ++j)
40 | if (grid[i][j] == 1 && !marked[i][j]) res = Math.max(res, BFS(i, j, grid));
41 | return res;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/MaxBinaryTree.java:
--------------------------------------------------------------------------------
1 | import javafx.util.Pair;
2 |
3 | /**
4 | * @author Harry Tran on 6/30/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class MaxBinaryTree {
10 | public class TreeNode {
11 | int val;
12 | TreeNode left;
13 | TreeNode right;
14 | TreeNode(int x) { val = x; }
15 | }
16 |
17 | private int[] p = new int[4000];
18 |
19 | private void build(int [] nums, int left, int right, int node) {
20 | if (left == right) {
21 | p[node] = left;
22 | return;
23 | }
24 | int mid = (left + right) / 2;
25 | build(nums, left, mid, node * 2);
26 |
27 | p[node] = p[node * 2];
28 |
29 | if (mid < right) {
30 | build(nums, mid + 1, right, node * 2 + 1);
31 | if (nums[p[node]] < nums[p[node * 2 + 1]]) {
32 | p[node] = p[node * 2 + 1];
33 | }
34 | }
35 | }
36 |
37 | private int get(int[] nums, int node, int left, int right, int u, int v) {
38 | if (left > v || right < u) return -1;
39 | if (u <= left && right <= v) return p[node];
40 | int mid = (left + right) / 2;
41 | int res = -1;
42 |
43 | int p1 = get(nums, node * 2, left, mid, u, v);
44 | if (p1 != -1) {
45 | res = p1;
46 | }
47 |
48 | if (mid < right) {
49 | int p2 = get(nums, node * 2 + 1, mid + 1, right, u, v);
50 | if (p2 != -1) {
51 | if (res == -1 || nums[res] < nums[p2]) {
52 | res = p2;
53 | }
54 | }
55 |
56 | }
57 | return res;
58 | }
59 |
60 | private TreeNode construct(int[] nums, int left, int right) {
61 | // int mid = get(nums, 1, 0, nums.length - 1, left, right);
62 | int mid = getMax(nums, left, right);
63 | TreeNode res = new TreeNode(nums[mid]);
64 | if (left < mid)
65 | res.left = construct(nums, left, mid - 1);
66 | if (mid < right)
67 | res.right = construct(nums, mid + 1, right);
68 | return res;
69 | }
70 |
71 | private int getMax(int[] nums, int left, int right) {
72 | int res = left;
73 | for (int i = left + 1; i <= right; ++i)
74 | if (nums[i] > nums[res]) res = i;
75 | return res;
76 | }
77 | public TreeNode constructMaximumBinaryTree(int[] nums) {
78 | build(nums, 0, nums.length - 1, 1);
79 | return construct(nums, 0, nums.length - 1);
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/MaxConsecutiveOnes.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/2/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class MaxConsecutiveOnes {
8 | public int findMaxConsecutiveOnes(int[] nums) {
9 | int len = nums.length;
10 |
11 | if (len == 0) return 0;
12 |
13 | int last0 = -1;
14 | int res = 0;
15 | for (int i = 0; i < len; i++) {
16 | if (nums[i] == 0) {
17 | res = Math.max(i - 1 - last0, res);
18 | last0 = i;
19 | }
20 | }
21 | if (nums[len - 1] == 1) {
22 | res = Math.max(res, len - 1 - last0);
23 | }
24 | return res;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/MaxIncreaseKeepCitySkyline.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/30/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class MaxIncreaseKeepCitySkyline {
8 | public int maxIncreaseKeepingSkyline(int[][] grid) {
9 | int size = grid.length;
10 | int[] topBottom = new int[size];
11 | int[] leftRight = new int[size];
12 |
13 | for (int i = 0; i < size; ++i)
14 | for (int j = 0; j < size; ++j) {
15 | topBottom[j] = Math.max(topBottom[j], grid[i][j]);
16 | leftRight[i] = Math.max(leftRight[i], grid[i][j]);
17 | }
18 | int res = 0;
19 | for (int i = 0; i < size; ++i)
20 | for (int j = 0; j < size; ++j)
21 | res += Math.min(topBottom[j], leftRight[i]) - grid[i][j];
22 | return res;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/MaxProfit.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/18/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class MaxProfit {
8 | public int maxProfit(int[] prices) {
9 | int maxProfit = 0;
10 | int len = prices.length;
11 | if (len <= 1) return maxProfit;
12 |
13 | int vmin = prices[0];
14 | for (int i = 1; i < len; ++i) {
15 | maxProfit = Math.max(maxProfit, prices[i] - vmin);
16 | vmin = Math.min(vmin, prices[i]);
17 | }
18 | return maxProfit;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/MaxSubArray.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/18/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class MaxSubArray {
8 | public int maxSubArray(int[] nums) {
9 | int n = nums.length;
10 | if (n == 0) return 0;
11 | int res = nums[0];
12 | int sum = nums[0];
13 | int sumMin = nums[0];
14 | for (int i = 1; i < n; ++i) {
15 | sum += nums[i];
16 | if (res < nums[i])
17 | res = nums[i];
18 | if (res < sum - sumMin)
19 | res = sum - sumMin;
20 | if (res < sum)
21 | res = sum;
22 | // res = Math.max(nums[i], res);
23 | // res = Math.max(sum - sumMin, res);
24 | // res = Math.max(sum, res);
25 | sumMin = Math.min(sumMin, sum);
26 | }
27 | return res;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/MaximumDepthBinaryTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/1/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class MaximumDepthBinaryTree {
8 | public class TreeNode {
9 | int val;
10 | TreeNode left;
11 | TreeNode right;
12 | TreeNode(int x) { val = x; }
13 | }
14 |
15 | public int maxDepth(TreeNode root) {
16 | if (root == null) return 0;
17 |
18 | return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/MedianFinder.java:
--------------------------------------------------------------------------------
1 | import java.util.Comparator;
2 | import java.util.PriorityQueue;
3 | import java.util.Queue;
4 |
5 | /**
6 | * @author Harry Tran on 9/30/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class MedianFinder {
12 | Queue maxLow;
13 | Queue minHi;
14 | /** initialize your data structure here. */
15 | public MedianFinder() {
16 | maxLow = new PriorityQueue<>();
17 | minHi = new PriorityQueue<>(Comparator.reverseOrder());
18 | }
19 |
20 | private void balance() {
21 | while (maxLow.size() < minHi.size()) {
22 | maxLow.offer(minHi.poll());
23 | }
24 | while (maxLow.size() > minHi.size() + 1) {
25 | minHi.offer(maxLow.poll());
26 | }
27 | }
28 |
29 | public void addNum(int num) {
30 | if (maxLow.isEmpty()) {
31 | maxLow.add(num);
32 | } else
33 | if (minHi.isEmpty()) {
34 | minHi.add(num);
35 | } else {
36 | int vmaxL = maxLow.peek();
37 | if (num <= vmaxL) maxLow.offer(num);
38 | else minHi.offer(num);
39 | }
40 | balance();
41 | }
42 |
43 | public double findMedian() {
44 | double res = 0.0;
45 | if (maxLow.size() > 0) {
46 | if (maxLow.size() == minHi.size())
47 | res = (maxLow.peek() + minHi.peek()) / 2;
48 | else
49 | res = maxLow.peek();
50 | }
51 | return res;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/Merge2BTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/27/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class Merge2BTree {
8 |
9 | public class TreeNode {
10 | int val;
11 | TreeNode left;
12 | TreeNode right;
13 | TreeNode(int x) { val = x; }
14 | }
15 |
16 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
17 | if (t1==null) return t2;
18 | if (t2==null) return t1;
19 | TreeNode newNode = new TreeNode(t1.val + t2.val);
20 | newNode.right = mergeTrees(t1.right, t2.right);
21 | newNode.left = mergeTrees(t1.left, t2.left);
22 | return newNode;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/MinCostClimbingStairs.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/17/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class MinCostClimbingStairs {
8 | public int minCostClimbingStairs(int[] cost) {
9 | int len = cost.length;
10 | if (len == 2) return Math.min(cost[0], cost[1]);
11 |
12 | int[] f = new int[len];
13 | for (int i = 2; i < len; ++i)
14 | f[i] = Math.min(f[i - 1] + cost[i - 1], f[i - 2] + cost[i - 2]);
15 | return Math.min(f[len - 1] + cost[len - 1], f[len - 2] + cost[len - 2]);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/MinDepth.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class MinDepth {
8 | public int minDepth(TreeNode root) {
9 | if (root == null) return 0;
10 | int left = minDepth(root.left) + 1;
11 | int right = minDepth(root.right) + 1;
12 | return Math.min(left, right);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/MinimumDeleteSum.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/21/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class MinimumDeleteSum {
8 | public int minimumDeleteSum(String s1, String s2) {
9 | int n1 = s1.length();
10 | int n2 = s2.length();
11 | int[][] f = new int[n1][n2];
12 | int sum1 = (int) s1.charAt(0);
13 | int sum2 = (int) s2.charAt(0);
14 |
15 | f[0][0] = s1.charAt(0) == s2.charAt(0) ? (int) s1.charAt(0) : 0;
16 | for (int i = 1; i < n1; ++i) {
17 | f[i][0] = s1.charAt(i) == s2.charAt(0) ? (int) s1.charAt(i) : 0;
18 | f[i][0] = Math.max(f[i][0], f[i - 1][0]);
19 | sum1 += (int) s1.charAt(i);
20 | }
21 | for (int j = 1; j < n2; ++j) {
22 | f[0][j] = s1.charAt(0) == s2.charAt(j) ? (int) s2.charAt(j) : 0;
23 | f[0][j] = Math.max(f[0][j], f[0][j - 1]);
24 | sum2 += (int) s2.charAt(j);
25 | }
26 |
27 | for (int i = 1; i < n1; ++i)
28 | for (int j = 1; j < n2; ++j) {
29 | f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
30 | if (s1.charAt(i) == s2.charAt(j))
31 | f[i][j] = Math.max(f[i][j], f[i - 1][j - 1] + (int) s1.charAt(i));
32 | }
33 |
34 | return sum1 - 2 * f[n1 - 1][n2 - 1] + sum2;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/MinimumMovesToEqualArray.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/5/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class MinimumMovesToEqualArray {
8 | public int minMoves(int[] nums) {
9 | int n = nums.length;
10 | int sum = 0, min = Integer.MAX_VALUE;
11 | for (int i = 0; i < n; ++i) {
12 | sum += nums[i];
13 | min = Math.min(min, nums[i]);
14 | }
15 | return sum - min * n;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/MinimumMovesToEqualArrayII.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 |
3 | /**
4 | * @author Harry Tran on 7/5/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class MinimumMovesToEqualArrayII {
10 | public int minMoves2(int[] nums) {
11 | int res = 0;
12 | int i = 0, j = nums.length - 1;
13 | Arrays.sort(nums);
14 | while (i < j) {
15 | res += nums[j--] - nums[i++];
16 | }
17 | return res;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/MostFrequentSubtreeSum.java:
--------------------------------------------------------------------------------
1 | import java.util.HashMap;
2 | import java.util.Map;
3 |
4 | /**
5 | * @author Harry Tran on 7/4/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class MostFrequentSubtreeSum {
11 | public class TreeNode {
12 | int val;
13 | TreeNode left;
14 | TreeNode right;
15 | TreeNode(int x) { val = x; }
16 | }
17 |
18 | Map map = new HashMap<>();
19 |
20 | private int traverse(TreeNode node) {
21 | if (node == null) return 0;
22 |
23 | int sum = node.val + traverse(node.left) + traverse(node.right);
24 | map.put(sum, map.getOrDefault(sum , 0) + 1);
25 | return sum;
26 | }
27 |
28 | public int[] findFrequentTreeSum(TreeNode root) {
29 | if (root == null) return new int[0];
30 |
31 | int x = traverse(root);
32 | int cnt = 1, best = 0;
33 | for (int key : map.keySet()) {
34 | int freq = map.get(key);
35 | if (freq > best) {
36 | best = freq;
37 | cnt = 1;
38 | } else
39 | if (freq == best) cnt++;
40 | }
41 | int[] res = new int[cnt];
42 | int i = 0;
43 | for (int key : map.keySet())
44 | if (map.get(key) == best)
45 | res[i++] = key;
46 | return res;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/MoveZeroes.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/2/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class MoveZeroes {
8 |
9 | public void moveZeroes(int[] nums) {
10 | int len = nums.length;
11 | int cnt = 0;
12 | for (int i = 0; i < len; ++i)
13 | if (nums[i] != 0) nums[cnt++] = nums[i];
14 | for (int i = cnt; i < len; ++i) nums[i] = 0;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/MyCircularDeque.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayDeque;
2 | import java.util.Deque;
3 | import java.util.LinkedList;
4 |
5 | /**
6 | * @author Harry Tran on 7/15/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class MyCircularDeque {
12 | Deque data;
13 | int capability;
14 |
15 | /** Initialize your data structure here. Set the size of the deque to be k. */
16 | public MyCircularDeque(int k) {
17 | data = new ArrayDeque<>(k);
18 | capability = k;
19 | }
20 |
21 | /** Adds an item at the front of Deque. Return true if the operation is successful. */
22 | public boolean insertFront(int value) {
23 | if (isFull()) return false;
24 | try {
25 | data.addFirst(value);
26 | return true;
27 | } catch (Exception e) {
28 | return false;
29 | }
30 | }
31 |
32 | /** Adds an item at the rear of Deque. Return true if the operation is successful. */
33 | public boolean insertLast(int value) {
34 | if (isFull()) return false;
35 | try {
36 | data.addLast(value);
37 | return true;
38 | } catch (Exception e) {
39 | return false;
40 | }
41 | }
42 |
43 | /** Deletes an item from the front of Deque. Return true if the operation is successful. */
44 | public boolean deleteFront() {
45 | if (isEmpty()) return false;
46 | try {
47 | data.removeFirst();
48 | return true;
49 | } catch (Exception e) {
50 | return false;
51 | }
52 | }
53 |
54 | /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
55 | public boolean deleteLast() {
56 | if (isEmpty()) return false;
57 | try {
58 | data.removeLast();
59 | return true;
60 | } catch (Exception e) {
61 | return false;
62 | }
63 | }
64 |
65 | /** Get the front item from the deque. */
66 | public int getFront() {
67 | if (isEmpty()) return -1;
68 | try {
69 | return data.getFirst();
70 | } catch (Exception e) {
71 | return -1;
72 | }
73 | }
74 |
75 | /** Get the last item from the deque. */
76 | public int getRear() {
77 | if (isEmpty()) return -1;
78 | try {
79 | return data.getLast();
80 | } catch (Exception e) {
81 | return -1;
82 | }
83 |
84 | }
85 |
86 | /** Checks whether the circular deque is empty or not. */
87 | public boolean isEmpty() {
88 | return data.isEmpty();
89 | }
90 |
91 | /** Checks whether the circular deque is full or not. */
92 | public boolean isFull() {
93 | return data.size() == capability;
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/src/MyCircularQueue2.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/20/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class MyCircularQueue2 {
8 | int[] data;
9 | int last;
10 | int first;
11 | int size;
12 | /** Initialize your data structure here. Set the size of the queue to be k. */
13 | public MyCircularQueue2(int k) {
14 | data = new int[k];
15 | size = k;
16 | last = 0;
17 | first = 0;
18 | }
19 |
20 | /** Insert an element into the circular queue. Return true if the operation is successful. */
21 | public boolean enQueue(int value) {
22 | if (isFull()) return false;
23 | data[last++ % size] = value;
24 | return true;
25 | }
26 |
27 | /** Delete an element from the circular queue. Return true if the operation is successful. */
28 | public boolean deQueue() {
29 | if (isEmpty()) return false;
30 | ++first;
31 | return true;
32 | }
33 |
34 | /** Get the front item from the queue. */
35 | public int Front() {
36 | if (isEmpty()) return -1;
37 | return data[first % size];
38 | }
39 |
40 | /** Get the last item from the queue. */
41 | public int Rear() {
42 | if (isEmpty()) return -1;
43 | return data[(last-1) % size];
44 | }
45 |
46 | /** Checks whether the circular queue is empty or not. */
47 | public boolean isEmpty() {
48 | return last == first;
49 | }
50 |
51 | /** Checks whether the circular queue is full or not. */
52 | public boolean isFull() {
53 | return last - first == size;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/NQueens.java:
--------------------------------------------------------------------------------
1 | import javafx.util.Pair;
2 |
3 | import java.util.*;
4 |
5 | /**
6 | * @author Harry Tran on 7/10/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class NQueens {
12 | List> res = new ArrayList<>();
13 | int[] row;
14 | int[] col;
15 | int[] diag;
16 | int[] diag2;
17 | int N;
18 |
19 | private void recursive(int i, int lastX, char[][] curr) {
20 | if (i == N) {
21 | List tmp = new ArrayList<>();
22 | for (char[] chrs : curr) {
23 | String str = String.valueOf(chrs);
24 | tmp.add(str);
25 | }
26 | res.add(tmp);
27 | return;
28 | }
29 |
30 | int x = lastX + 1;
31 | if (row[x] == 0)
32 | for (int y = 0; y < N; ++y)
33 | if (col[y] == 0) {
34 | int d = x + y;
35 | int d2 = x - y + (N - 1); //row - col + (N - 1)
36 | if (diag[d] == 0 && diag2[d2] == 0) {
37 | diag[d] = 1;
38 | diag2[d2] = 1;
39 | row[x] = 1;
40 | col[y] = 1;
41 | curr[x][y] = 'Q';
42 |
43 | recursive(i + 1, x, curr);
44 |
45 | diag[d] = 0;
46 | diag2[d2] = 0;
47 | row[x] = 0;
48 | col[y] = 0;
49 | curr[x][y] = '.';
50 | }
51 | }
52 | }
53 |
54 | public List> solveNQueens(int n) {
55 | this.N = n;
56 | row = new int[N];
57 | col = new int[N];
58 | diag = new int[N * 2 + 1];
59 | diag2 = new int[N * 2 + 1];
60 | char[][] curr = new char[N][N];
61 | for (int i = 0; i < N; ++i)
62 | for (int j = 0; j < N; ++j)
63 | curr[i][j] = '.';
64 | recursive(0, -1, curr);
65 | return res;
66 | }
67 |
68 | public static void main(String[] args) {
69 | NQueens nq = new NQueens();
70 | List> res = nq.solveNQueens(14);
71 | System.out.println(res.size());
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/NextGreaterElementI.java:
--------------------------------------------------------------------------------
1 | import java.util.HashMap;
2 |
3 | /**
4 | * @author Harry Tran on 7/1/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class NextGreaterElementI {
10 | public int[] nextGreaterElement(int[] nums1, int[] nums2) {
11 | int len1 = nums1.length;
12 | int len2 = nums2.length;
13 |
14 | if (nums1.length == 0) return nums1;
15 |
16 | HashMap next = new HashMap<>();
17 |
18 | next.put(nums2[len2 - 1], -1);
19 |
20 | for (int i = len2 - 2; i >= 0; --i) {
21 | int j = nums2[i + 1];
22 | while (j != -1 && nums2[i] > j) j = next.getOrDefault(j, -1);
23 | next.put(nums2[i], j);
24 | }
25 |
26 | int[] res = new int[len1];
27 | for (int i = 0; i < len1; ++i)
28 | res[i] = next.getOrDefault(nums1[i], -1);
29 | return res;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/NimGame.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/1/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class NimGame {
8 | public boolean canWinNim(int n) {
9 | return (n % 4 != 0);
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/NonDecreasingArray.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/4/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class NonDecreasingArray {
8 | public boolean checkPossibility_2(int[] nums) {
9 | int len = nums.length;
10 | int pos = -1;
11 |
12 |
13 | for (int i = 0; i < len - 1; ++i) {
14 | if (nums[i] > nums[i + 1]) {
15 | if (pos != -1) return false;
16 | pos = i;
17 | }
18 | }
19 | return pos == -1 || pos == 0 || pos == len - 2 ||
20 | nums[pos - 1] <= nums[pos + 1] || nums[pos] <= nums[pos + 2];
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/NumArray.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/21/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class NumArray {
8 | int[] f;
9 | public NumArray(int[] nums) {
10 | int len = nums.length;
11 | f = new int[len];
12 | if (len == 0) return;
13 | f[0] = nums[0];
14 | for (int i = 1; i < len; ++i)
15 | f[i] = f[i - 1] + nums[i];
16 | }
17 |
18 | public int sumRange(int i, int j) {
19 | if (f.length == 0) return 0;
20 | if (i < 0) i = 0;
21 | if (j >= f.length) j = f.length - 1;
22 | if (i == 0) return f[j];
23 | else return f[j] - f[i - 1];
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/NumOfLineToWriteString.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/29/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class NumOfLineToWriteString {
8 | public int[] numberOfLines(int[] widths, String S) {
9 | int numLine = 1;
10 | int lastLine = 0;
11 | for (char ch : S.toCharArray()) {
12 | int size = widths[ch - 'a'];
13 | if (lastLine + size <= 100) lastLine += size;
14 | else {
15 | lastLine = size;
16 | numLine++;
17 | }
18 | }
19 | return new int[]{numLine, lastLine};
20 | }
21 | //[4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
22 | //"bbbcccdddaaa"
23 | }
24 |
--------------------------------------------------------------------------------
/src/NumberComplement.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/29/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class NumberComplement {
8 | public int findComplement(int num) {
9 | int i = 31;
10 | while ((num & (1 << i)) == 0) --i; // first bit 1
11 | for (int j = i; j >= 0; --j)
12 | num ^= (1 << j);
13 | return num;
14 | }
15 |
16 | public static void main(String[] args) {
17 | NumberComplement nc = new NumberComplement();
18 | nc.findComplement(7);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/NumberThread.java:
--------------------------------------------------------------------------------
1 | import java.util.List;
2 |
3 | /**
4 | * @author Harry Tran on 10/5/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 |
10 | public class NumberThread extends FizzBuzzThread {
11 | public NumberThread(boolean div3, boolean div5, int max, List res) {
12 | super(div3, div5, max, null, res);
13 | }
14 | public void addToRes() {
15 | res.add(String.valueOf(current));
16 | }
17 | }
--------------------------------------------------------------------------------
/src/OptimalDivision.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/4/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class OptimalDivision {
8 | public String optimalDivision(int[] nums) {
9 | int len = nums.length;
10 | if (len == 1) return nums[0] + "";
11 | if (len == 2) return nums[0] + "/" + nums[1];
12 | String res = nums[0] + "/(" + nums[1];
13 | for (int i = 2; i < len; ++i)
14 | res += "/" + nums[i];
15 | res += ")";
16 | return res;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/PalindromicSubstrings.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/4/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class PalindromicSubstrings {
8 | public int countSubstrings(String s) {
9 | int len = s.length();
10 |
11 | int[][] isPalndromic = new int[len][len];
12 |
13 | for (int i = 0; i < len; ++i) isPalndromic[i][i] = 1;
14 |
15 | for (int i = 0; i < len - 1; ++i)
16 | if (s.charAt(i) == s.charAt(i + 1)) isPalndromic[i][i + 1] = 1;
17 |
18 | for (int le = 3; le <= len; ++le)
19 | for (int i = 0; i < len - le + 1; ++i) {
20 | int j = i + le - 1;
21 | if (s.charAt(i) == s.charAt(j))
22 | isPalndromic[i][j] = isPalndromic[i + 1][j - 1];
23 | }
24 |
25 | int cnt = 0;
26 | for (int i = 0; i < len; ++i)
27 | for (int j = i; j < len; ++j)
28 | cnt += isPalndromic[i][j];
29 | return cnt;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/PartitionLabels.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.HashMap;
3 | import java.util.List;
4 |
5 | /**
6 | * @author Harry Tran on 6/30/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class PartitionLabels {
12 | public List partitionLabels_1(String S) {
13 | HashMap map = new HashMap<>();
14 | int lengthS = S.length();
15 | for (int i = lengthS - 1; i >= 0; --i) {
16 | if (map.containsKey(S.charAt(i))) continue;
17 | map.put(S.charAt(i), i);
18 | }
19 | int begin = 0;
20 | int last = 0;
21 | List res = new ArrayList<>();
22 | for (int i = 0; i < lengthS; ++i) {
23 | int newLast = map.get(S.charAt(i));
24 | if (newLast <= i && last <= i) {
25 | res.add(last - begin + 1);
26 | begin = i + 1;
27 | last = i + 1;
28 | } else {
29 | last = Math.max(last, newLast);
30 | }
31 | }
32 | return res;
33 | }
34 |
35 | public List partitionLabels_2(String S) {
36 | int[] pos = new int[26];
37 |
38 | int lengthS = S.length();
39 | for (int i = 0; i < lengthS; ++i)
40 | pos[S.charAt(i) - 'a'] = i;
41 |
42 | int begin = 0;
43 | int last = 0;
44 | List res = new ArrayList<>();
45 |
46 | for (int i = 0; i < lengthS; ++i) {
47 | last = Math.max(last, pos[S.charAt(i) - 'a']);
48 | if (last == i) {
49 | res.add(last - begin + 1);
50 | begin = i + 1;
51 | }
52 | }
53 | return res;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/PathSum.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class PathSum {
8 | public boolean hasPathSum(TreeNode root, int sum) {
9 | if (root == null) return false;
10 | if (root.left == null && root.right == null) {
11 | return root.val == sum;
12 | }
13 | boolean res = false;
14 | if (root.left != null)
15 | res |= hasPathSum(root.left, sum - root.val);
16 | if (root.right != null)
17 | res |= hasPathSum(root.right, sum - root.val);
18 | return res;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/PathSumIII.java:
--------------------------------------------------------------------------------
1 | import javafx.util.Pair;
2 |
3 | import java.util.HashMap;
4 |
5 | /**
6 | * @author Harry Tran on 7/13/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class PathSumIII {
12 | HashMap, Integer> map = new HashMap<>();
13 |
14 | private int pathFrom(TreeNode n, int currSum) {
15 | if (n == null) return 0;
16 | Pair p = new Pair<>(n, currSum);
17 | if (map.containsKey(p)) {
18 | return map.get(p);
19 | }
20 | int res = (n.val == currSum ? 1 : 0) + pathFrom(n.left, currSum - n.val) + pathFrom(n.right, currSum - n.val);
21 | map.put(p, res);
22 | return res;
23 | }
24 |
25 | public int pathSum(TreeNode root, int sum) {
26 | if (root == null) return 0;
27 | return pathSum(root.left, sum) + pathSum(root.right, sum) + pathFrom(root, sum);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/PeakIndexInMountain.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/27/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class PeakIndexInMountain {
8 | public int peakIndexInMountainArray(int[] A) {
9 | int lengthA = A.length;
10 | for (int i = 1; i < lengthA - 1; ++i)
11 | if (A[i] > A[i - 1] && A[i] > A[i + 1]) return i;
12 | return 0;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/Permutations.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.Arrays;
3 | import java.util.List;
4 |
5 | /**
6 | * @author Harry Tran on 7/5/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class Permutations {
12 | List> res = new ArrayList<>();
13 | private int getBit(int num, int i) {
14 | return (num >> i) & 1;
15 | }
16 |
17 | private int onBit(int num, int i) {
18 | return num | (1 << i);
19 | }
20 |
21 | private void recursion(int pos, int n, int[] nums, int status, List curr) {
22 | if (pos == n) {
23 | res.add(new ArrayList<>(curr));
24 | return;
25 | }
26 |
27 | for (int i = 0; i < n; ++i)
28 | if (getBit(status, i) == 0) {
29 | curr.set(pos, nums[i]);
30 | recursion(pos + 1, n, nums, onBit(status, i), curr);
31 | }
32 |
33 | }
34 |
35 |
36 | public List> permute(int[] nums) {
37 | if (nums.length == 0) {
38 | res.add(new ArrayList<>());
39 | return res;
40 | }
41 | int n = nums.length;
42 | List curr = Arrays.asList(new Integer[nums.length]);
43 | recursion(0, n, nums, 0, curr);
44 | return res;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/PopulatingNextRightPointers.java:
--------------------------------------------------------------------------------
1 | import java.util.LinkedList;
2 | import java.util.Queue;
3 |
4 | /**
5 | * @author Harry Tran on 7/28/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | class TreeLinkNode {
11 | int val;
12 | TreeLinkNode left, right, next;
13 | TreeLinkNode(int x) { val = x; }
14 | }
15 |
16 | public class PopulatingNextRightPointers {
17 |
18 |
19 | public void connect(TreeLinkNode root) {
20 | if (root != null) {
21 | Queue q = new LinkedList<>();
22 | q.add(root);
23 |
24 | while (!q.isEmpty()) {
25 | Queue tmpQ = new LinkedList<>();
26 |
27 | TreeLinkNode last = null;
28 | while (!q.isEmpty()) {
29 | TreeLinkNode n = q.poll();
30 | if (n.left != null) {
31 | tmpQ.add(n.left);
32 | tmpQ.add(n.right);
33 | n.left.next = n.right;
34 | if (last != null) {
35 | last.next = n.left;
36 | }
37 | last = n.right;
38 | }
39 | }
40 |
41 | q.addAll(tmpQ);
42 | }
43 | }
44 | }
45 |
46 | public static void main(String[] args) {
47 | TreeLinkNode n1 = new TreeLinkNode(1);
48 | TreeLinkNode n2 = new TreeLinkNode(2);
49 | TreeLinkNode n3 = new TreeLinkNode(3);
50 | TreeLinkNode n4 = new TreeLinkNode(4);
51 | TreeLinkNode n5 = new TreeLinkNode(5);
52 | TreeLinkNode n6 = new TreeLinkNode(6);
53 | TreeLinkNode n7 = new TreeLinkNode(7);
54 | n1.left = n2;
55 | n1.right = n3;
56 | n2.left = n4;
57 | n2.right = n5;
58 | n3.left = n6;
59 | n3.right = n7;
60 | PopulatingNextRightPointers p = new PopulatingNextRightPointers();
61 | p.connect(n1);
62 |
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/PopulatingNextRightPointers2.java:
--------------------------------------------------------------------------------
1 | import java.util.LinkedList;
2 | import java.util.Queue;
3 |
4 | /**
5 | * @author Harry Tran on 7/28/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 |
11 | public class PopulatingNextRightPointers2 {
12 |
13 |
14 | public void connect(TreeLinkNode root) {
15 | if (root != null) {
16 | Queue q = new LinkedList<>();
17 | q.add(root);
18 |
19 | while (!q.isEmpty()) {
20 | Queue tmpQ = new LinkedList<>();
21 |
22 | TreeLinkNode last = null;
23 | while (!q.isEmpty()) {
24 | TreeLinkNode n = q.poll();
25 | if (n.left != null) {
26 | tmpQ.add(n.left);
27 | if (last != null) {
28 | last.next = n.left;
29 | }
30 | last = n.left;
31 | }
32 |
33 | if (n.right != null) {
34 | tmpQ.add(n.right);
35 | if (last != null) {
36 | last.next = n.right;
37 | }
38 | last = n.right;
39 | }
40 | }
41 | q.addAll(tmpQ);
42 | }
43 | }
44 | System.out.println("DOne");
45 | }
46 |
47 | public static void main(String[] args) {
48 | TreeLinkNode n1 = new TreeLinkNode(1);
49 | TreeLinkNode n2 = new TreeLinkNode(2);
50 | TreeLinkNode n3 = new TreeLinkNode(3);
51 | TreeLinkNode n4 = new TreeLinkNode(4);
52 | TreeLinkNode n5 = new TreeLinkNode(5);
53 | TreeLinkNode n6 = new TreeLinkNode(6);
54 | TreeLinkNode n7 = new TreeLinkNode(7);
55 | n1.left = n2;
56 | n1.right = n3;
57 | n2.left = n4;
58 | n2.right = n5;
59 | n3.left = n6;
60 | n3.right = n7;
61 | PopulatingNextRightPointers2 p = new PopulatingNextRightPointers2();
62 | p.connect(n1);
63 |
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/PreorderTraversal.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 | import java.util.Stack;
4 |
5 | /**
6 | * @author Harry Tran on 7/23/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class PreorderTraversal {
12 | public List preorderTraversal(TreeNode root) {
13 | List res = new ArrayList<>();
14 | Stack st = new Stack<>();
15 | if (root == null) return res;
16 |
17 | st.push(root);
18 | while (!st.empty()) {
19 | TreeNode n = st.pop();
20 |
21 | res.add(n.val);
22 | if (n.right != null) st.push(n.right);
23 | if (n.left != null) st.push(n.left);
24 | }
25 | return res;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/PrimeNumberOfSetBits.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.Arrays;
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * @author Harry Tran on 7/1/18.
8 | * @project Leetcode
9 | * @email trunghieu.tran@utdallas.edu
10 | * @organization UTDallas
11 | */
12 | public class PrimeNumberOfSetBits {
13 |
14 | public int countPrimeSetBits(int L, int R) {
15 | Set primes = new HashSet<>(Arrays.asList(2, 3,5,7, 11, 13, 17, 19, 23));
16 | int res = 0;
17 | for (int i = L; i <= R; ++i) {
18 | int cnt = Integer.bitCount(i);
19 | if (primes.contains(cnt)) ++res;
20 | }
21 | return res;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/QueueReconstructionByHeight.java:
--------------------------------------------------------------------------------
1 | import javafx.util.Pair;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.Collections;
6 | import java.util.Comparator;
7 |
8 | /**
9 | * @author Harry Tran on 6/30/18.
10 | * @project Leetcode
11 | * @email trunghieu.tran@utdallas.edu
12 | * @organization UTDallas
13 | */
14 | public class QueueReconstructionByHeight {
15 | public int[][] reconstructQueue2(int[][] people) {
16 | ArrayList> tmp = new ArrayList<>();
17 | for (int i = 0; i < people.length; ++i) {
18 | tmp.add(new Pair<>(people[i][0], people[i][1]));
19 | }
20 |
21 | Collections.sort(tmp, new Comparator>() {
22 | @Override
23 | public int compare(Pair o1, Pair o2) {
24 | if (o1.getValue() < o2.getValue()) return -1;
25 | if (o1.getValue() > o2.getValue()) return 1;
26 | return o1.getKey().compareTo(o2.getKey());
27 | }
28 | });
29 |
30 | int[][] res = new int[people.length][2];
31 | ArrayList> tmp2 = new ArrayList<>();
32 | for (int i = 0; i < tmp.size(); ++i) {
33 | System.out.println(Integer.toString(tmp.get(i).getKey()) + " " + Integer.toString(tmp.get(i).getValue()));
34 | int cc = 0;
35 | int h = tmp.get(i).getKey();
36 | int c = tmp.get(i).getValue();
37 | boolean added = false;
38 | for (int j = 0; j < tmp2.size(); ++j) {
39 | if (tmp2.get(j).getKey() >= h) ++cc;
40 | if (cc > c) {
41 | tmp2.add(j, tmp.get(i));
42 | added = true;
43 | break;
44 | }
45 | }
46 | if (!added) tmp2.add(tmp.get(i));
47 | }
48 |
49 | int cc = 0;
50 | for (Pair p : tmp2) {
51 | // System.out.println(Integer.toString(p.getKey()) + " " + Integer.toString(p.getValue()));
52 | res[cc][0] = p.getKey();
53 | res[cc][1] = p.getValue();
54 | ++cc;
55 | }
56 |
57 | return res;
58 | }
59 |
60 | public int[][] reconstructQueue(int[][] people) {
61 | Arrays.sort(people, ((o1, o2) -> (o1[0] == o2[0])? o1[1] - o2[1] : o2[0] - o1[0]));
62 | ArrayList res = new ArrayList<>();
63 | for (int[] p : people)
64 | res.add(p[1], p);
65 | return res.toArray(new int[people.length][2]);
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/RangeSumQueryMutable.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/22/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class RangeSumQueryMutable {
8 | class NumArray {
9 |
10 | class TreeNode {
11 | int sum;
12 | TreeNode left;
13 | TreeNode right;
14 | public TreeNode(int sum, TreeNode l, TreeNode r) {
15 | this.sum = sum;
16 | this.left = l;
17 | this.right = r;
18 | }
19 | }
20 |
21 | TreeNode root;
22 | int n;
23 |
24 | public NumArray(int[] nums) {
25 | n = nums.length - 1;
26 | root = buildTree(0, n, nums);
27 | }
28 |
29 | private TreeNode buildTree(int start, int end, int[] nums) {
30 | if (start > end) return null;
31 | if (start == end) {
32 | return new TreeNode(nums[start], null, null);
33 | }
34 | int mid = (start + end) / 2;
35 | TreeNode l = buildTree(start, mid, nums);
36 | TreeNode r = buildTree(mid + 1, end, nums);
37 | return new TreeNode( l.sum + r.sum, l, r);
38 | }
39 |
40 | private void updateTree(int start, int end, int i, int val, TreeNode node) {
41 | if (i > end || i < start) return;
42 | if (start == end) {
43 | node.sum = val;
44 | return;
45 | }
46 | int mid = (start + end) / 2;
47 | if (mid >= i) {
48 | updateTree(start, mid, i, val, node.left);
49 | } else
50 | updateTree(mid + 1, end, i, val, node.right);
51 | node.sum = node.left.sum + node.right.sum;
52 | }
53 |
54 | private int getSum(int start, int end, int i, int j, TreeNode node) {
55 | if (start > end || start > j || end < i) return 0;
56 | if (start == end) return node.sum;
57 | int mid = (start + end) / 2;
58 | return getSum(start, mid, i, j, node.left) + getSum(mid + 1, end, i, j, node.right);
59 | }
60 |
61 | public void update(int i, int val) {
62 | updateTree(0, n, i, val, root);
63 | }
64 |
65 | public int sumRange(int i, int j) {
66 | return getSum(0, n, i, j, root);
67 | }
68 | }
69 |
70 | public static void main(String[] args) {
71 | // NumArray obj = new NumArray(nums);
72 | // obj.update(i,val);
73 | // int param_2 = obj.sumRange(i,j);
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/RecoverBinarySearchTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/11/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class RecoverBinarySearchTree {
8 | public class TreeNode {
9 | int val;
10 | TreeNode left;
11 | TreeNode right;
12 | TreeNode(int x) { val = x; }
13 | }
14 |
15 | TreeNode n1 = null;
16 | TreeNode n2 = null;
17 | TreeNode last = new TreeNode(Integer.MIN_VALUE);
18 |
19 | private void traverse(TreeNode node) {
20 | if (node == null) return;
21 | // if (n1 != null && n2 != null) return;
22 |
23 | traverse(node.left);
24 |
25 | if (n1 == null && node.val < last.val) n1 = last;
26 | if (n1 != null && node.val < last.val) n2 = node;
27 | last = node;
28 |
29 | traverse(node.right);
30 | }
31 | public void recoverTree(TreeNode root) {
32 | traverse(root);
33 |
34 | int tmp = n1.val;
35 | n1.val = n2.val;
36 | n2.val = tmp;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/ReshapMatrix.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/30/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ReshapMatrix {
8 | public int[][] matrixReshape(int[][] nums, int r, int c) {
9 | int height = nums.length;
10 | int width = nums[0].length;
11 | if (width * height != r * c) return nums;
12 | int[][] res = new int[r][c];
13 | int ii = 0;
14 | int jj = 0;
15 | for (int i = 0; i < height; ++i)
16 | for (int j = 0; j < width; ++j) {
17 | res[ii][jj] = nums[i][j];
18 |
19 | if (jj == c - 1) {
20 | jj = 0;
21 | ii++;
22 | } else jj++;
23 | }
24 | return res;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/ReverseBits.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/4/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ReverseBits {
8 | // you need treat n as an unsigned value
9 | public static int reverseBits(int n) {
10 | if (n == 0) return 0;
11 |
12 | int res = 0;
13 | for (int i = 0; i < 32; ++i) {
14 | res <<= 1;
15 | if ((n & 1) == 1) res++;
16 | n >>= 1;
17 | }
18 | return res;
19 | }
20 |
21 | public static void main(String[] args) {
22 | System.out.println(reverseBits(1));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/ReverseString.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/30/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ReverseString {
8 | public String reverseString(String s) {
9 | return new StringBuilder(s).reverse().toString();
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/ReverseWordsInString.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/29/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ReverseWordsInString {
8 | public String reverseWords(String s) {
9 | String[] str = s.split(" ");
10 | StringBuilder res = new StringBuilder(str[0]).reverse();
11 | for (int i = 1; i < str.length; ++i) {
12 | res.append(" ").append(new StringBuilder(str[i]).reverse());
13 | }
14 | return res.toString();
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/SameTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/10/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class SameTree {
8 | public class TreeNode {
9 | int val;
10 | TreeNode left;
11 | TreeNode right;
12 | TreeNode(int x) { val = x; }
13 | }
14 |
15 | public boolean isSameTree(TreeNode p, TreeNode q) {
16 | if (p == null)
17 | return q == null;
18 | return (q != null) && (p.val == q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/ScoreOfParentheses.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/3/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ScoreOfParentheses {
8 | public int scoreOfParentheses(String S) {
9 | int res = 0, numOfOpen = 0;
10 | int lenS = S.length();
11 | for (int i = 0; i < lenS; ++i) {
12 | if (S.charAt(i) == '(') {
13 |
14 | if (S.charAt(i + 1) == ')')
15 | res += 1 << numOfOpen;
16 |
17 | numOfOpen++;
18 | } else numOfOpen--;
19 | }
20 | return res;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/Search2DMatrix.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/30/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class Search2DMatrix {
8 |
9 | private boolean bi_searchRow(int i, int j1, int j2, int[][] maxtrix, int target) {
10 | // if (maxtrix[i][j1] > target || maxtrix[i][j2] < target) return false;
11 | while (j1 <= j2) {
12 | int mid = (j1 + j2) / 2;
13 | if (maxtrix[i][mid] > target) j2 = mid - 1;
14 | else
15 | if (maxtrix[i][mid] < target) j1 = mid + 1;
16 | else return true;
17 | }
18 | return false;
19 | }
20 |
21 | private boolean bi_searchCol(int j, int i1, int i2, int[][] maxtrix, int target) {
22 | // if (maxtrix[i1][j] > target || maxtrix[i2][j] < target) return false;
23 | while (i1 <= i2) {
24 | int mid = (i1 + i2) / 2;
25 | if (maxtrix[mid][j] > target) i2 = mid - 1;
26 | else
27 | if (maxtrix[mid][j] < target) i1 = mid + 1;
28 | else return true;
29 |
30 |
31 | }
32 | return false;
33 | }
34 |
35 |
36 | private boolean search(int i, int j, int[][] matrix, int target) {
37 | if (i == 0) return bi_searchRow(0, 0, j, matrix, target);
38 | if (j == 0) return bi_searchCol(0, 0, i, matrix, target);
39 |
40 | boolean res = bi_searchRow(i, 0, j, matrix, target);
41 | res |= bi_searchCol(j, 0, i, matrix, target);
42 | if (!res && matrix[i - 1][j - 1] >= target)
43 | res |= search(i - 1, j - 1, matrix, target);
44 |
45 | return res;
46 | }
47 | public boolean searchMatrix(int[][] matrix, int target) {
48 | if (matrix.length == 0 || matrix[0].length == 0) return false;
49 | return search(matrix.length - 1, matrix[0].length - 1, matrix, target);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/SearchBST.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class SearchBST {
8 | public TreeNode searchBST(TreeNode root, int val) {
9 | if (root == null) return null;
10 | if (root.val == val) return root;
11 | if (root.val > val) return searchBST(root.left, val);
12 | return searchBST(root.right, val);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/SecondMinNodeInBTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class SecondMinNodeInBTree {
8 | int min = -2;
9 | int min2 = -1;
10 |
11 | private void traverse(TreeNode n) {
12 | if (min == -2 || min > n.val) min = n.val;
13 | if (n.val > min) {
14 | if (min2 == -1 || min2 > n.val) min2 = n.val;
15 | }
16 | if (n.left == null) return;
17 |
18 | int currMin = Math.min(n.left.val, n.right.val);
19 |
20 | if (min2 == -1 || currMin < min2) {
21 | traverse(n.left);
22 | traverse(n.right);
23 | }
24 | }
25 | public int findSecondMinimumValue(TreeNode root) {
26 | traverse(root);
27 | return min2;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/SelfDividingNum.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | /**
5 | * @author Harry Tran on 6/28/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class SelfDividingNum {
11 | public List selfDividingNumbers(int left, int right) {
12 | List res = new ArrayList<>();
13 | for (int i = left; i <= right; ++i) {
14 | int j = i;
15 | boolean isOk = true;
16 | while (j > 0 && isOk) {
17 | int xmod = j % 10;
18 | isOk &= ((xmod != 0) && (i % xmod == 0));
19 | j /= 10;
20 | }
21 | if (isOk) res.add(i);
22 | }
23 | return res;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/ShortestDistanceToCharacter.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/29/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ShortestDistanceToCharacter {
8 | public int[] shortestToChar(String S, char C) {
9 | int lengthS = S.length();
10 | int[] res = new int[lengthS];
11 | int[] f_left = new int[lengthS];
12 | int[] f_right = new int[lengthS];
13 |
14 | f_left[0] = (S.charAt(0) == C) ? 0 : lengthS;
15 | for (int i = 1; i < lengthS; ++i) {
16 | if (S.charAt(i) == C) f_left[i] = 0;
17 | else
18 | f_left[i] = f_left[i - 1] + 1;
19 | }
20 |
21 | f_right[lengthS - 1] = (S.charAt(lengthS - 1) == C) ? 0 : lengthS;
22 | for (int i = lengthS - 2; i >= 0; --i) {
23 | if (S.charAt(i) == C) f_right[i] = 0;
24 | else
25 | f_right[i] = f_right[i + 1] + 1;
26 | }
27 |
28 | for (int i = 0; i < lengthS; ++i)
29 | res[i] = Math.min(f_left[i], f_right[i]);
30 | return res;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/SingleElementInSortedArray.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/3/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class SingleElementInSortedArray {
8 | public int singleNonDuplicate(int[] nums) {
9 | int l = 0, r = nums.length;
10 | while (l <= r) {
11 | int mid = (l + r) / 2;
12 | if ( (mid==0 || nums[mid-1] != nums[mid]) &&
13 | (mid==nums.length - 1 || nums[mid] != nums[mid + 1])) return nums[mid];
14 | if ((mid - l + 1) % 2 == 0) {
15 | if (nums[mid] != nums[mid + 1]) l = mid + 1;
16 | else r = mid - 1;
17 | }
18 | else {
19 | if (nums[mid] != nums[mid + 1]) r = mid;
20 | else l = mid + 2;
21 | }
22 | }
23 | return 0;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/SingleNumber.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/1/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class SingleNumber {
8 | public int singleNumber(int[] nums) {
9 | int len = nums.length;
10 | int res = 0;
11 | for (int i = 0; i < len; ++i) res ^= nums[i];
12 | return res;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/SingleNumberII.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/4/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class SingleNumberII {
8 | private int getBit(int num, int i) {
9 | return (num >> i) & 1;
10 | }
11 |
12 | private int onBit(int num, int i) {
13 | return (1 << i) | num;
14 | }
15 |
16 | public int singleNumber(int[] nums) {
17 | int len = nums.length;
18 | int res = 0;
19 | for (int i = 0; i < 32; ++i) {
20 | int sum = 0;
21 | for (int j = 0; j < len; ++j)
22 | sum += getBit(nums[j], i);
23 | if (sum % 3 != 0)
24 | res = onBit(res, i);
25 | }
26 | return res;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/SingleNumberIII.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/4/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class SingleNumberIII {
8 |
9 | private int getBit(int num, int i) {
10 | // return num & (1 << i);
11 | return (num >> i) & 1;
12 | }
13 | public int[] singleNumber(int[] nums) {
14 | int len = nums.length;
15 |
16 | int xor = 0;
17 | for (int i = 0; i < len; ++i)
18 | xor ^= nums[i];
19 |
20 | int posDiff = 0;
21 | for (int i = 0; i < 32; ++i)
22 | if (getBit(xor, i) == 1) {
23 | posDiff = i;
24 | break;
25 | }
26 |
27 | int xor0 = 0;
28 | int xor1 = 0;
29 | for (int i = 0; i < len; ++i)
30 | if (getBit(nums[i], posDiff) == 0) xor0 ^= nums[i];
31 | else xor1 ^= nums[i];
32 | return new int[]{xor0, xor1};
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | /**
4 | * Definition for singly-linked list.
5 | * public class ListNode {
6 | * int val;
7 | * ListNode next;
8 | * ListNode(int x) {
9 | * val = x;
10 | * next = null;
11 | * }
12 | * }
13 | */
14 | public class Solution {
15 |
16 | public static void main(String[] args) {
17 | HashMap map = new HashMap<>();
18 | map.put("Tran HIeu", 1);
19 | int x = 10;
20 | int y = 20;
21 | String s = x + " " + y;
22 | System.out.println(s);
23 | }
24 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
25 | if (headA == null || headB == null) return null;
26 |
27 | Info fa = getInfo(headA);
28 | Info fb = getInfo(headB);
29 |
30 | if (fa.tail != fb.tail) return null;
31 |
32 | ListNode shorter = fa.size > fb.size ? headB : headA;
33 | ListNode longer = fa.size > fb.size ? headA : headB;
34 |
35 | longer = gotoKthNode(longer, Math.abs(fa.size - fb.size));
36 |
37 | while (longer != shorter) {
38 | longer = longer.next;
39 | shorter = shorter.next;
40 | }
41 | Queue q = new LinkedList<>();
42 | q.offer(10);
43 | q.poll();
44 | List l = new LinkedList<>();
45 | l.iterator();
46 | l.isEmpty();
47 |
48 | return shorter;
49 | }
50 |
51 | private ListNode gotoKthNode(ListNode n, int k) {
52 | for (int i = 0; i < k; ++i) {
53 | n = n.next;
54 | }
55 | return n;
56 | }
57 |
58 | private Info getInfo(ListNode n) {
59 | int size = 1;
60 | ListNode curr = n;
61 | while (curr.next != null) {
62 | curr = curr.next;
63 | ++size;
64 | }
65 | return new Info(curr, size);
66 | }
67 | }
68 |
69 | class Info {
70 | public ListNode tail;
71 | public int size;
72 | public Info(ListNode tail, int size){
73 | this.tail = tail;
74 | this.size = size;
75 | }
76 | }
--------------------------------------------------------------------------------
/src/SortCharactersByFrequency.java:
--------------------------------------------------------------------------------
1 | import javafx.util.Pair;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Comparator;
5 | import java.util.List;
6 |
7 | /**
8 | * @author Harry Tran on 7/5/18.
9 | * @project Leetcode
10 | * @email trunghieu.tran@utdallas.edu
11 | * @organization UTDallas
12 | */
13 | public class SortCharactersByFrequency {
14 | public static String frequencySort(String s) {
15 | int[] count = new int[130];
16 | for (char c : s.toCharArray())
17 | count[c]++;
18 | List> list = new ArrayList<>();
19 | for (int i = 0; i < 130; ++i)
20 | if (count[i] > 0) list.add(new Pair<>(count[i], i));
21 | list.sort(new Comparator>() {
22 | @Override
23 | public int compare(Pair o1, Pair o2) {
24 | return o2.getKey().compareTo(o1.getKey());
25 | }
26 | });
27 | int len = list.size();
28 | StringBuilder res = new StringBuilder();
29 | char[] cc = new char[s.length()];
30 | int cnt = 0;
31 |
32 | for (int i = 0; i < len; ++i) {
33 | int num = list.get(i).getKey();
34 | char c = (char) list.get(i).getValue().intValue();
35 | for (int j = 0; j < num; ++j)
36 | cc[cnt++] = c;
37 | // res.append(c);
38 | }
39 | // return res.toString();
40 | return String.valueOf(cc);
41 | }
42 |
43 | public static void main(String[] args) {
44 | StringBuilder sb = new StringBuilder();
45 | for (int i = 0; i <= 500000; ++i)
46 | sb.append("ab");
47 | System.out.println(sb.length());
48 | System.out.println(SortCharactersByFrequency.frequencySort(sb.toString()));
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/StringToIntegerAtoi.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/10/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class StringToIntegerAtoi {
8 | public static int myAtoi(String str) {
9 | if (str.isEmpty()) return 0;
10 |
11 | int i = 0;
12 | while (i < str.length() && str.charAt(i) == ' ') ++i;
13 | if (i >= str.length()) return 0;
14 |
15 | char c1 = str.charAt(i);
16 | if (c1 != '-' && c1 != '+' && (c1 > '9' || c1 < '0')) return 0;
17 |
18 | boolean am = false;
19 | if (str.charAt(i) == '-') {
20 | am = true;
21 | ++i;
22 | } else
23 | if (str.charAt(i) == '+') ++i;
24 |
25 | while (i < str.length() && str.charAt(i) == '0') ++i;
26 | if (i >= str.length() || str.charAt(i) > '9' || str.charAt(i) < '0') return 0;
27 |
28 | int j = i + 1;
29 | while (j < str.length() && str.charAt(j) >= '0' && str.charAt(j) <= '9') ++j;
30 | String snum = str.substring(i, j);
31 | try {
32 | if (j - i >= 11) {
33 | if (am) return Integer.MIN_VALUE;
34 | else return Integer.MAX_VALUE;
35 | }
36 | long num = Long.parseLong(snum);
37 | if (am) num = -num;
38 |
39 | if (num > Integer.MAX_VALUE)
40 | return Integer.MAX_VALUE;
41 | else if (num < Integer.MIN_VALUE)
42 | return Integer.MIN_VALUE;
43 | return (int) num;
44 | } catch (Exception e) {
45 | return 0;
46 | }
47 |
48 | }
49 |
50 | public static void main(String[] args) {
51 | System.out.println(StringToIntegerAtoi.myAtoi(" -2147483648"));
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/SubdomainVisitCount.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.HashMap;
3 | import java.util.List;
4 | import java.util.Map;
5 |
6 | /**
7 | * @author Harry Tran on 6/29/18.
8 | * @project Leetcode
9 | * @email trunghieu.tran@utdallas.edu
10 | * @organization UTDallas
11 | */
12 | public class SubdomainVisitCount {
13 | public List subdomainVisits(String[] cpdomains) {
14 | Map map = new HashMap<>();
15 | ArrayList res = new ArrayList<>();
16 |
17 | for (String str : cpdomains) {
18 | String[] tmp = str.split(" ");
19 | String[] tmp2 = tmp[1].split("\\.");
20 | int cnt = Integer.parseInt(tmp[0]);
21 |
22 | map.put(tmp[1], map.getOrDefault(tmp[1], 0) + cnt);
23 |
24 | int id = tmp2.length - 1;
25 | map.put(tmp2[id], map.getOrDefault(tmp2[id], 0) + cnt);
26 |
27 | if (id == 2) {
28 | String sub2 = tmp2[1] + "." + tmp2[2];
29 | map.put(sub2, map.getOrDefault(sub2, 0) + cnt);
30 | }
31 | }
32 |
33 | for (String str : map.keySet()) {
34 | res.add(Integer.toString(map.get(str)) + " " + str);
35 | }
36 |
37 | return res;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/Subsets.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | /**
5 | * @author Harry Tran on 7/4/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class Subsets {
11 |
12 | private void recursion(int pos, int[] nums, ArrayList curr, List> res) {
13 | if (pos == nums.length) {
14 | res.add(new ArrayList<>(curr));
15 | return;
16 | }
17 |
18 | recursion(pos + 1, nums, curr, res);
19 |
20 | curr.add(nums[pos]);
21 | recursion(pos + 1, nums, curr, res);
22 | curr.remove(curr.size() - 1);
23 | }
24 |
25 | public List> subsets(int[] nums) {
26 | List> res = new ArrayList<>();
27 | recursion(0, nums, new ArrayList<>(), res);
28 | return res;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/SubsetsII.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.Arrays;
3 | import java.util.List;
4 |
5 | /**
6 | * @author Harry Tran on 7/4/18.
7 | * @project Leetcode
8 | * @email trunghieu.tran@utdallas.edu
9 | * @organization UTDallas
10 | */
11 | public class SubsetsII {
12 | private void recursion(int pos, int[] nums, ArrayList curr, List> res) {
13 | if (pos == nums.length) {
14 | // res.add(new ArrayList<>(curr));
15 | return;
16 | }
17 |
18 |
19 | for (int i = pos; i < nums.length; ++i) {
20 | if (i == pos || nums[i] != nums[i - 1]) {
21 | curr.add(nums[i]);
22 | res.add(new ArrayList<>(curr));
23 | recursion(i + 1, nums, curr, res);
24 | curr.remove(curr.size() - 1);
25 | }
26 | }
27 | }
28 | public List> subsetsWithDup(int[] nums) {
29 | Arrays.sort(nums);
30 | List> res = new ArrayList<>();
31 | recursion(0, nums, new ArrayList<>(), res);
32 | res.add(new ArrayList<>());
33 | return res;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/SudokuSolver.java:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * @author Harry Tran on 7/4/18.
4 | * @project Leetcode
5 | * @email trunghieu.tran@utdallas.edu
6 | * @organization UTDallas
7 | */
8 | public class SudokuSolver {
9 | boolean[][] row = new boolean[9][9];
10 | boolean[][] col = new boolean[9][9];
11 | boolean[][] box = new boolean[9][9];
12 |
13 | int[][] boardI = new int[9][9];
14 |
15 | boolean isResolved = false;
16 |
17 |
18 | private int getBoxNum(int i, int j) {
19 | return (i / 3) * 3 + (j / 3);
20 | }
21 |
22 | private void recursion_solving(int resolvedNum) {
23 | if (resolvedNum == 81) {
24 | System.out.println("Resolved");
25 | isResolved = true;
26 | return;
27 | }
28 |
29 | int posI = 0, posJ = 0, posB = 0;
30 | int best = 10;
31 | for (int i = 0; i < 9; ++i)
32 | if (best > 1)
33 | for (int j = 0; j < 9; ++j)
34 | if (boardI[i][j] == -1) {
35 | int boxNum = getBoxNum(i, j);
36 | int cnt = 0;
37 |
38 | for (int val = 0; val < 9; ++val)
39 | if (row[i][val] || col[j][val] || box[boxNum][val]) continue;
40 | else cnt++;
41 |
42 | if (cnt == 0) return;
43 |
44 | if (cnt < best) {
45 | best = cnt;
46 | posI = i;
47 | posJ = j;
48 | posB = boxNum;
49 |
50 | if (best == 1) break;
51 | }
52 | }
53 |
54 |
55 | for (int val = 0; val < 9; ++val) {
56 | if (row[posI][val] || col[posJ][val] || box[posB][val]) continue;
57 |
58 | boardI[posI][posJ] = val;
59 | row[posI][val] = true;
60 | col[posJ][val] = true;
61 | box[posB][val] = true;
62 |
63 | recursion_solving(resolvedNum + 1);
64 | if (isResolved) return;
65 |
66 | boardI[posI][posJ] = -1;
67 | row[posI][val] = false;
68 | col[posJ][val] = false;
69 | box[posB][val] = false;
70 | }
71 | }
72 |
73 | public void solveSudoku(char[][] board) {
74 | int resolvedNum = 0;
75 |
76 | for (int i = 0; i < 9; ++i)
77 | for (int j = 0; j < 9; ++j)
78 | if (board[i][j] != '.') {
79 | int num = Character.digit(board[i][j], 10) - 1;
80 | int boxNum = getBoxNum(i, j);
81 | boardI[i][j] = num;
82 | resolvedNum++;
83 |
84 | row[i][num] = true;
85 | col[j][num] = true;
86 | box[boxNum][num] = true;
87 |
88 | } else boardI[i][j] = -1;
89 |
90 |
91 | recursion_solving(resolvedNum);
92 |
93 | for (int i = 0; i < 9; ++i)
94 | for (int j = 0; j < 9; ++j)
95 | board[i][j] = Character.forDigit(boardI[i][j] + 1, 10);
96 |
97 | }
98 |
99 | public static void main(String[] args) {
100 | char[][] board = {{'5','3','.','.','7','.','.','.','.'},
101 | {'6','.','.','1','9','5','.','.','.'},
102 | {'.','9','8','.','.','.','.','6','.'},
103 | {'8','.','.','.','6','.','.','.','3'},
104 | {'4','.','.','8','.','3','.','.','1'},
105 | {'7','.','.','.','2','.','.','.','6'},
106 | {'.','6','.','.','.','.','2','8','.'},
107 | {'.','.','.','4','1','9','.','.','5'},
108 | {'.','.','.','.','8','.','.','7','9'}};
109 |
110 | SudokuSolver ss = new SudokuSolver();
111 | ss.solveSudoku(board);
112 | for (int i = 0; i < 9; ++i) {
113 | for (int j = 0; j < 9; ++j)
114 | System.out.print(board[i][j] + " ");
115 | System.out.println();
116 | }
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/src/SumOfDistancesInTree.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | /**
4 | * @author Harry Tran on 7/9/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class SumOfDistancesInTree {
10 | List> nextNodes = new ArrayList<>();
11 | List> nextNodes2 = new ArrayList<>();
12 | int[] nChild;
13 | int[] res;
14 | int N;
15 | private void traverse(int u, int parent) {
16 | for (int v : nextNodes.get(u))
17 | if (v != parent) {
18 | nextNodes2.get(u).add(v);
19 | traverse(v, u);
20 | nChild[u] += nChild[v];
21 | res[u] += res[v] + nChild[v]; // res[v] - result for subtree v
22 | }
23 | }
24 |
25 | private void traverse2(int u) {
26 | for (int v : nextNodes2.get(u))
27 | {
28 | res[v] = res[u] - nChild[v] + (N - nChild[v]);
29 | traverse2(v);
30 | }
31 | }
32 |
33 | public int[] sumOfDistancesInTree(int N, int[][] edges) {
34 | res = new int[N];
35 |
36 | if (N == 1) {
37 | res[0] = 0;
38 | return res;
39 | }
40 |
41 | for (int i = 0; i < N; ++i) {
42 | nextNodes.add(new HashSet<>());
43 | nextNodes2.add(new HashSet<>());
44 | }
45 |
46 | for (int[] e : edges) {
47 | nextNodes.get(e[0]).add(e[1]);
48 | nextNodes.get(e[1]).add(e[0]);
49 | }
50 | this.N = N;
51 | nChild = new int[N];
52 | Arrays.fill(nChild, 1);
53 |
54 | traverse(0, -1);
55 | traverse2(0);
56 | return res;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/SumOfLeftLeaves.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class SumOfLeftLeaves {
8 | int res = 0;
9 | public int sumOfLeftLeaves(TreeNode root) {
10 | if (root == null) return 0;
11 |
12 | if (root.left != null) {
13 | if (root.left.left == null && root.left.right == null)
14 | res += root.left.val;
15 | sumOfLeftLeaves(root.left);
16 | }
17 | sumOfLeftLeaves(root.right);
18 |
19 | return res;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/SymmetricTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/3/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class SymmetricTree {
8 |
9 | public class TreeNode {
10 | int val;
11 | TreeNode left;
12 | TreeNode right;
13 | TreeNode(int x) { val = x; }
14 | }
15 |
16 | private boolean isSymmetric2Nodes(TreeNode n1, TreeNode n2) {
17 | if (n1 == null) return n2 == null;
18 | if (n2 == null) return false;
19 |
20 | boolean res = n1.val == n2.val;
21 | res &= isSymmetric2Nodes(n1.left, n2.right);
22 | res &= isSymmetric2Nodes(n1.right, n2.left);
23 |
24 | return res;
25 | }
26 |
27 | public boolean isSymmetric(TreeNode root) {
28 | if (root == null) return true;
29 | return isSymmetric2Nodes(root.left, root.right);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/TaskScheduler.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.Comparator;
3 | import java.util.List;
4 | import java.util.PriorityQueue;
5 |
6 | /**
7 | * @author Harry Tran on 7/21/18.
8 | * @project Leetcode
9 | * @email trunghieu.tran@utdallas.edu
10 | * @organization UTDallas
11 | */
12 | public class TaskScheduler {
13 | public int leastInterval(char[] tasks, int n) {
14 | int[] count = new int[26];
15 | for (char chr : tasks)
16 | count[chr-'A']++;
17 | PriorityQueue q = new PriorityQueue<>(26, Comparator.reverseOrder());
18 | for (int i : count)
19 | if (i > 0) q.add(i);
20 | int res = 0;
21 | while (!q.isEmpty()) {
22 | List tmp = new ArrayList<>();
23 | for (int i = 0; i < n; ++i) {
24 | if (!q.isEmpty()) {
25 | int x = q.poll() - 1;
26 | if (x > 0) tmp.add(x);
27 | }
28 | res++;
29 | if (q.isEmpty() && tmp.size() == 0) break;
30 | }
31 | q.addAll(tmp);
32 | }
33 | return res;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/ToLowerCase.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/12/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ToLowerCase {
8 | public String toLowerCase(String str) {
9 | return str.toLowerCase();
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/ToeplitzMatrix.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/30/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ToeplitzMatrix {
8 | public boolean isToeplitzMatrix(int[][] matrix) {
9 | int height = matrix.length;
10 | int width = matrix[0].length;
11 | for (int i = 1; i < height; ++i)
12 | for (int j = 1; j < width; ++j) {
13 | if (matrix[i][j] != matrix[i -1][j -1]) return false;
14 | }
15 | return true;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/TreeNode.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/11/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class TreeNode {
8 | int val;
9 | TreeNode left;
10 | TreeNode right;
11 | TreeNode(int x) { val = x; }
12 | }
13 |
--------------------------------------------------------------------------------
/src/TrimBinarySearchTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 6/30/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class TrimBinarySearchTree {
8 | public class TreeNode {
9 | int val;
10 | TreeNode left;
11 | TreeNode right;
12 | TreeNode(int x) { val = x; }
13 | }
14 |
15 | public TreeNode trimBST(TreeNode root, int L, int R) {
16 | if (root == null) return null;
17 |
18 | if (root.val > R) return trimBST(root.left, L, R);
19 |
20 | if (root.val < L) return trimBST(root.right, L, R);
21 |
22 | root.left = trimBST(root.left, L, R);
23 | root.right = trimBST(root.right, L, R);
24 | return root;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/TwoSum.java:
--------------------------------------------------------------------------------
1 | import java.util.HashMap;
2 | import java.util.HashSet;
3 |
4 | /**
5 | * @author Harry Tran on 6/25/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class TwoSum {
11 | public static int[] twoSum(int[] nums, int target) {
12 | HashMap hashMap = new HashMap<>();
13 |
14 | for (int i = 0; i < nums.length; ++i) {
15 | if (hashMap.containsKey(nums[i])) {
16 | return new int[]{i, hashMap.get(nums[i])};
17 | } else
18 | hashMap.put(target - nums[i], i);
19 | }
20 |
21 | return new int[]{};
22 | }
23 |
24 | public static void main(String[] args) {
25 | int[] nums = new int[]{4, 5, 11, 15};
26 | int[] res = TwoSum.twoSum(nums, 9);
27 | System.out.println(res[0]);
28 | System.out.println(res[1]);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/TwoSumIVInputBST.java:
--------------------------------------------------------------------------------
1 | import java.util.HashSet;
2 | import java.util.Set;
3 |
4 | /**
5 | * @author Harry Tran on 7/10/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class TwoSumIVInputBST {
11 | public class TreeNode {
12 | int val;
13 | TreeNode left;
14 | TreeNode right;
15 | TreeNode(int x) { val = x; }
16 | }
17 |
18 | Set set = new HashSet<>();
19 |
20 | private boolean traverse(TreeNode node, int target) {
21 | if (node == null) return false;
22 | if (set.contains(target - node.val)) return true;
23 | set.add(node.val);
24 | return traverse(node.left, target) || traverse(node.right, target);
25 | }
26 |
27 | public boolean findTarget(TreeNode root, int k) {
28 | if (root == null) return false;
29 | return traverse(root, k);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/UniqueBinarySearchTrees.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 |
3 | /**
4 | * @author Harry Tran on 7/11/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class UniqueBinarySearchTrees {
10 |
11 | int[][] f = new int[100][100];
12 | private int find(int vmin, int vmax) {
13 | if (vmin >= vmax) return 1;
14 | if (f[vmin][vmax] != -1) return f[vmin][vmax];
15 |
16 | int res = 0;
17 | for (int i = vmin; i <= vmax; ++i) {
18 | int left = find(vmin, i - 1);
19 | int right = find(i + 1, vmax);
20 | res += left * right;
21 | }
22 | f[vmin][vmax] = res;
23 | return res;
24 | }
25 |
26 | public int numTrees(int n) {
27 | if (n == 0) return 1;
28 |
29 | for (int i = 0; i < 100; ++i) {
30 | Arrays.fill(f[i], -1);
31 | }
32 |
33 | return find(1, n);
34 | }
35 |
36 | public static void main(String[] args) {
37 | UniqueBinarySearchTrees u = new UniqueBinarySearchTrees();
38 | System.out.println(u.numTrees(3));
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/UniqueBinarySearchTreesII.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | /**
5 | * @author Harry Tran on 7/10/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class UniqueBinarySearchTreesII {
11 | public class TreeNode {
12 | int val;
13 | TreeNode left;
14 | TreeNode right;
15 | TreeNode(int x) { val = x; }
16 | }
17 |
18 |
19 | private List generate(int vmin, int vmax) {
20 | List res = new ArrayList<>();
21 |
22 | if (vmin > vmax) {
23 | res.add(null);
24 | return res;
25 | }
26 |
27 | if (vmin == vmax) {
28 | res.add(new TreeNode(vmax));
29 | return res;
30 | }
31 |
32 | for (int i = vmin; i <= vmax; ++i) {
33 | List lefts = generate(vmin, i - 1);
34 | List rights = generate(i + 1, vmax);
35 | for (TreeNode left : lefts)
36 | for (TreeNode right : rights) {
37 | TreeNode tmp = new TreeNode(i);
38 | tmp.left = left;
39 | tmp.right = right;
40 | res.add(tmp);
41 | }
42 | }
43 | return res;
44 | }
45 |
46 | public List generateTrees(int n) {
47 | if (n == 0) return new ArrayList<>();
48 | return generate(1, n);
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/UniqueMorseCodeWords.java:
--------------------------------------------------------------------------------
1 | import java.util.HashSet;
2 |
3 | /**
4 | * @author Harry Tran on 6/27/18.
5 | * @project Leetcode
6 | * @email trunghieu.tran@utdallas.edu
7 | * @organization UTDallas
8 | */
9 | public class UniqueMorseCodeWords {
10 | public int uniqueMorseRepresentations(String[] words) {
11 | String[] MORSE = new String[]{".-","-...","-.-.","-..",".","..-.","--.",
12 | "....","..",".---","-.-",".-..","--","-.",
13 | "---",".--.","--.-",".-.","...","-","..-",
14 | "...-",".--","-..-","-.--","--.."};
15 |
16 | HashSet setTrans = new HashSet<>();
17 | for (String str : words) {
18 | StringBuilder tmp = new StringBuilder();
19 | for (int i = 0; i < str.length(); ++i) {
20 | tmp.append(MORSE[str.charAt(i) - 'a']);
21 | }
22 | setTrans.add(tmp.toString());
23 | }
24 | return setTrans.size();
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/ValidSudoku.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/4/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class ValidSudoku {
8 |
9 |
10 | public boolean isValidSudoku(char[][] board) {
11 | boolean[][] row = new boolean[9][9];
12 | boolean[][] col = new boolean[9][9];
13 | boolean[][] box = new boolean[9][9];
14 |
15 | for (int i = 0; i < 9; ++i)
16 | for (int j = 0; j < 9; ++j)
17 | if (board[i][j] != '.') {
18 | int num = Character.digit(board[i][j], 10);
19 | if (row[i][num]) return false;
20 | if (col[j][num]) return false;
21 | row[i][num] = true;
22 | col[j][num] = true;
23 |
24 | int boxNum = (i / 3) * 3 + (j / 3);
25 | if (box[boxNum][num]) return false;
26 | box[boxNum][num] = true;
27 | }
28 | return true;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/constructBTFromPreorderPostorder.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 11/7/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class constructBTFromPreorderPostorder {
8 | public TreeNode construct(int[] pre, int preL, int preR, int[] post, int postL, int postR) {
9 | if (preL > preR) return null;
10 | if (pre[preL] != post[postR]) return null;
11 | TreeNode root = new TreeNode(pre[preL]);
12 | if (preL == preR) {
13 | return root ;
14 | }
15 | // Left children number: [ 1 , (preR - preL)]
16 | for (int i = 1; i <= preR - preL; ++i) {
17 | TreeNode tmpL = construct(pre, preL + 1, preL + i, post, postL, postL + i - 1);
18 | if (tmpL == null) continue;
19 | TreeNode tmpR = construct(pre, preL + i + 1, preR, post, postL + i, postR - 1);
20 | if (i != preR - preL && tmpR == null) continue;
21 | root.left = tmpL;
22 | root.right = tmpR;
23 | return root;
24 | }
25 | return null;
26 | }
27 |
28 | public TreeNode constructFromPrePost(int[] pre, int[] post) {
29 | return construct(pre, 0, pre.length - 1, post, 0, post.length - 1);
30 | }
31 |
32 | public static void main(String[] args) {
33 | constructBTFromPreorderPostorder tmp = new constructBTFromPreorderPostorder();
34 | int[] pre = {1,2,4,5,3,6,7};
35 | int[] post = {4,5,2,6,7,3,1};
36 | TreeNode n = tmp.constructFromPrePost(pre, post);
37 | System.out.println(n.val);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/kthLargestElement.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 11/3/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class kthLargestElement {
8 | private int partition(int[] nums, int lo, int hi, int k) {
9 | // select a random element, and store it to the end
10 | int mid = (lo + hi) / 2;
11 | swap(nums, mid, hi);
12 | int i = lo, j = hi - 1, pivot = nums[hi];
13 |
14 | // partition
15 | while (i <= j) {
16 | if (nums[i] > pivot) {
17 | swap(nums, i, j);
18 | j--;
19 | } else ++i;
20 | }
21 |
22 | // put it into the right position
23 | swap(nums, i, hi);
24 |
25 | // check as if it is the k-smallest element
26 | int count = i - lo + 1;
27 | if (count == k) return i;
28 | if (count > k) return partition(nums, lo, i - 1, k);
29 | return partition(nums, i + 1, hi, k - count);
30 | }
31 |
32 |
33 | private void swap(int[] nums, int i, int j) {
34 | int tmp = nums[i];
35 | nums[i] = nums[j];
36 | nums[j] = tmp;
37 | }
38 |
39 | public int findKthLargest(int[] nums, int k) {
40 | int i = partition(nums, 0, nums.length - 1, nums.length - k + 1);
41 | return nums[i];
42 | }
43 |
44 | public static void main(String[] args) {
45 | kthLargestElement ke = new kthLargestElement();
46 | // int[] a = {3,2,3,1,2,4,5,5,6};
47 | int[] a = {3,2,1,3,3,3,3,5,6};
48 | System.out.println(ke.findKthLargest(a, 5));
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/longestPalindromeSubString.java:
--------------------------------------------------------------------------------
1 | /**
2 | * @author Harry Tran on 7/1/18.
3 | * @project Leetcode
4 | * @email trunghieu.tran@utdallas.edu
5 | * @organization UTDallas
6 | */
7 | public class longestPalindromeSubString {
8 | public static String longestPalindrome(String s) {
9 | int lengS = s.length();
10 |
11 | if (lengS <= 1) return s;
12 | if (lengS == 2) {
13 | if (s.charAt(0) == s.charAt(1)) return s;
14 | else return String.valueOf(s.charAt(0));
15 | }
16 |
17 | boolean[][] f = new boolean[lengS][lengS];
18 |
19 | for (int i = 0; i < lengS; ++i) f[i][i] = true;
20 | for (int i = 0; i < lengS - 1; ++i)
21 | if (s.charAt(i) == s.charAt(i + 1))
22 | f[i][i + 1] = true;
23 |
24 | for (int len = 3; len <= lengS; ++len) {
25 | for (int i = 0; i < lengS - len + 1; ++i) {
26 | int j = i + len - 1;
27 | if (s.charAt(i) == s.charAt(j))
28 | f[i][j] = f[i + 1][j - 1];
29 | }
30 | }
31 |
32 | for (int len = lengS; len >= 1; len--)
33 | for (int i = 0; i < lengS - len + 1; i++) {
34 | int j = i + len - 1;
35 | if (f[i][j]) {
36 | return s.substring(i, j + 1);
37 | }
38 | }
39 | return "";
40 | }
41 |
42 | public static void main(String[] args) {
43 | System.out.println(longestPalindrome("ccc"));
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/testHashSet.java:
--------------------------------------------------------------------------------
1 | import java.util.HashSet;
2 | import java.util.Set;
3 |
4 | /**
5 | * @author Harry Tran on 7/27/18.
6 | * @project Leetcode
7 | * @email trunghieu.tran@utdallas.edu
8 | * @organization UTDallas
9 | */
10 | public class testHashSet {
11 | //static Set set = new HashSet<>();
12 |
13 |
14 |
15 | public static void main(String[] args) {
16 | Set test = new HashSet<>();
17 | test.add(new A(1, "a"));
18 | test.add(new A(1, "a"));
19 | System.out.println(test.size());
20 |
21 | }
22 | }
23 | class A {
24 | int id;
25 | String str;
26 |
27 | public A(int id, String str) {
28 | this.id = id;
29 | this.str = str;
30 | }
31 |
32 | @Override
33 | public boolean equals(Object obj) {
34 | return this.id == ((A) obj).id && this.str.equals(((A) obj).str);
35 | // return this.equals((A)obj);
36 | }
37 |
38 | @Override
39 | public int hashCode() {
40 | return (id + ""+ str).hashCode();
41 | }
42 | }
43 |
--------------------------------------------------------------------------------