├── src ├── main │ ├── cpp │ │ ├── readme.txt │ │ ├── 015_3Sum.cpp │ │ ├── 018_4Sum.cpp │ │ ├── 143_Reorder_List.cpp │ │ ├── 040_Combination_Sum_II.cpp │ │ ├── 172_Factorial_Trailing_Zeroes.cpp │ │ ├── 088_Merge_Sorted_Array.cpp │ │ ├── 089_Gray_Code.cpp │ │ ├── 171_Excel_Sheet_Column_Number.cpp │ │ ├── 100_Same_Tree.cpp │ │ ├── 071_Simplify_Path.cpp │ │ ├── 147_Insertion_Sort_List.cpp │ │ ├── 055_Jump_Game.cpp │ │ ├── 020_Valid_Parentheses.cpp │ │ ├── 083_Remove_Duplicates_from_Sorted_List.cpp │ │ ├── 104_Maximum_Depth_of_Binary_Tree.cpp │ │ ├── 058_Length_of_Last_Word.cpp │ │ ├── 190_Reverse_Bits.cpp │ │ ├── 010_Regular_Expression_Matching.cpp │ │ ├── 011_Container_With_Most_Water.cpp │ │ ├── 019_Remove_Nth_Node_From_End_of_List.cpp │ │ ├── 141_Linked_List_Cycle.cpp │ │ ├── 108_Convert_Sorted_Array_to_Binary_Search_Tree.cpp │ │ ├── 150_Evaluate_Reverse_Polish_Notation.cpp │ │ └── 092_Reverse_Linked_List_II.cpp │ └── java │ │ └── com │ │ └── freetymekiyan │ │ ├── database │ │ ├── easy │ │ │ ├── SecondHighestSalary.sql │ │ │ ├── EmployeesEarningMore.sql │ │ │ └── CombineTwoTables.sql │ │ └── medium │ │ │ ├── ConsecutiveNumbers.sql │ │ │ ├── NthHighestSalary.sql │ │ │ └── RankScores.sql │ │ ├── algorithms │ │ ├── other │ │ │ ├── CanBePalindrome.java │ │ │ ├── QuickUnionUF.java │ │ │ ├── SubstringsStartEndWith1.java │ │ │ ├── DeleteLinkedListNode.java │ │ │ ├── CharFrequencyOrderOfAString.java │ │ │ ├── RunLengthEncoding.java │ │ │ ├── HeapSort.java │ │ │ ├── TreeDiameter.java │ │ │ ├── WiggleSort.java │ │ │ ├── Celebrity.java │ │ │ ├── DeepestNode.java │ │ │ ├── RateLimiter.java │ │ │ ├── FindSecondLargest.java │ │ │ ├── DeepestLeftLeafNode.java │ │ │ ├── MostFrequentElementInArray.java │ │ │ ├── GetNumberOfOnes.java │ │ │ ├── AddWithoutOperators.java │ │ │ ├── BinaryTreeLongestPath.java │ │ │ ├── FindDup.java │ │ │ ├── PeekIterator.java │ │ │ ├── Astroid01.java │ │ │ ├── Fib.java │ │ │ └── LowestCommonAncestor.java │ │ └── level │ │ │ ├── easy │ │ │ ├── DeleteNodeInLinkedList.java │ │ │ ├── FactorialTrailingZeroes.java │ │ │ ├── PowerOfTwo.java │ │ │ ├── Numberof1Bits.java │ │ │ ├── ExcelSheetColNumber.java │ │ │ ├── SameTree.java │ │ │ ├── LengthOfLastWord.java │ │ │ ├── MaxDepth.java │ │ │ ├── MinimumDepthOfBinaryTree.java │ │ │ ├── CountPrimes.java │ │ │ ├── RangeSumQueryImmutable.java │ │ │ ├── NthDigit.java │ │ │ ├── CountAndSay.java │ │ │ ├── RemoveElement.java │ │ │ ├── RemoveNthNodeFromEnd.java │ │ │ ├── SumOfTwoIntegers.java │ │ │ ├── PascalsTriangle2.java │ │ │ ├── PowerOfFour.java │ │ │ ├── MovingAverageFromDataStream.java │ │ │ ├── PowerOfThree.java │ │ │ ├── RansomNote.java │ │ │ ├── PascalsTriangle.java │ │ │ ├── PathSum.java │ │ │ ├── BestTimetoBuyandSellStock1.java │ │ │ ├── MeetingRooms.java │ │ │ └── FindTheDifference.java │ │ │ ├── medium │ │ │ ├── FourSumTreeMap.java │ │ │ ├── FindMinimuminRotatedSortedArray.java │ │ │ ├── SearchInsertPosition.java │ │ │ ├── SingleNumber2.java │ │ │ ├── LexicographicalNumbers.java │ │ │ ├── LinkedListCycle.java │ │ │ ├── CoinChange.java │ │ │ ├── InsertionSortList.java │ │ │ ├── BestTimeStock2.java │ │ │ ├── Pow.java │ │ │ ├── IntegerBreak.java │ │ │ ├── SingleNumber3.java │ │ │ ├── MaxProductSubArr.java │ │ │ ├── RemoveDuplicatesFromSortedArray2.java │ │ │ ├── LargestNumber_shuna.java │ │ │ ├── ConvertSortedArrToBST.java │ │ │ ├── LineReflection.java │ │ │ ├── RestoreIpAddresses.java │ │ │ ├── ReorderList.java │ │ │ └── SumRootToLeafNumbers.java │ │ │ └── hard │ │ │ ├── FindMinimumInRotatedSortedArray2.java │ │ │ └── FirstMissingPositive.java │ │ └── datastructures │ │ ├── ST.java │ │ ├── LinkedListBag.java │ │ ├── LinkedListQueue.java │ │ └── LinkedListStack.java └── test │ └── java │ └── com │ └── freetymekiyan │ ├── algorithms │ ├── level │ │ ├── hard │ │ │ ├── StrobogrammaticNumber3Test.java │ │ │ ├── MaximumSumOf3NonOverlappingSubarraysTest.java │ │ │ ├── RegularExpressionMatchingTest.java │ │ │ ├── SearchInRotatedSortedArrayTest.java │ │ │ ├── SerializeAndDeserializeBinaryTreeTest.java │ │ │ ├── FrogJumpTest.java │ │ │ ├── MinimumWindowSubsequenceTest.java │ │ │ ├── DecodeWays2Test.java │ │ │ ├── MedianOfTwoSortedArraysTest.java │ │ │ ├── TextJustificationTest.java │ │ │ ├── MinimumWindowSubstringTest.java │ │ │ ├── PrefixAndSuffixSearchTest.java │ │ │ ├── LongestSubstringWithAtMostTwoDistinctCharactersTest.java │ │ │ ├── PalindromePairsTest.java │ │ │ ├── IntegerToEnglishWordsTest.java │ │ │ ├── LongestConsecutiveSeqTest.java │ │ │ └── WordLadder2Test.java │ │ ├── medium │ │ │ ├── DeleteAndEarnTest.java │ │ │ ├── ValidParenthesisStringTest.java │ │ │ ├── SimplifyPathTest.java │ │ │ ├── ExclusiveTimeOfFunctionsTest.java │ │ │ ├── MonotoneIncreasingDigitsTest.java │ │ │ ├── MaximumSwapTest.java │ │ │ ├── SubArraySumEqualsKTest.java │ │ │ ├── ContinuousSubarraySumTest.java │ │ │ ├── GraphValidTreeTest.java │ │ │ ├── NetworkDelayTimeTest.java │ │ │ ├── BestTimeStockTest.java │ │ │ ├── MinimumSwapsToMakeSequencesIncreasingTest.java │ │ │ ├── IncreasingTripletSubsequenceTest.java │ │ │ ├── NumberOfLongestIncreasingSubsequenceTest.java │ │ │ ├── HIndex2Test.java │ │ │ ├── BinaryTreeInOrderTraversalTest.java │ │ │ ├── PalindromicSubstringsTest.java │ │ │ ├── DailyTemperaturesTest.java │ │ │ ├── WordLadderTest.java │ │ │ ├── CombinationSum4Test.java │ │ │ ├── LongestIncreasingSubsequenceTest.java │ │ │ ├── ClosestLeafInABinaryTreeTest.java │ │ │ ├── WordSearchTest.java │ │ │ ├── MissingRangesTest.java │ │ │ ├── SqrtTest.java │ │ │ ├── ProductofArrayExceptSelfTest.java │ │ │ ├── NumberOfCornerRectanglesTest.java │ │ │ ├── NonOverlappingIntervalsTest.java │ │ │ ├── IsGraphBipartiteTest.java │ │ │ ├── NumberOfIslandsTest.java │ │ │ ├── FindRightIntervalTest.java │ │ │ └── PermutationInStringTest.java │ │ └── easy │ │ │ ├── PalindromeLinkedListTest.java │ │ │ ├── TwoSumTest.java │ │ │ ├── ImplementStrStrTest.java │ │ │ ├── RomanToIntegerTest.java │ │ │ ├── FizzBuzzTest.java │ │ │ ├── StrobogrammaticNumberTest.java │ │ │ ├── ValidPalindromeTest.java │ │ │ ├── ValidWordAbbreviationTest.java │ │ │ ├── ValidParenthesesTest.java │ │ │ ├── AddBinaryTest.java │ │ │ ├── AverageOfLevelsInBinaryTreeTest.java │ │ │ ├── FindSmallestLetterGreaterThanTargetTest.java │ │ │ ├── MoveZeroesTest.java │ │ │ └── ValidPalindrome2Test.java │ └── other │ │ ├── FindSecondLargestTest.java │ │ ├── ValidParentheseStringTest.java │ │ ├── MedianOfNSortedArraysTest.java │ │ ├── GraphPathsTest.java │ │ ├── ThreeSumReuseOnceTest.java │ │ ├── UpdateTreeValueTest.java │ │ ├── TotalNumberOfSecondsTest.java │ │ ├── AddTwoDoublesTest.java │ │ ├── BinaryTreeLongestPathTest.java │ │ ├── MinimumDistanceOfTwoSortedArraysTest.java │ │ ├── DoublyLinkedListToBinarySearchTreeTest.java │ │ ├── AlmostBalancedTreeTest.java │ │ └── LCAOfDeepestLeavesTest.java │ └── datastructures │ └── BinaryIndexedTreeTest.java ├── Leetcode.xlsx ├── Leetcode.numbers ├── resources └── leetcode Frequencey.xlsx ├── .gitignore └── LICENSE /src/main/cpp/readme.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Leetcode.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FreeTymeKiyan/LeetCode-Sol-Res/HEAD/Leetcode.xlsx -------------------------------------------------------------------------------- /Leetcode.numbers: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FreeTymeKiyan/LeetCode-Sol-Res/HEAD/Leetcode.numbers -------------------------------------------------------------------------------- /src/main/cpp/015_3Sum.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FreeTymeKiyan/LeetCode-Sol-Res/HEAD/src/main/cpp/015_3Sum.cpp -------------------------------------------------------------------------------- /src/main/cpp/018_4Sum.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FreeTymeKiyan/LeetCode-Sol-Res/HEAD/src/main/cpp/018_4Sum.cpp -------------------------------------------------------------------------------- /src/main/cpp/143_Reorder_List.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FreeTymeKiyan/LeetCode-Sol-Res/HEAD/src/main/cpp/143_Reorder_List.cpp -------------------------------------------------------------------------------- /resources/leetcode Frequencey.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FreeTymeKiyan/LeetCode-Sol-Res/HEAD/resources/leetcode Frequencey.xlsx -------------------------------------------------------------------------------- /src/main/cpp/040_Combination_Sum_II.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FreeTymeKiyan/LeetCode-Sol-Res/HEAD/src/main/cpp/040_Combination_Sum_II.cpp -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | 14 | Resources/CleanCodeHandbook_v1.0.1.pdf 15 | 16 | # Project and Build Files 17 | .idea/ 18 | LeetCode-Sol-Res.iml 19 | out/ 20 | 21 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/StrobogrammaticNumber3Test.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | import static org.testng.Assert.*; 7 | 8 | public class StrobogrammaticNumber3Test { 9 | 10 | @Test 11 | public void testStrobogrammaticInRange() { 12 | StrobogrammaticNumber3 s = new StrobogrammaticNumber3(); 13 | Assert.assertEquals(s.strobogrammaticInRange("50", "100"), 3); 14 | } 15 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/DeleteAndEarnTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | public class DeleteAndEarnTest { 7 | 8 | @Test 9 | public void testDeleteAndEarnExamples() { 10 | int[] nums = new int[0]; 11 | DeleteAndEarn d = new DeleteAndEarn(); 12 | Assert.assertEquals(d.deleteAndEarn(nums), 0); 13 | nums = new int[]{3, 4, 2}; 14 | Assert.assertEquals(d.deleteAndEarn(nums), 6); 15 | } 16 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/ValidParenthesisStringTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | import static org.testng.Assert.*; 7 | 8 | public class ValidParenthesisStringTest { 9 | 10 | @Test 11 | public void testCheckValidString() { 12 | String string = "(())((())()()(*)(*()(())())())()()((()())((()))(*"; 13 | ValidParenthesisString v = new ValidParenthesisString(); 14 | Assert.assertFalse(v.checkValidString(string)); 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/database/easy/SecondHighestSalary.sql: -------------------------------------------------------------------------------- 1 | Write a SQL query to get the second highest salary from the Employee table. 2 | 3 | +----+--------+ 4 | | Id | Salary | 5 | +----+--------+ 6 | | 1 | 100 | 7 | | 2 | 200 | 8 | | 3 | 300 | 9 | +----+--------+ 10 | For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return null. 11 | 12 | ------ 13 | Get second highest salary lower than highest one 14 | ------ 15 | SELECT max(Salary) 16 | FROM Employee 17 | WHERE Salary < (SELECT max(Salary) FROM Employee) -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/PalindromeLinkedListTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import com.freetymekiyan.algorithms.utils.Utils.ListNode; 5 | import org.testng.Assert; 6 | import org.testng.annotations.Test; 7 | 8 | public class PalindromeLinkedListTest { 9 | 10 | @Test 11 | public void testIsPalindrome() { 12 | ListNode h = Utils.buildLinkedList(new int[]{1, 2}); 13 | PalindromeLinkedList p = new PalindromeLinkedList(); 14 | Assert.assertFalse(p.isPalindrome(h)); 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/CanBePalindrome.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Given a string, return whether the characters in the string can form a palindrome. 5 | * 6 | * Follow up, generate all possible combinations. 7 | */ 8 | public class CanBePalindrome { 9 | 10 | /** 11 | * use a hash table to store count 12 | * iterate the hash table to check whether no or only 1 character appeared odd times 13 | */ 14 | public boolean canBePalindrome(String s) { 15 | return false; 16 | } 17 | 18 | public static void main(String[] args) { 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/TwoSumTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import org.junit.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | public class TwoSumTest { 7 | 8 | @Test 9 | public void testTwoSum() { 10 | TwoSum t = new TwoSum(); 11 | int[] numbers = {3, 2, 4}; // 6 = 3 + 3 12 | int target = 6; 13 | int[] res = t.twoSum(numbers, target); 14 | Assert.assertArrayEquals(new int[]{1, 2}, res); 15 | 16 | numbers = new int[]{2, 7, 11, 15}; 17 | target = 9; 18 | res = t.twoSum(numbers, target); 19 | Assert.assertArrayEquals(new int[]{0, 1}, res); 20 | } 21 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/MaximumSumOf3NonOverlappingSubarraysTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import org.testng.Assert; 5 | import org.testng.annotations.Test; 6 | 7 | public class MaximumSumOf3NonOverlappingSubarraysTest { 8 | 9 | @Test 10 | public void testMaxSumOfThreeSubarrays() { 11 | int[] input = {1, 2, 1, 2, 6, 7, 6, 1}; 12 | MaximumSumOf3NonOverlappingSubarrays m = new MaximumSumOf3NonOverlappingSubarrays(); 13 | int[] output = m.maxSumOfThreeSubarrays(input, 2); 14 | Assert.assertTrue(Utils.compareArrays(output, new int[]{0, 3, 5})); 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/QuickUnionUF.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Created by kiyan on 6/23/16. 5 | */ 6 | public class QuickUnionUF { 7 | 8 | private int[] id; 9 | 10 | public QuickUnionUF(int N) { 11 | id = new int[N]; 12 | for (int i = 0; i < N; i++) id[i] = i; 13 | } 14 | 15 | private int root(int i) { 16 | while (i != id[i]) i = id[i]; 17 | return i; 18 | } 19 | 20 | public boolean connected(int p, int q) { 21 | return root(p) == root(q); 22 | } 23 | 24 | public void union(int p, int q) { 25 | int i = root(p); 26 | int j = root(q); 27 | id[i] = j; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/SimplifyPathTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | public class SimplifyPathTest { 7 | 8 | @Test 9 | public void testSimplifyPath() { 10 | SimplifyPath s = new SimplifyPath(); 11 | Assert.assertEquals(s.simplifyPath("/home/"), "/home"); 12 | Assert.assertEquals(s.simplifyPath("/a/./b/../../c/"), "/c"); 13 | Assert.assertEquals(s.simplifyPath("/../"), "/"); 14 | Assert.assertEquals(s.simplifyPath("/home//foo/"), "/home/foo"); 15 | Assert.assertEquals(s.simplifyPath("/a/./b///../c/../././../d/..//../e/./f/./g/././//.//h///././/..///"), "/e/f/g"); 16 | } 17 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/ImplementStrStrTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | public class ImplementStrStrTest { 7 | 8 | @Test 9 | public void testStrStr() { 10 | ImplementStrStr i = new ImplementStrStr(); 11 | String str1 = "14531234"; 12 | String str2 = "123"; 13 | String str3 = "1123"; 14 | String str4 = "1245"; 15 | String str5 = "12121212123"; 16 | Assert.assertEquals(i.strStr(str1, str2), 4); 17 | Assert.assertEquals(i.strStr(str3, str2), 1); 18 | Assert.assertEquals(i.strStr(str4, str2), -1); 19 | Assert.assertEquals(i.strStr(str5, str2), 8); 20 | } 21 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/ExclusiveTimeOfFunctionsTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import org.testng.Assert; 5 | import org.testng.annotations.Test; 6 | 7 | import java.util.Collections; 8 | import java.util.List; 9 | 10 | public class ExclusiveTimeOfFunctionsTest { 11 | 12 | 13 | @Test 14 | public void testExclusiveTimeExamples() { 15 | List logs = Collections.unmodifiableList(List.of("0:start:0", "1:start:2", "1:end:5", "0:end:6")); 16 | int[] output = {3, 4}; 17 | ExclusiveTimeOfFunctions e = new ExclusiveTimeOfFunctions(); 18 | Assert.assertTrue(Utils.compareArrays(e.exclusiveTime(2, logs), output)); 19 | } 20 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/RegularExpressionMatchingTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | public class RegularExpressionMatchingTest { 7 | 8 | @Test 9 | public void testIsMatch() { 10 | RegularExpressionMatching r = new RegularExpressionMatching(); 11 | Assert.assertFalse(r.isMatch("aa", "a")); 12 | Assert.assertTrue(r.isMatch("aa", "aa")); 13 | Assert.assertFalse(r.isMatch("aaa", "aa")); 14 | Assert.assertTrue(r.isMatch("aa", "a*")); 15 | Assert.assertTrue(r.isMatch("aa", ".*")); 16 | Assert.assertTrue(r.isMatch("ab", ".*")); 17 | Assert.assertTrue(r.isMatch("aab", "c*a*b")); 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/cpp/172_Factorial_Trailing_Zeroes.cpp: -------------------------------------------------------------------------------- 1 | // 172. Factorial Trailing Zeroes 2 | /** 3 | * Given an integer n, return the number of trailing zeroes in n!. 4 | * 5 | * Note: Your solution should be in logarithmic time complexity. 6 | * 7 | * Tags: Math 8 | * 9 | * Similar Problems: (H) Number of Digit One 10 | */ 11 | 12 | 13 | #include "stdafx.h" 14 | 15 | // in the factorial, there are many 2s, so it is enough just to count the number of 5 16 | class Solution { 17 | public: 18 | int trailingZeroes(int n) { 19 | int count = 0; 20 | while (n > 0) 21 | { 22 | n /= 5; 23 | count += n; 24 | } 25 | 26 | return count; 27 | } 28 | }; 29 | 30 | int _tmain(int argc, _TCHAR* argv[]) 31 | { 32 | return 0; 33 | } 34 | 35 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/SubstringsStartEndWith1.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Given a binary string, count number of substrings that start and end with 1. 5 | * 6 | * Tags: String, Math 7 | */ 8 | class SubstringsStartEndWith1 { 9 | public static void main(String[] args) { 10 | 11 | } 12 | 13 | /** 14 | * O(n) Time 15 | * Count # of 1's in the string and return combinations c*(c-1) / 2 16 | */ 17 | public int substringStartEnd(String s) { 18 | if (s == null || s.length() == 0) return 0; 19 | int count = 0; 20 | for (int i = s.length() - 1; i >= 0; i--) 21 | if (s.charAt(i) == '1') count++; 22 | return count * (count - 1) / 2; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/MonotoneIncreasingDigitsTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.junit.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | public class MonotoneIncreasingDigitsTest { 7 | 8 | @Test 9 | public void testMonotoneIncreasingDigitsExamples() { 10 | int N = 10; 11 | int output = 9; 12 | MonotoneIncreasingDigits m = new MonotoneIncreasingDigits(); 13 | Assert.assertEquals(m.monotoneIncreasingDigits(N), output); 14 | N = 1234; 15 | output = 1234; 16 | Assert.assertEquals(m.monotoneIncreasingDigits(N), output); 17 | N = 332; 18 | output = 299; 19 | Assert.assertEquals(m.monotoneIncreasingDigits(N), output); 20 | } 21 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/MaximumSwapTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | import java.util.Collections; 7 | import java.util.List; 8 | 9 | public class MaximumSwapTest { 10 | 11 | private static final List INPUTS = Collections.unmodifiableList(List.of(2736, 9973)); 12 | private static final List OUTPUTS = Collections.unmodifiableList(List.of(7236, 9973)); 13 | 14 | @Test 15 | public void testMaximumSwapExamples() { 16 | MaximumSwap m = new MaximumSwap(); 17 | for (int i = 0; i < INPUTS.size(); i++) { 18 | Assert.assertEquals(m.maximumSwap(INPUTS.get(i)), OUTPUTS.get(i).intValue()); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/database/medium/ConsecutiveNumbers.sql: -------------------------------------------------------------------------------- 1 | Write a SQL query to find all numbers that appear at least three times consecutively. 2 | 3 | +----+-----+ 4 | | Id | Num | 5 | +----+-----+ 6 | | 1 | 1 | 7 | | 2 | 1 | 8 | | 3 | 1 | 9 | | 4 | 2 | 10 | | 5 | 1 | 11 | | 6 | 2 | 12 | | 7 | 2 | 13 | +----+-----+ 14 | For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times. 15 | 16 | ------ 17 | 18 | ------ 19 | 20 | SELECT DISTINCT num 21 | FROM 22 | (SELECT num, 23 | CASE 24 | when @record = num then @count:=@count+1 25 | when @record <> @record:=num then @count:=1 end as n 26 | FROM 27 | Logs ,(SELECT @count:=0,@record:=(SELECT num FROM Logs LIMIT 0,1)) r 28 | ) a 29 | WHERE a.n>=3 -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/DeleteLinkedListNode.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Given only a pointer to a node to be deleted in a singly linked list, how do 5 | * you delete it? 6 | * 7 | * Tags: LinkedList 8 | */ 9 | class DeleteLinkedListNode { 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | /** 15 | * Copy the data from the next node to the node to be deleted and delete 16 | * the next node 17 | */ 18 | void delete(Node n) { 19 | if (n.next == null) n = null; 20 | Node temp = n.next; 21 | n.val = temp.val; 22 | n.next = temp.next; 23 | temp = null; 24 | } 25 | 26 | class Node { 27 | int val; 28 | Node next; 29 | } 30 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/RomanToIntegerTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class RomanToIntegerTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{"DCXXI", 621}, 13 | new Object[]{"DCXXIV", 624}, 14 | new Object[]{"I", 1}, 15 | }; 16 | } 17 | 18 | @Test(dataProvider = "examples") 19 | public void testRomanToInt(String romans, int expected) { 20 | RomanToInteger r = new RomanToInteger(); 21 | Assert.assertEquals(r.romanToInt(romans), expected); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/database/medium/NthHighestSalary.sql: -------------------------------------------------------------------------------- 1 | Write a SQL query to get the nth highest salary from the Employee table. 2 | 3 | +----+--------+ 4 | | Id | Salary | 5 | +----+--------+ 6 | | 1 | 100 | 7 | | 2 | 200 | 8 | | 3 | 300 | 9 | +----+--------+ 10 | For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null. 11 | 12 | ------ 13 | Decalare M because LIMIT do not accept constant 14 | Then order by Salary and 15 | ------ 16 | 17 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 18 | BEGIN 19 | DECLARE M INT; 20 | SET M=N-1; 21 | RETURN ( 22 | # Write your MySQL query statement below. 23 | SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT M, 1 24 | ); 25 | END -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/SearchInRotatedSortedArrayTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | public class SearchInRotatedSortedArrayTest { 7 | 8 | private static final int[] nums = {5, 1, 3}; 9 | private static final int target = 5; 10 | private static final int expected = 0; 11 | 12 | @Test 13 | public void testSearch() { 14 | SearchInRotatedSortedArray s = new SearchInRotatedSortedArray(); 15 | Assert.assertEquals(s.search(nums, target), expected); 16 | } 17 | 18 | @Test 19 | public void testSearch2() { 20 | SearchInRotatedSortedArray s = new SearchInRotatedSortedArray(); 21 | Assert.assertEquals(s.search2(nums, target), expected); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/DeleteNodeInLinkedList.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils.ListNode; 4 | 5 | /** 6 | * Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 7 | *

8 | * Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should 9 | * become 1 -> 2 -> 4 after calling your function. 10 | *

11 | * Tags: LinkedList 12 | * Similar Problems: (E) Remove Linked List Elements 13 | */ 14 | public class DeleteNodeInLinkedList { 15 | 16 | public void deleteNode(ListNode node) { 17 | if (node == null || node.next == null) return; 18 | node.val = node.next.val; 19 | node.next = node.next.next; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/SerializeAndDeserializeBinaryTreeTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import com.freetymekiyan.algorithms.utils.Utils.TreeNode; 5 | import org.testng.Assert; 6 | import org.testng.annotations.Test; 7 | 8 | public class SerializeAndDeserializeBinaryTreeTest { 9 | 10 | @Test 11 | public void testExample() { 12 | TreeNode root = Utils.buildBinaryTree(new Integer[]{1, 2, null, null, 3, 4, null, null, 5}); 13 | SerializeAndDeserializeBinaryTree s = new SerializeAndDeserializeBinaryTree(); 14 | String output = s.serialize(root); 15 | TreeNode newRoot = s.deserialize(output); 16 | String output2 = s.serialize(newRoot); 17 | Assert.assertEquals(output, output2); 18 | } 19 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/other/FindSecondLargestTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class FindSecondLargestTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[]{3, 1, 2}, 2}, 13 | new Object[]{new int[]{5, 2, 3, 4}, 4}, 14 | new Object[]{new int[]{-5, 2, 3, 4}, 3} 15 | }; 16 | } 17 | 18 | @Test(dataProvider = "examples") 19 | public void testFindSecondLargest(int[] nums, int expected) { 20 | FindSecondLargest f = new FindSecondLargest(); 21 | Assert.assertEquals(f.findSecondLargest(nums), expected); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/FactorialTrailingZeroes.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * Given an integer n, return the number of trailing zeroes in n!. 5 | *

6 | * Note: Your solution should be in logarithmic time complexity. 7 | *

8 | * Tag: Math 9 | */ 10 | class FactorialTrailingZeroes { 11 | 12 | public static void main(String[] args) { 13 | System.out.println(trailingZeroes(20)); 14 | } 15 | 16 | /** 17 | * O(log5-n) 18 | */ 19 | public static int trailingZeroes(int n) { 20 | int r = 0; 21 | while (n > 0) { 22 | n /= 5; 23 | r += n; // add # of 5 in n 24 | } 25 | return r; 26 | } 27 | 28 | /** 29 | * Recursive 30 | */ 31 | public static int trailingZeroesB(int n) { 32 | return n <= 0 ? 0 : n / 5 + trailingZeroes(n / 5); 33 | } 34 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/FrogJumpTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.junit.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class FrogJumpTest { 8 | 9 | @DataProvider 10 | public Object[][] testCases() { 11 | return new Object[][]{ 12 | new Object[]{new int[]{0, 1, 3, 4, 5, 7, 9, 10, 12}, true}, 13 | new Object[]{new int[]{0}, true}, 14 | new Object[]{new int[]{1}, true}, 15 | new Object[]{new int[]{0, 1}, true}, 16 | new Object[]{new int[]{0, 2}, false}}; 17 | } 18 | 19 | @Test 20 | public void testCanCross(final int[] stones, final boolean expected) { 21 | final FrogJump f = new FrogJump(); 22 | final boolean result = f.canCross(stones); 23 | Assert.assertTrue(result == expected); 24 | } 25 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/SubArraySumEqualsKTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class SubArraySumEqualsKTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[]{1, 1, 1}, 2, 2}, 13 | new Object[]{new int[]{1, 1, 1, 1}, 2, 3}, 14 | new Object[]{new int[]{-1, -1, -1, -1}, -2, 3}, 15 | }; 16 | } 17 | 18 | @Test(dataProvider = "examples") 19 | public void testSubarraySum(int[] nums, int k, int expected) { 20 | SubArraySumEqualsK s = new SubArraySumEqualsK(); 21 | Assert.assertEquals(s.subarraySum(nums, k), expected); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/PowerOfTwo.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * 231. Power of Two 5 | *

6 | * Given an integer, write a function to determine if it is a power of two. 7 | *

8 | * Tags: Math, Bit Manipulation 9 | * Similar Problems: (E) Number of 1 Bits, (E) Power of Three, (E) Power of Four 10 | */ 11 | public class PowerOfTwo { 12 | 13 | /** 14 | * 2's power only has a single 1 at the highest bit. 15 | * So n & (n - 1) should be 0. 16 | * Check also if n is positive. 17 | */ 18 | public boolean isPowerOfTwo(int n) { 19 | return n > 0 && (n & (n - 1)) == 0; 20 | } 21 | 22 | /** 23 | * One-liner using Integer.bitCount because only a single bit should be 1 for 2's power. 24 | */ 25 | public boolean isPowerOfTwoB(int n) { 26 | return n > 0 && Integer.bitCount(n) == 1; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/FizzBuzzTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | import java.util.List; 7 | 8 | public class FizzBuzzTest { 9 | 10 | private static final List EXPECTED = List.of( 11 | "1", 12 | "2", 13 | "Fizz", 14 | "4", 15 | "Buzz", 16 | "Fizz", 17 | "7", 18 | "8", 19 | "Fizz", 20 | "Buzz", 21 | "11", 22 | "Fizz", 23 | "13", 24 | "14", 25 | "FizzBuzz"); 26 | 27 | @Test 28 | public void testFizzBuzz() { 29 | FizzBuzz f = new FizzBuzz(); 30 | Assert.assertEquals(f.fizzBuzz(15), EXPECTED); 31 | } 32 | 33 | @Test 34 | public void testFizzBuzz2() { 35 | FizzBuzz f = new FizzBuzz(); 36 | Assert.assertEquals(f.fizzBuzz2(15), EXPECTED); 37 | } 38 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/StrobogrammaticNumberTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class StrobogrammaticNumberTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{"68", false}, 13 | new Object[]{"69", true}, 14 | new Object[]{"80", true}, 15 | new Object[]{"818", true} 16 | }; 17 | } 18 | 19 | @Test(dataProvider = "examples") 20 | public void testIsStrobogrammatic(String num, boolean expected) { 21 | StrobogrammaticNumber s = new StrobogrammaticNumber(); 22 | Assert.assertEquals(s.isStrobogrammatic(num), expected); 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/FourSumTreeMap.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import java.util.List; 4 | 5 | class FourSumTreeMap { 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | public static List> fourSum(int[] num, int target) { 11 | // TODO: 12/1/17 implement this method 12 | return null; 13 | } 14 | 15 | /** 16 | * regard two integers as a pair 17 | */ 18 | class Pair { 19 | int a; 20 | int ai; 21 | int b; 22 | int bi; 23 | 24 | public Pair(int a, int ai, int b, int bi) { 25 | this.a = a; 26 | this.ai = ai; 27 | this.b = b; 28 | this.bi = bi; 29 | } 30 | 31 | boolean same(Pair p) { 32 | return p != null && p.a == a && p.b == b; 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/ValidPalindromeTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class ValidPalindromeTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{"A man, a plan, a canal: Panama", true}, 13 | new Object[]{"race a car", false}, 14 | new Object[]{"a", true}, 15 | new Object[]{"0P", false} 16 | }; 17 | } 18 | 19 | @Test(dataProvider = "examples") 20 | public void testIsPalindrome(String input, boolean expected) { 21 | ValidPalindrome v = new ValidPalindrome(); 22 | Assert.assertEquals(v.isPalindrome(input), expected); 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/Numberof1Bits.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * Number of 1 Bits 5 | * Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). 6 | * For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. 7 | * Tags Bit Manipulation 8 | * Similar Problems: (E) Reverse Bits (E) Power of Two (M) Counting Bits 9 | * @author chenshuna 10 | */ 11 | 12 | public class Numberof1Bits { 13 | public static int hammingWeight(int n) { 14 | int res = 0; 15 | while(n != 0){ 16 | n = n & (n - 1); 17 | res++; 18 | } 19 | return res; 20 | } 21 | 22 | public static void main(String[] args) { 23 | System.out.print(hammingWeight(13)); 24 | } 25 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/datastructures/ST.java: -------------------------------------------------------------------------------- 1 | /** 2 | * API 3 | * ST(): create a symbol table 4 | * void put(Key key, Value val): put key-value pair into the table 5 | * Value get(Key key): value paired with key 6 | * void delete(Key key): remove key and its value from table 7 | * boolean contains(Key key): is there a value paired with key? 8 | * boolean isEmpty(): is the table empty? 9 | * int size(): number of key-value pairs in the table 10 | * Iterable keys(): all the keys in the table 11 | *

12 | * Created by kiyan on 5/26/16. 13 | */ 14 | public class ST { 15 | 16 | public void delete(Key key) { 17 | put(key, null); 18 | } 19 | 20 | private void put(Key key, Value val) { 21 | } 22 | 23 | public boolean contains(Key key) { 24 | return get(key) != null; 25 | } 26 | 27 | private Key get(Key key) { 28 | return null; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/ContinuousSubarraySumTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | public class ContinuousSubarraySumTest { 7 | 8 | @Test 9 | public void testCheckSubarraySum() throws Exception { 10 | int[] input = {23, 2, 6, 4, 7}; 11 | int k = 6; 12 | ContinuousSubarraySum c = new ContinuousSubarraySum(); 13 | Assert.assertTrue(c.checkSubarraySum(input, k)); 14 | Assert.assertTrue(c.checkSubarraySum2(input, k)); 15 | k = 0; 16 | Assert.assertFalse(c.checkSubarraySum(input, k)); 17 | Assert.assertFalse(c.checkSubarraySum2(input, k)); 18 | input = new int[]{0, 1, 0}; 19 | k = 0; 20 | Assert.assertFalse(c.checkSubarraySum(input, k)); 21 | Assert.assertFalse(c.checkSubarraySum2(input, k)); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/cpp/088_Merge_Sorted_Array.cpp: -------------------------------------------------------------------------------- 1 | //88. Merge Sorted Array 2 | /* 3 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 4 | 5 | Tag: Array, Two pointers 6 | 7 | Author: Xinyu Liu 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | using namespace std; 14 | 15 | class Solution { 16 | public: 17 | void merge(vector& nums1, int m, vector& nums2, int n) { 18 | int i = m-1, j = n-1, fin = m+n-1; 19 | while(j >= 0) 20 | nums1[fin--] = (i >= 0 && nums1[i] > nums2[j]) ? nums1[i--] : nums2[j--]; 21 | } 22 | }; 23 | 24 | void main(){ 25 | int n1[] = {1,2,3}; 26 | vector nums1(6); 27 | nums1.at(0) = n1[0]; 28 | nums1.at(1) = n1[1]; 29 | nums1.at(2) = n1[2]; 30 | int n2[] = {1,2,4}; 31 | vector nums2(n2, n2+sizeof(n2)/sizeof(int)); 32 | Solution sol; 33 | sol.merge(nums1,3,nums2,3); 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/GraphValidTreeTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class GraphValidTreeTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{5, new int[][]{{0, 1}, {0, 2}, {0, 3}, {1, 4}}, true}, 13 | new Object[]{5, new int[][]{{0, 1}, {1, 2}, {2, 3}, {1, 3}, {1, 4}}, false}, 14 | new Object[]{5, new int[][]{{0, 1}, {0, 4}, {1, 4}, {2, 3}}, false} 15 | }; 16 | } 17 | 18 | @Test(dataProvider = "examples") 19 | public void testValidTree(int n, int[][] edges, boolean output) { 20 | GraphValidTree g = new GraphValidTree(); 21 | Assert.assertEquals(g.validTree(n, edges), output); 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/cpp/089_Gray_Code.cpp: -------------------------------------------------------------------------------- 1 | //89. Gray Code 2 | /* 3 | The gray code is a binary numeral system where two successive values differ in only one bit. 4 | Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. 5 | 6 | For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: 7 | 00 - 0 8 | 01 - 1 9 | 11 - 3 10 | 10 - 2 11 | 12 | Tag: Backtracking 13 | 14 | Author: Xinyu Liu 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | using namespace std; 21 | 22 | class Solution { 23 | public: 24 | vector grayCode(int n) { 25 | vector v; 26 | for (int i = 0; i < 1<>1)^i ); 28 | } 29 | return v; 30 | } 31 | }; 32 | 33 | void main(){ 34 | unsigned int num = 0; 35 | Solution sol; 36 | vector a = sol.grayCode(num); 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/CharFrequencyOrderOfAString.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import java.util.TreeMap; 4 | 5 | /** 6 | * Given a String, output the characters in the String according to its frequency. 7 | *

8 | * For example, 9 | * given "banana", the output should be “a 3, n 2, b 1” 10 | */ 11 | public class CharFrequencyOrderOfAString { 12 | 13 | public static void main(String[] args) { 14 | CharFrequencyOrderOfAString c = new CharFrequencyOrderOfAString(); 15 | c.output("banana"); 16 | } 17 | 18 | public void output(String s) { 19 | TreeMap map = new TreeMap<>(); 20 | for (int i = 0; i < s.length(); i++) { 21 | char key = s.charAt(i); 22 | map.put(key, map.containsKey(key)? map.get(key) + 1 : 1); 23 | } 24 | while (map.size() > 0) 25 | System.out.println(map.pollFirstEntry()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/cpp/171_Excel_Sheet_Column_Number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a column title as appear in an Excel sheet, return its corresponding column number. 3 | 4 | * For example: 5 | 6 | * A -> 1 7 | B -> 2 8 | C -> 3 9 | ... 10 | Z -> 26 11 | AA -> 27 12 | AB -> 28 13 | 14 | * Tag: string 15 | 16 | * Author : Dawei Li 17 | */ 18 | 19 | 20 | #include 21 | 22 | using namespace std; 23 | 24 | class Solution { 25 | public: 26 | int titleToNumber(string s) { 27 | 28 | const int CharNum = 26; 29 | 30 | int iVal = 0; 31 | for( int iIndex = 0; iIndex < s.size(); iIndex++ ) 32 | { 33 | iVal = iVal * CharNum + (s[iIndex] - 'A' + 1); 34 | } 35 | 36 | return iVal; 37 | 38 | } 39 | }; 40 | 41 | int main( int argc, char ** argv ) 42 | { 43 | string test = "ABB"; 44 | Solution sln; 45 | 46 | sln.titleToNumber( test ); 47 | 48 | return 0; 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/other/ValidParentheseStringTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class ValidParentheseStringTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{"", ""}, 13 | new Object[]{"(()das10())", "(()das10())"}, 14 | new Object[]{"()()())", "()()()"}, 15 | new Object[]{")(", ""}, 16 | new Object[]{"((((((", ""}, 17 | new Object[]{"))))))", ""}, 18 | }; 19 | } 20 | 21 | @Test(dataProvider = "examples") 22 | public void testGetValidString(String s, String expected) { 23 | ValidParentheseString v = new ValidParentheseString(); 24 | Assert.assertEquals(v.getValidString(s), expected); 25 | } 26 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/database/easy/EmployeesEarningMore.sql: -------------------------------------------------------------------------------- 1 | The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id. 2 | 3 | +----+-------+--------+-----------+ 4 | | Id | Name | Salary | ManagerId | 5 | +----+-------+--------+-----------+ 6 | | 1 | Joe | 70000 | 3 | 7 | | 2 | Henry | 80000 | 4 | 8 | | 3 | Sam | 60000 | NULL | 9 | | 4 | Max | 90000 | NULL | 10 | +----+-------+--------+-----------+ 11 | Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager. 12 | 13 | +----------+ 14 | | Employee | 15 | +----------+ 16 | | Joe | 17 | +----------+ 18 | 19 | ------ 20 | Get employees 21 | compare Manager id with id, and Salary 22 | ------ 23 | 24 | SELECT a.NAME 25 | FROM Employee a, Employee b 26 | WHERE a.ManagerId = b.Id AND a.Salary > b.Salary; -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/datastructures/BinaryIndexedTreeTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.datastructures; 2 | 3 | import org.junit.After; 4 | import org.junit.Assert; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | 8 | public class BinaryIndexedTreeTest { 9 | 10 | private BinaryIndexedTree tree; 11 | 12 | @Before 13 | public void setUp() { 14 | int[] arr = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9}; 15 | tree = new BinaryIndexedTree(arr, arr.length); 16 | } 17 | 18 | @Test 19 | public void testExamples() { 20 | Assert.assertEquals(2, tree.getSum(0)); 21 | Assert.assertEquals(3, tree.getSum(1)); 22 | Assert.assertEquals(4, tree.getSum(2)); 23 | Assert.assertEquals(7, tree.getSum(3)); 24 | tree.update(3, 6); // Update BIT for above change in arr[] 25 | Assert.assertEquals(13, tree.getSum(3)); 26 | } 27 | 28 | @After 29 | public void tearDown() { 30 | tree = null; 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/NetworkDelayTimeTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | public class NetworkDelayTimeTest { 7 | 8 | @Test 9 | public void testNetworkDelayTime() { 10 | int[][] times = {{2, 1, 1}, {2, 3, 1}, {3, 4, 1}}; 11 | int N = 4; 12 | int K = 2; 13 | NetworkDelayTime n = new NetworkDelayTime(); 14 | Assert.assertEquals(n.networkDelayTime(times, N, K), 2); 15 | Assert.assertEquals(n.networkDelayTime2(times, N, K), 2); 16 | Assert.assertEquals(n.networkDelayTime3(times, N, K), 2); 17 | 18 | int[][] times2 = {{1, 2, 1}, {2, 1, 3}}; 19 | N = 2; 20 | K = 2; 21 | Assert.assertEquals(n.networkDelayTime(times2, N, K), 3); 22 | Assert.assertEquals(n.networkDelayTime2(times2, N, K), 3); 23 | Assert.assertEquals(n.networkDelayTime3(times2, N, K), 3); 24 | } 25 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/ValidWordAbbreviationTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class ValidWordAbbreviationTest { 8 | 9 | @DataProvider 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{null, null, true}, 13 | new Object[]{null, "", false}, 14 | new Object[]{"", null, false}, 15 | new Object[]{"internationalization", "i12iz4n", true}, 16 | new Object[]{"apple", "a2e", false}, 17 | new Object[]{"apple", "0a2e", false} // Edge case: leading zeros 18 | }; 19 | } 20 | 21 | @Test(dataProvider = "getExamples") 22 | public void testValidWordAbbreviation(String word, String abbr, boolean expected) { 23 | final boolean actual = new ValidWordAbbreviation().validWordAbbreviation(word, abbr); 24 | Assert.assertEquals(actual, expected); 25 | } 26 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/other/MedianOfNSortedArraysTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class MedianOfNSortedArraysTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[][]{}, 0}, 13 | new Object[]{new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 5}, 14 | new Object[]{new int[][]{{1, 2, 3, 4, 5, 6, 7}, {1, 2, 3, 4}, {7, 8, 9, 10}}, 4}, 15 | new Object[]{new int[][]{{1, 2, 3, 4, 5, 6, 7}, {1, 2, 3, 6, 7}, {7, 8, 9, 10}}, 5.5} 16 | }; 17 | } 18 | 19 | @Test(dataProvider = "examples") 20 | public void testGetMedian(int[][] arrs, double median) { 21 | MedianOfNSortedArrays m = new MedianOfNSortedArrays(); 22 | Assert.assertEquals(m.getMedian(arrs), median); 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/cpp/100_Same_Tree.cpp: -------------------------------------------------------------------------------- 1 | //100 Same Tree 2 | /* 3 | *Given two binary trees, write a function to check if they are equal or not. 4 | * 5 | *Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 6 | * 7 | *Tag: Tree, Depth-first Search 8 | * 9 | *Author: Linsen Wu 10 | * 11 | */ 12 | 13 | #include "stdafx.h" 14 | 15 | using namespace std; 16 | 17 | //Definition for a binary tree node. 18 | struct TreeNode { 19 | int val; 20 | TreeNode *left; 21 | TreeNode *right; 22 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 23 | }; 24 | 25 | class Solution { 26 | public: 27 | bool isSameTree(TreeNode *p, TreeNode *q) { 28 | if(!p && !q) return true; 29 | if(!p || !q) return false; 30 | return (p->val == q->val) && 31 | isSameTree(p->left, q->left) && 32 | isSameTree(p->right, q->right); 33 | } 34 | }; 35 | 36 | int _tmain(int argc, _TCHAR* argv[]) 37 | { 38 | return 0; 39 | } 40 | 41 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/other/GraphPathsTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import com.freetymekiyan.algorithms.utils.Utils.TreeNode; 5 | import org.testng.Assert; 6 | import org.testng.annotations.Test; 7 | 8 | import java.util.List; 9 | 10 | 11 | public class GraphPathsTest { 12 | 13 | @Test 14 | public void testGraphPaths() { 15 | TreeNode node1 = new TreeNode(1); 16 | TreeNode node2 = new TreeNode(2); 17 | TreeNode node3 = new TreeNode(3); 18 | TreeNode node4 = new TreeNode(4); 19 | TreeNode node5 = new TreeNode(5); 20 | node1.left = node2; 21 | node1.right = node3; 22 | node2.left = node4; 23 | node3.left = node2; 24 | node3.right = node5; 25 | node4.left = node3; 26 | GraphPaths g = new GraphPaths(); 27 | Assert.assertTrue(Utils.compareListsIgnoreOrder(g.graphPaths(node1), List.of("1->2->4->3->5", "1->3->5"))); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/FindMinimuminRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | /** 4 | * 153. Find Minimum in Rotated Sorted Array 5 | *

6 | * Suppose a sorted array is rotated at some pivot unknown to you beforehand. 7 | * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 8 | *

9 | * Find the minimum element. 10 | * You may assume no duplicate exists in the array. 11 | *

12 | * Tags: Array, Binary Search 13 | */ 14 | class FindMinimumInRotatedSortedArray { 15 | 16 | public int findMin(int[] nums) { 17 | int lo = 0, hi = nums.length - 1; 18 | while (lo < hi) { // Stop when lo == hi. 19 | int mid = lo + (hi - lo) / 2; 20 | if (nums[mid] > nums[hi]) { // Minimum must be in right half, excluding mid. 21 | lo = mid + 1; 22 | } else { // Minimum must be in left half, including mid. 23 | hi = mid; 24 | } 25 | } 26 | return nums[lo]; 27 | } 28 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/BestTimeStockTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class BestTimeStockTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[]{7, 1, 5, 3, 6, 4}, 5}, 13 | new Object[]{new int[]{7, 6, 4, 3, 1}, 0} 14 | }; 15 | } 16 | 17 | @Test(dataProvider = "examples") 18 | public void testMaxProfit(int[] prices, int expected) { 19 | BestTimeStock b = new BestTimeStock(); 20 | Assert.assertEquals(b.maxProfit(prices), expected); 21 | } 22 | 23 | @Test(dataProvider = "examples") 24 | public void testMaxProfit2(int[] prices, int expected) { 25 | BestTimeStock b = new BestTimeStock(); 26 | Assert.assertEquals(b.maxProfit2(prices), expected); 27 | } 28 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/ExcelSheetColNumber.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * Related to question Excel Sheet Column Title 5 | *

6 | * Given a column title as appear in an Excel sheet, return its corresponding 7 | * column number. 8 | *

9 | * For example: 10 | *

11 | * A -> 1 12 | * B -> 2 13 | * C -> 3 14 | * ... 15 | * Z -> 26 16 | * AA -> 27 17 | * AB -> 28 18 | *

19 | * Tags: Math 20 | */ 21 | class ExcelSheetColNumber { 22 | 23 | public static void main(String[] args) { 24 | System.out.println(titleToNumber("AAA")); 25 | } 26 | 27 | /** 28 | * Go through the title 29 | * Map A ~ Z to 1 ~ 26 30 | * next result = current res * 26 + number of current letter 31 | */ 32 | public static int titleToNumber(String s) { 33 | if (s == null || s.length() == 0) return 0; 34 | int res = 0; 35 | for (int i = 0; i < s.length(); i++) { 36 | res = res * 26 + (s.charAt(i) - '@'); 37 | } 38 | return res; 39 | } 40 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/MinimumWindowSubsequenceTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class MinimumWindowSubsequenceTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{"abcdebdde", "bde", "bcde"} 13 | }; 14 | } 15 | 16 | @Test(dataProvider = "examples") 17 | public void testMinWindow(String S, String T, String expected) { 18 | MinimumWindowSubsequence m = new MinimumWindowSubsequence(); 19 | Assert.assertEquals(m.minWindow(S, T), expected); 20 | } 21 | 22 | @Test(dataProvider = "examples") 23 | public void testMinWindow2(String S, String T, String expected) { 24 | MinimumWindowSubsequence m = new MinimumWindowSubsequence(); 25 | Assert.assertEquals(m.minWindow2(S, T), expected); 26 | } 27 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/other/ThreeSumReuseOnceTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import org.testng.Assert; 5 | import org.testng.annotations.Test; 6 | 7 | import java.util.List; 8 | 9 | public class ThreeSumReuseOnceTest { 10 | 11 | @Test 12 | public void testThreeSumReuseOnce() { 13 | int[] nums = {3, 2, 1, 4, 6, 7}; 14 | int target = 10; 15 | List> expected = List.of(List.of(1, 2, 7), List.of(1, 3, 6), List.of(2, 2, 6), List.of(3, 3, 4), List.of(2, 4, 4)); 16 | ThreeSumReuseOnce t = new ThreeSumReuseOnce(); 17 | Assert.assertTrue(Utils.compareListsIgnoreOrder(t.threeSumReuseOnce(nums, target), expected)); 18 | 19 | target = 9; 20 | expected = List.of(List.of(1, 1, 7), List.of(1, 2, 6), List.of(1, 4, 4), List.of(2, 3, 4)); // Note that [3,3,3] is invalid. 21 | Assert.assertTrue(Utils.compareListsIgnoreOrder(t.threeSumReuseOnce(nums, target), expected)); 22 | } 23 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/MinimumSwapsToMakeSequencesIncreasingTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class MinimumSwapsToMakeSequencesIncreasingTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[]{1, 3, 5, 4}, new int[]{1, 2, 3, 7}, 1}, 13 | new Object[]{new int[]{2, 1, 6, 9, 10, 13, 13, 16, 19, 26, 23, 24, 25, 27, 32, 31, 35, 36, 37, 39}, new int[]{0, 5, 8, 8, 10, 12, 14, 15, 22, 22, 28, 29, 30, 31, 30, 33, 33, 36, 37, 38}, 6} 14 | }; 15 | } 16 | 17 | @Test(dataProvider = "examples") 18 | public void testMinSwap(int[] A, int[] B, int expected) { 19 | MinimumSwapsToMakeSequencesIncreasing m = new MinimumSwapsToMakeSequencesIncreasing(); 20 | Assert.assertEquals(m.minSwap(A, B), expected); 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/SearchInsertPosition.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | /** 4 | * Given a sorted array and a target value, return the index if the target is 5 | * found. If not, return the index where it would be if it were inserted in 6 | * order. 7 | *

8 | * You may assume no duplicates in the array. 9 | *

10 | * Here are few examples. 11 | * [1,3,5,6], 5 → 2 12 | * [1,3,5,6], 2 → 1 13 | * [1,3,5,6], 7 → 4 14 | * [1,3,5,6], 0 → 0 15 | *

16 | * Tags: Array, Binary Search 17 | */ 18 | class SearchInsertPosition { 19 | 20 | /** 21 | * Binary search 22 | * r = m - 1, l = m + 1 23 | */ 24 | public int searchInsert(int[] A, int target) { 25 | if (A == null || A.length == 0) return 0; 26 | int l = 0; 27 | int r = A.length - 1; 28 | int m; 29 | while (l <= r) { 30 | m = l + (r - l) / 2; 31 | if (A[m] == target) return m; 32 | else if (A[m] > target) r = m - 1; 33 | else l = m + 1; 34 | } 35 | return l; 36 | } 37 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/other/UpdateTreeValueTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | public class UpdateTreeValueTest { 7 | 8 | @Test 9 | public void testUpdateValue() { 10 | UpdateTreeValue.TreeNode root = new UpdateTreeValue.TreeNode(); 11 | UpdateTreeValue.TreeNode left = new UpdateTreeValue.TreeNode(); 12 | UpdateTreeValue.TreeNode mid = new UpdateTreeValue.TreeNode(); 13 | UpdateTreeValue.TreeNode right = new UpdateTreeValue.TreeNode(); 14 | root.val = 1; 15 | left.val = 0; 16 | mid.val = 0; 17 | right.val = 2; 18 | root.children.add(left); 19 | root.children.add(mid); 20 | root.children.add(right); 21 | left.parent = root; 22 | mid.parent = root; 23 | right.parent = root; 24 | UpdateTreeValue u = new UpdateTreeValue(root); 25 | u.updateValue(right, 0); 26 | Assert.assertEquals(root.val, 0); 27 | } 28 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/SingleNumber2.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | /** 4 | * 137. Single Number II 5 | *

6 | * Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. 7 | * Find that single one. 8 | *

9 | * Note: 10 | *

11 | * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 12 | *

13 | * Example 1: 14 | *

15 | * Input: [2,2,3,2] 16 | * Output: 3 17 | * Example 2: 18 | *

19 | * Input: [0,1,0,1,0,1,99] 20 | * Output: 99 21 | *

22 | * Related Topics: Bit Manipulation 23 | *

24 | * Similar Questions: Single Number (E), Single Number III (M) 25 | */ 26 | public class SingleNumber2 { 27 | 28 | public int singleNumber(int[] nums) { 29 | int ones = 0, twos = 0; 30 | for (int i = 0; i < nums.length; i++) { 31 | ones = (ones ^ nums[i]) & ~twos; 32 | twos = (twos ^ nums[i]) & ~ones; 33 | } 34 | return ones; 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/SameTree.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * Given two binary trees, write a function to check if they are equal or not. 5 | *

6 | * Two binary trees are considered equal if they are structurally identical 7 | * and the nodes have the same value. 8 | *

9 | * Tags: Tree, DFS 10 | */ 11 | class SameTree { 12 | 13 | /** 14 | * Recursive, pre-order check 15 | * If both node's values are the same, left subtrees are same and so right 16 | * Return true, otherwise return false 17 | */ 18 | public static boolean isSameTree(TreeNode p, TreeNode q) { 19 | if (p == null || q == null) return p == q; // if one of them is null, it will return false. both null, true. 20 | return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); // equal val, equal subtrees 21 | } 22 | 23 | public class TreeNode { 24 | int val; 25 | TreeNode left; 26 | TreeNode right; 27 | 28 | TreeNode(int x) { 29 | val = x; 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/RunLengthEncoding.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Run Length Encoding 5 | * wwwwaaadexxxxxx 6 | * => w4a3d1e1x6 7 | *

8 | * Tags: String 9 | */ 10 | class RunLengthEncoding { 11 | 12 | public static void main(String[] args) { 13 | String src = "wwwwaaadexxxxxx"; 14 | } 15 | 16 | /** 17 | * Traverse the source string 18 | * Append current char to result first 19 | * Get count with a loop, note the edge case 20 | * Append count of current char to result 21 | */ 22 | public String encode(String src) { 23 | StringBuilder dest = new StringBuilder(); 24 | for (int i = 0; i < src.length(); i++) { 25 | dest.append(src.charAt(i)); 26 | int cnt = 1; 27 | while (i + 1 < src.length() && src.charAt(i) == src.charAt(i + 1)) { 28 | i++; 29 | cnt++; 30 | } 31 | dest.append(cnt); 32 | } 33 | return dest.toString(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/cpp/071_Simplify_Path.cpp: -------------------------------------------------------------------------------- 1 | //71. Simplify Path 2 | /* 3 | Given an absolute path for a file (Unix-style), simplify it. 4 | 5 | For example, 6 | path = "/home/", => "/home" 7 | path = "/a/./b/../../c/", => "/c" 8 | 9 | Tag: stack, string 10 | 11 | Author: Xinyu Liu 12 | */ 13 | 14 | #include 15 | #include 16 | #include 17 | #include 18 | using namespace std; 19 | 20 | class Solution{ 21 | public: 22 | string simplifyPath(string path) { 23 | string ss, tmp; 24 | vector stk; 25 | stringstream str(path); 26 | while(getline(str,tmp,'/')){ 27 | if (tmp == "" || tmp == ".") continue; 28 | if (tmp == ".." && !stk.empty()) stk.pop_back(); 29 | if (tmp != "..") stk.push_back(tmp); 30 | } 31 | for(int i = 0; i != stk.size(); i++) 32 | ss += "/" + stk[i]; 33 | return stk.empty() ? "/" : ss; 34 | } 35 | }; 36 | 37 | void main(){ 38 | string s = "/a/./b/../../c/"; 39 | Solution sol; 40 | string ss = sol.simplifyPath(s); 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/LengthOfLastWord.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * 58. Length of Last Word 5 | *

6 | * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last 7 | * word in the string. 8 | *

9 | * If the last word does not exist, return 0. 10 | *

11 | * Note: A word is defined as a character sequence consists of non-space characters only. 12 | *

13 | * Example: 14 | *

15 | * Input: "Hello World" 16 | * Output: 5 17 | *

18 | * Related Topics: String 19 | */ 20 | public class LengthOfLastWord { 21 | 22 | public int lengthOfLastWord(String s) { 23 | s = s.trim(); 24 | char space = ' '; 25 | if (s.indexOf(space) == -1) return s.length(); // No space 26 | int len = s.length(); 27 | // Find the starting index of the last word 28 | for (int i = len - 1; i >= 0; i--) { 29 | if (s.charAt(i) == ' ' && i != len - 1) { 30 | return len - 1 - i; 31 | } 32 | } 33 | return 0; 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/database/easy/CombineTwoTables.sql: -------------------------------------------------------------------------------- 1 | Table: Person 2 | 3 | +-------------+---------+ 4 | | Column Name | Type | 5 | +-------------+---------+ 6 | | PersonId | int | 7 | | FirstName | varchar | 8 | | LastName | varchar | 9 | +-------------+---------+ 10 | PersonId is the primary key column for this table. 11 | Table: Address 12 | 13 | +-------------+---------+ 14 | | Column Name | Type | 15 | +-------------+---------+ 16 | | AddressId | int | 17 | | PersonId | int | 18 | | City | varchar | 19 | | State | varchar | 20 | +-------------+---------+ 21 | AddressId is the primary key column for this table. 22 | 23 | Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people: 24 | 25 | FirstName, LastName, City, State 26 | 27 | ------ 28 | Left join Person with Address with Aliase 29 | ------ 30 | 31 | SELECT FirstName, LastName, City, State 32 | From Person AS P 33 | LEFT JOIN Address AS A 34 | ON P.PersonId = A.PersonId; -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/datastructures/LinkedListBag.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | /** 4 | * void add(Item item) 5 | */ 6 | public class LinkedListBag implements Iterable { 7 | 8 | private Node first; 9 | 10 | public void add(Item item) { 11 | Node oldFirst = first; 12 | first = new Node(); 13 | first.item = item; 14 | first.next = oldFirst; 15 | } 16 | 17 | @Override 18 | public Iterator iterator() { 19 | return new ListIterator(); 20 | } 21 | 22 | private class ListIterator implements Iterator { 23 | 24 | private Node current = first; 25 | 26 | @Override 27 | public boolean hasNext() { 28 | return current != null; 29 | } 30 | 31 | @Override 32 | public Item next() { 33 | Item item = current.item; 34 | current = current.next; 35 | return item; 36 | } 37 | } 38 | 39 | 40 | private class Node { 41 | 42 | Item item; 43 | Node next; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/DecodeWays2Test.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | import java.util.Map; 7 | 8 | public class DecodeWays2Test { 9 | 10 | private static final Map EXAMPLES = Map.of( 11 | "0", 0, 12 | "1", 1, 13 | "1*", 18, 14 | "**", 96, 15 | "***", 999, 16 | "*1*1*0", 404, 17 | "**********1111111111", 133236775, // Test overflow. 18 | "********************", 104671669 // Test overflow. 19 | ); 20 | 21 | @Test 22 | public void testNumDecodings() { 23 | DecodeWays2 d = new DecodeWays2(); 24 | for (Map.Entry e : EXAMPLES.entrySet()) { 25 | System.out.println("Input is: " + e.getKey()); 26 | Assert.assertEquals(d.numDecodings(e.getKey()), e.getValue().intValue()); 27 | Assert.assertEquals(d.numDecodings2(e.getKey()), e.getValue().intValue()); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/MaxDepth.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * Given a binary tree, find its maximum depth. 5 | * 6 | * The maximum depth is the number of nodes along the longest path from the 7 | * root node down to the farthest leaf node. 8 | * 9 | * Tags: Tree, DFS 10 | */ 11 | class MaxDepth { 12 | public static void main(String[] args) { 13 | 14 | } 15 | 16 | /** 17 | * Recursive, O(n) 18 | * If tree is empty, return 0 19 | * Else 20 | * Get the max depth of left subtree recursively 21 | * Get the max depth of right subtree recursively 22 | * Get the max of max depths of left and right subtrees and add 1 to it 23 | */ 24 | private int maxDepth(TreeNode root) { 25 | if (root == null) return 0; 26 | int left = maxDepth(root.left); 27 | int right = maxDepth(root.right); 28 | return Math.max(left, right) + 1; 29 | } 30 | 31 | class TreeNode { 32 | int val; 33 | TreeNode left; 34 | TreeNode right; 35 | } 36 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/IncreasingTripletSubsequenceTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class IncreasingTripletSubsequenceTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[]{1, 2, 3, 4, 5}, true}, 13 | new Object[]{new int[]{5, 4, 3, 2, 1}, false} 14 | }; 15 | } 16 | 17 | @Test 18 | public void testIncreasingTriplet(int[] input, boolean output) { 19 | IncreasingTripletSubsequence i = new IncreasingTripletSubsequence(); 20 | Assert.assertEquals(i.increasingTriplet(input), output); 21 | } 22 | 23 | @Test 24 | public void testIncreasingTriplet2(int[] input, boolean output) { 25 | IncreasingTripletSubsequence i = new IncreasingTripletSubsequence(); 26 | Assert.assertEquals(i.increasingTriplet2(input), output); 27 | } 28 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/NumberOfLongestIncreasingSubsequenceTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class NumberOfLongestIncreasingSubsequenceTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[]{1, 3, 5, 4, 7}, 2}, 13 | new Object[]{new int[]{2, 2, 2, 2, 2}, 5}, 14 | new Object[]{new int[]{3, 2, 1}, 3}, 15 | new Object[]{new int[]{1, 2, 4, 3, 5, 4, 7, 2}, 3}, 16 | new Object[]{new int[]{1, 2, 3, 1, 2, 3, 1, 2, 3}, 10} 17 | }; 18 | } 19 | 20 | @Test(dataProvider = "examples") 21 | public void testFindNumberOfLISExamples(int[] nums, int expected) { 22 | NumberOfLongestIncreasingSubsequence n = new NumberOfLongestIncreasingSubsequence(); 23 | Assert.assertEquals(n.findNumberOfLIS(nums), expected); 24 | } 25 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/HeapSort.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Heap construction 5 | * delMax() till empty 6 | */ 7 | public class HeapSort { 8 | 9 | public void sort(Comparable[] pq) { 10 | int N = pq.length; 11 | for (int i = N / 2; i >= 1; i--) { 12 | sink(pq, i, N); 13 | } 14 | 15 | while (N > 1) { 16 | exch(pq, 1, N--); 17 | sink(pq, 1, N); 18 | } 19 | } 20 | 21 | private void exch(Comparable[] pq, int i, int j) { 22 | Comparable temp = pq[i]; 23 | pq[i] = pq[j]; 24 | pq[j] = temp; 25 | } 26 | 27 | private void sink(Comparable[] pq, int i, int j) { 28 | while (2 * i <= j) { 29 | int k = 2 * i; 30 | if (k < j && less(pq, k, k + 1)) k++; 31 | if (!less(pq, i, k)) break; 32 | exch(pq, i, k); 33 | i = k; 34 | } 35 | } 36 | 37 | private boolean less(Comparable[] pq, int i, int k) { 38 | return pq[i].compareTo(pq[k]) < 0; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/MedianOfTwoSortedArraysTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class MedianOfTwoSortedArraysTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[]{}, new int[]{}, 0.0}, 13 | new Object[]{new int[]{2}, new int[]{}, 2.0}, 14 | new Object[]{new int[]{}, new int[]{2}, 2.0}, 15 | new Object[]{new int[]{1, 2, 3, 4, 5}, new int[]{2, 4, 5, 6, 7}, 4.0}, 16 | new Object[]{new int[]{1, 2, 3, 4, 5}, new int[]{2, 4, 5, 6, 7, 8}, 4.0}, 17 | }; 18 | } 19 | 20 | @Test(dataProvider = "examples") 21 | public void testExamples(int[] nums1, int[] nums2, double expected) { 22 | MedianOfTwoSortedArrays m = new MedianOfTwoSortedArrays(); 23 | Assert.assertEquals(m.findMedianSortedArrays(nums1, nums2), expected); 24 | } 25 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/TextJustificationTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | import java.util.List; 8 | 9 | public class TextJustificationTest { 10 | 11 | @DataProvider(name = "examples") 12 | public Object[][] getExamples() { 13 | List expected = List.of( 14 | "This is an", 15 | "example of text", 16 | "justification. " 17 | ); 18 | return new Object[][]{ 19 | new Object[]{new String[]{"This", "is", "an", "example", "of", "text", "justification."}, 16, expected}, 20 | new Object[]{new String[]{""}, 2, List.of(" ")} 21 | }; 22 | } 23 | 24 | @Test(dataProvider = "examples") 25 | public void testFullJustify(String[] words, int maxWidth, List expected) { 26 | TextJustification t = new TextJustification(); 27 | Assert.assertEquals(t.fullJustify(words, maxWidth), expected); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/MinimumDepthOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * 111. Minimum Depth of Binary Tree 5 | *

6 | * Given a binary tree, find its minimum depth. 7 | *

8 | * The minimum depth is the number of nodes along the shortest path from the 9 | * root node down to the nearest leaf node. 10 | *

11 | * Tags: Tree, DFS 12 | */ 13 | class MinimumDepthOfBinaryTree { 14 | 15 | /** 16 | * Recursive 17 | * Get minDepth of left and right subtree 18 | * If one side is 0, return the other side plus 1 19 | * Return the smaller one + 1 20 | */ 21 | public int minDepth(TreeNode root) { 22 | if (root == null) return 0; 23 | int left = minDepth(root.left); 24 | int right = minDepth(root.right); 25 | if (left == 0) return right + 1; 26 | if (right == 0) return left + 1; 27 | return Math.min(left, right) + 1; // plus root 28 | } 29 | 30 | public class TreeNode { 31 | int val; 32 | TreeNode left; 33 | TreeNode right; 34 | 35 | TreeNode(int x) { 36 | val = x; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /src/main/cpp/147_Insertion_Sort_List.cpp: -------------------------------------------------------------------------------- 1 | //147. Insertion Sort List 2 | /* 3 | Sort a linked list using insertion sort. 4 | 5 | Author: Xinyu Liu 6 | */ 7 | 8 | 9 | #include 10 | using namespace std; 11 | 12 | //Definition for singly-linked list. 13 | struct ListNode { 14 | int val; 15 | ListNode *next; 16 | ListNode(int x) : val(x), next(NULL) {} 17 | }; 18 | 19 | 20 | class Solution{ 21 | public: 22 | ListNode* insertionSortList(ListNode* head){ 23 | ListNode L(INT_MIN); 24 | L.next = head; 25 | 26 | if(!head||!head->next) 27 | { 28 | return head; 29 | } 30 | head = head->next; 31 | L.next->next = NULL; 32 | 33 | ListNode* i; 34 | while (head){ 35 | i = &L; 36 | while (i ->next && i ->next ->val < head ->val){ 37 | i = i->next; 38 | } 39 | ListNode* insert = head; 40 | head = head ->next; 41 | insert->next = i ->next; 42 | i ->next = insert; 43 | 44 | } 45 | return L.next; 46 | 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/MinimumWindowSubstringTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class MinimumWindowSubstringTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{"ADOBECODEBANC", "ABC", "BANC"}, 13 | new Object[]{"a", "a", "a"}, 14 | new Object[]{"ab", "b", "b"} 15 | }; 16 | } 17 | 18 | @Test(dataProvider = "examples") 19 | public void testMinWindow(String s, String t, String expected) { 20 | MinimumWindowSubstring m = new MinimumWindowSubstring(); 21 | Assert.assertEquals(m.minWindow(s, t), expected); 22 | } 23 | 24 | @Test(dataProvider = "examples") 25 | public void testMinWindow2(String s, String t, String expected) { 26 | MinimumWindowSubstring m = new MinimumWindowSubstring(); 27 | Assert.assertEquals(m.minWindow2(s, t), expected); 28 | } 29 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/HIndex2Test.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class HIndex2Test { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[0], 0}, 13 | new Object[]{new int[]{1}, 1}, 14 | new Object[]{new int[]{1, 2, 3, 4, 5}, 3}, 15 | new Object[]{new int[]{5, 6, 7, 8, 9}, 5}, 16 | new Object[]{new int[]{0, 0, 0, 0, 0}, 0} 17 | }; 18 | } 19 | 20 | @Test(dataProvider = "examples") 21 | public void testHIndex(int[] input, int output) { 22 | HIndex2 h = new HIndex2(); 23 | Assert.assertEquals(h.hIndex(input), output); 24 | } 25 | 26 | @Test(dataProvider = "examples") 27 | public void testHIndex2(int[] input, int output) { 28 | HIndex2 h = new HIndex2(); 29 | Assert.assertEquals(h.hIndex2(input), output); 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/cpp/055_Jump_Game.cpp: -------------------------------------------------------------------------------- 1 | //55. Jump Game 2 | /* 3 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 4 | 5 | Each element in the array represents your maximum jump length at that position. 6 | 7 | Determine if you are able to reach the last index. 8 | 9 | For example: 10 | A = [2,3,1,1,4], return true. 11 | 12 | A = [3,2,1,0,4], return false. 13 | 14 | Author: Xinyu Liu 15 | 16 | Tag: Array, Greedy 17 | */ 18 | 19 | #include 20 | #include 21 | using namespace std; 22 | 23 | class Solution { 24 | public: 25 | bool canJump(vector& nums) { 26 | int size_nums = nums.size(); 27 | int i = 0; 28 | for (int reach = 0; i < size_nums && i <= reach; i++){ 29 | reach = max(nums.at(i) + i, reach); 30 | if (reach >= size_nums - 1) 31 | return true; 32 | } 33 | return false; 34 | } 35 | }; 36 | 37 | void main(){ 38 | 39 | int test[5] = {1,2,3,4,5}; 40 | vector vec(test, test + sizeof(test)/sizeof(int)); 41 | Solution sol; 42 | bool y = sol.canJump(vec); 43 | 44 | } 45 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Kiyan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/BinaryTreeInOrderTraversalTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import com.freetymekiyan.algorithms.utils.Utils.TreeNode; 5 | import org.testng.Assert; 6 | import org.testng.annotations.DataProvider; 7 | import org.testng.annotations.Test; 8 | 9 | import java.util.List; 10 | 11 | public class BinaryTreeInOrderTraversalTest { 12 | 13 | @DataProvider(name = "examples") 14 | public Object[][] getExamples() { 15 | return new Object[][]{ 16 | new Object[]{Utils.buildBinaryTree(new Integer[]{1, null, 2, 3}), List.of(1, 3, 2)}, 17 | new Object[]{Utils.buildBinaryTree(new Integer[]{1, 2, 6, 3, 4, null, 7, null, null, 5, null, null, null, null, null}), List.of(3, 2, 5, 4, 1, 6, 7)} 18 | }; 19 | } 20 | 21 | @Test(dataProvider = "examples") 22 | public void testExamples(TreeNode root, List expected) { 23 | BinaryTreeInOrderTraversal b = new BinaryTreeInOrderTraversal(); 24 | Assert.assertEquals(b.inorderTraversal(root), expected); 25 | } 26 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/other/TotalNumberOfSecondsTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | import java.util.List; 8 | 9 | public class TotalNumberOfSecondsTest { 10 | 11 | @DataProvider(name = "examples") 12 | public Object[][] getExamples() { 13 | return new Object[][]{ 14 | new Object[]{List.of(new int[]{0, 1}, new int[]{1, 2}), 2}, 15 | new Object[]{List.of(new int[]{0, 5}, new int[]{4, 6}), 6}, 16 | new Object[]{List.of(new int[]{4, 6}, new int[]{1, 3}), 4}, 17 | new Object[]{List.of(new int[]{4, 6}, new int[]{1, 8}), 7} 18 | }; 19 | } 20 | 21 | @Test(dataProvider = "examples") 22 | public void testTotalNumberOfSeconds(List events, int expected) { 23 | TotalNumberOfSeconds t = new TotalNumberOfSeconds(); 24 | int s = 0; 25 | for (int[] e : events) { 26 | s = t.totalNumberOfSeconds(e); 27 | } 28 | Assert.assertEquals(s, expected); 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/TreeDiameter.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Created by kiyan on 5/5/16. 5 | * Now become 543. Diameter of Binary Tree 6 | */ 7 | public class TreeDiameter { 8 | public int getTreeDiameter(TreeNode root) { 9 | int d = 0; 10 | if (root == null) return d; 11 | d = height(root.left) + height(root.right) + 1; 12 | int ld = getTreeDiameter(root.left); 13 | int rd = getTreeDiameter(root.right); 14 | /* 15 | Return max of following three 16 | 1) Diameter of left subtree 17 | 2) Diameter of right subtree 18 | 3) Height of left subtree + height of right subtree + 1 */ 19 | return Math.max(d, Math.max(ld, rd)); 20 | } 21 | 22 | private int height(TreeNode root) { 23 | if (root == null) return 0; 24 | return Math.max(height(root.left), height(root.right)) + 1; 25 | } 26 | 27 | class TreeNode { 28 | int val; 29 | TreeNode left; 30 | TreeNode right; 31 | 32 | TreeNode(int x) { 33 | val = x; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/LexicographicalNumbers.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 386. Lexicographical Numbers 8 | *

9 | * Given an integer n, return 1 - n in lexicographical order. 10 | *

11 | * For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. 12 | *

13 | * Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000. 14 | *

15 | * Companies: Google, Facebook, Adobe, Bloomberg 16 | */ 17 | public class LexicographicalNumbers { 18 | 19 | public List lexicalOrder(int n) { 20 | List res = new ArrayList<>(n); 21 | for (int i = 1; i < 10; i++) { 22 | dfs(i, n, res); 23 | } 24 | return res; 25 | } 26 | 27 | private void dfs(int curr, int n, List res) { 28 | if (curr > n) { 29 | return; 30 | } 31 | res.add(curr); 32 | for (int i = 0; i < 10; i++) { 33 | int next = 10 * curr + i; 34 | if (next > n) { 35 | return; 36 | } 37 | dfs(next, n, res); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/ValidParenthesesTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class ValidParenthesesTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{"()", true}, 13 | new Object[]{"()[]{}", true}, 14 | new Object[]{"([)]", false}, 15 | new Object[]{"[({(())}[()])]", true}, 16 | new Object[]{"a[a(a{a(a(.)a)a}x[a(a)v]w)q]z", false}, 17 | }; 18 | } 19 | 20 | @Test(dataProvider = "examples") 21 | public void testIsValid(String s, boolean expected) { 22 | ValidParentheses v = new ValidParentheses(); 23 | Assert.assertEquals(v.isValid(s), expected); 24 | } 25 | 26 | @Test(dataProvider = "examples") 27 | public void testIsValid2(String s, boolean expected) { 28 | ValidParentheses v = new ValidParentheses(); 29 | Assert.assertEquals(v.isValid2(s), expected); 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | /** 4 | * Given a linked list, determine if it has a cycle in it. 5 | *

6 | * Follow up: 7 | * Can you solve it without using extra space? 8 | *

9 | * Tags: Linkedlist, Two pointers 10 | */ 11 | class LinkedListCycle { 12 | 13 | public static void main(String[] args) { 14 | 15 | } 16 | 17 | /** 18 | * Runnner's technique 19 | * Check the next and next next of faster node is slower node or not. 20 | */ 21 | public boolean hasCycle(ListNode head) { 22 | if (head == null || head.next == null) return false; 23 | ListNode fast = head; 24 | ListNode slow = head; 25 | while (fast.next != null && fast.next.next != null) { 26 | fast = fast.next.next; 27 | slow = slow.next; 28 | if (fast == slow) return true; 29 | } 30 | return false; 31 | } 32 | 33 | class ListNode { 34 | int val; 35 | ListNode next; 36 | 37 | ListNode(int x) { 38 | val = x; 39 | next = null; 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/WiggleSort.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Given a sorted array, and re-arrange it to wiggle style in one pass. 5 | * i.e. 6 | * [1] A0 >= A1 <= A2 >= A3 .... .... An. 7 | * [2] A0 <= A1 >= A2 <= A3 .... .... An. 8 | *

9 | * Tags: Sort, Array 10 | */ 11 | class WiggleSort { 12 | public static void main(String[] args) { 13 | 14 | } 15 | 16 | /** 17 | * Swap neighbors 18 | * A0 >= A1 <= A2 >= A3 .... .... An. 19 | */ 20 | public void wiggleSort(int[] A) { 21 | if (A == null || A.length == 0) return; 22 | for (int i = 0; i < A.length - 1; i += 2) { 23 | swap(A, i, i + 1); 24 | } 25 | } 26 | 27 | /** 28 | * A0 <= A1 >= A2 <= A3 .... .... An. 29 | */ 30 | public void wiggleSort2(int[] A) { 31 | if (A == null || A.length == 0) return; 32 | for (int i = 1; i < A.length - 1; i += 2) { 33 | swap(A, i, i + 1); 34 | } 35 | } 36 | 37 | private void swap(int[] a, int i1, int i2) { 38 | int temp = a[i1]; 39 | a[i1] = a[i2]; 40 | a[i2] = temp; 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/Celebrity.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Given: 5 | * function: isFriend(a, b) 6 | * Returns true iff b is treated as a friend by a group of persons, say, 7 | * represented as an array 8 | */ 9 | class Celebrity { 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | /** 15 | * Traverse the list 16 | * Update leader index if leader is friend of current id 17 | * Then check if leader is real with one more traversal 18 | */ 19 | int hasLeader(Person[] persons) { 20 | int n = persons.length; 21 | int leader = 0; 22 | int cur = 1; 23 | while (cur < n) { 24 | if (isFriend(persons[leader], persons[cur])) leader = cur; 25 | cur++; 26 | } 27 | 28 | for (int i = 0; i < n; i++) { 29 | if (i != leader && isFriend(persons[leader], persons[i])) { 30 | return -1; 31 | } 32 | } 33 | return leader; 34 | } 35 | 36 | private boolean isFriend(Person p1, Person p2) { 37 | return false; 38 | } 39 | 40 | class Person { 41 | } 42 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/other/AddTwoDoublesTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class AddTwoDoublesTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{"1.13", "0.9", "2.03"}, 13 | new Object[]{"1.0", "1.0", "2.0"}, 14 | new Object[]{"0.0", "5.0", "5.0"}, 15 | new Object[]{"1.0", "0.0", "1.0"}, 16 | new Object[]{"0.0", "0.0", "0.0"}, 17 | new Object[]{"1.01", "1.0", "2.01"}, 18 | new Object[]{"1.011111", "1.0", "2.011111"}, 19 | new Object[]{"1.0", "1.011111", "2.011111"}, 20 | new Object[]{"1.099999", "1.011111", "2.11111"} 21 | }; 22 | } 23 | 24 | @Test(dataProvider = "examples") 25 | public void testAddDoubles(String s1, String s2, String expected) { 26 | AddTwoDoubles a = new AddTwoDoubles(); 27 | Assert.assertEquals(a.addDoubles(s1, s2), expected); 28 | } 29 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/PalindromicSubstringsTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | import java.util.Collections; 7 | import java.util.List; 8 | 9 | public class PalindromicSubstringsTest { 10 | 11 | private static final List INPUTS = Collections.unmodifiableList(List.of("abc", "aaa")); 12 | private static final List OUTPUTS = Collections.unmodifiableList(List.of(3, 6)); 13 | 14 | @Test 15 | public void testCountSubstringsExamples() { 16 | PalindromicSubstrings p = new PalindromicSubstrings(); 17 | for (int i = 0; i < INPUTS.size(); i++) { 18 | Assert.assertEquals(p.countSubstrings(INPUTS.get(i)), OUTPUTS.get(i).intValue()); 19 | Assert.assertEquals(p.countSubstrings2(INPUTS.get(i)), OUTPUTS.get(i).intValue()); 20 | } 21 | } 22 | 23 | @Test(description = "Should handle it and return 0 if input is null.") 24 | public void testNullInput() { 25 | PalindromicSubstrings p = new PalindromicSubstrings(); 26 | p.countSubstrings(null); 27 | p.countSubstrings2(null); 28 | } 29 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/other/BinaryTreeLongestPathTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import com.freetymekiyan.algorithms.utils.Utils.TreeNode; 5 | import org.testng.Assert; 6 | import org.testng.annotations.DataProvider; 7 | import org.testng.annotations.Test; 8 | 9 | public class BinaryTreeLongestPathTest { 10 | 11 | @DataProvider(name = "examples") 12 | public Object[][] getExamples() { 13 | return new Object[][]{ 14 | new Object[]{null, null}, 15 | new Object[]{Utils.buildBinaryTree(new Integer[]{1}), "1"}, 16 | new Object[]{Utils.buildBinaryTree(new Integer[]{1, 2}), "1->2"}, 17 | new Object[]{Utils.buildBinaryTree(new Integer[]{1, 2, 3}), "1->2"}, 18 | new Object[]{Utils.buildBinaryTree(new Integer[]{1, 2, 3, null, null, 4}), "1->3->4"} 19 | }; 20 | } 21 | 22 | @Test(dataProvider = "examples") 23 | public void testLongestPath(TreeNode root, String expected) { 24 | BinaryTreeLongestPath b = new BinaryTreeLongestPath(); 25 | Assert.assertEquals(b.longestPath(root), expected); 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/cpp/020_Valid_Parentheses.cpp: -------------------------------------------------------------------------------- 1 | //20. Valid Parentheses 2 | /* 3 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 4 | The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 5 | 6 | Tag: Stack, String 7 | 8 | Author: Xinyu Liu 9 | */ 10 | 11 | #include 12 | #include 13 | #include 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | bool isValid(string s) { 19 | if (s.empty()) return true; 20 | stack cha; 21 | for (int i = 0; i < s.size(); i++){ 22 | if (s[i] == '(' || s[i] == '[' || s[i] == '{') 23 | cha.push(s[i]); 24 | else{ 25 | if(cha.empty()) return false; 26 | if((s[i] == ')' && cha.top() == '(') || (s[i] == ']' && cha.top() == '[') || (s[i] == '}' && cha.top() == '{')) 27 | cha.pop(); 28 | else return false; 29 | } 30 | } 31 | return(cha.empty()); 32 | } 33 | }; 34 | 35 | void main(){ 36 | string s = "([])"; 37 | Solution sol; 38 | bool b = sol.isValid(s); 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/DailyTemperaturesTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import org.testng.Assert; 5 | import org.testng.annotations.Test; 6 | 7 | 8 | public class DailyTemperaturesTest { 9 | 10 | @Test 11 | public void testDailyTemperatures() throws Exception { 12 | int[] temperatures = {73, 74, 75, 71, 69, 72, 76, 73}; // Duplicate temperatures separated. 13 | int[] output = {1, 1, 4, 2, 1, 1, 0, 0}; 14 | DailyTemperatures d = new DailyTemperatures(); 15 | Assert.assertTrue(Utils.compareArrays(d.dailyTemperatures(temperatures), output)); 16 | 17 | temperatures = new int[]{89, 62, 70, 58, 47, 47, 46, 76, 100, 70}; // Duplicate temperatures followed. 18 | output = new int[]{8, 1, 5, 4, 3, 2, 1, 1, 0, 0}; 19 | Assert.assertTrue(Utils.compareArrays(d.dailyTemperatures(temperatures), output)); 20 | 21 | temperatures = new int[]{34, 80, 80, 34, 34, 80, 80, 80, 80, 34}; 22 | output = new int[]{1, 0, 0, 2, 1, 0, 0, 0, 0, 0}; 23 | Assert.assertTrue(Utils.compareArrays(d.dailyTemperatures(temperatures), output)); 24 | } 25 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/WordLadderTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.junit.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | public class WordLadderTest { 11 | 12 | @DataProvider(name = "examples") 13 | public Object[][] getExamples() { 14 | List s = new ArrayList<>(); 15 | s.add("hot"); 16 | s.add("dog"); 17 | s.add("dot"); 18 | return new Object[][]{ 19 | new Object[]{"hot", "dog", s, 3}, 20 | }; 21 | } 22 | 23 | @Test(dataProvider = "examples") 24 | public void testLadderLength(String begin, String end, List words, int output) { 25 | WordLadder w = new WordLadder(); 26 | Assert.assertEquals(w.ladderLength(begin, end, words), output); 27 | } 28 | 29 | @Test(dataProvider = "examples") 30 | public void testLadderLengthB(String begin, String end, List words, int output) { 31 | WordLadder w = new WordLadder(); 32 | Assert.assertEquals(w.ladderLengthB(begin, end, words), output); 33 | } 34 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/AddBinaryTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class AddBinaryTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{"1010", "1011", "10101"}, 13 | new Object[]{"11110011001011110111110001010000111110011110101100011111010010001000001101111001000111", "111001011011111010001001111001100000101010000101100010101100010010010011011000", "11110100000101010011101011011010110111111111010110100100110100110100100000001100011111"}, 14 | }; 15 | } 16 | 17 | @Test(dataProvider = "examples") 18 | public void testAddBinary(String a, String b, String sum) { 19 | AddBinary ab = new AddBinary(); 20 | Assert.assertEquals(ab.addBinary(a, b), sum); 21 | } 22 | 23 | @Test(dataProvider = "examples") 24 | public void testAddBinary2(String a, String b, String sum) { 25 | AddBinary ab = new AddBinary(); 26 | Assert.assertEquals(ab.addBinary2(a, b), sum); 27 | } 28 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/CombinationSum4Test.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class CombinationSum4Test { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] generateExamples() { 11 | int[] nums = {1, 2, 3}; 12 | return new Object[][]{ 13 | new Object[]{nums, 4, 7}, 14 | new Object[]{nums, 6, 24} 15 | }; 16 | } 17 | 18 | @Test(description = "Test examples on bottom-up implementation.", dataProvider = "examples") 19 | public void testCombinationSum4(int[] nums, int target, int output) { 20 | CombinationSum4 c = new CombinationSum4(); 21 | Assert.assertEquals(c.combinationSum4(nums, target), output); 22 | } 23 | 24 | @Test(description = "Test examples on top-down implementation.", dataProvider = "examples") 25 | public void testCombinationSum4TopDown(int[] nums, int target, int output) { 26 | CombinationSum4 c = new CombinationSum4(); 27 | Assert.assertEquals(c.combinationSum4TopDown(nums, target), output); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/CountPrimes.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * 204. Count Primes 5 | *

6 | * Count the number of prime numbers less than a non-negative number, n. 7 | *

8 | * Example: 9 | *

10 | * Input: 10 11 | * Output: 4 12 | * Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 13 | *

14 | * Companies: Microsoft, Amazon, Adobe, Google, Apple, Yahoo, Goldman Sachs, Nvidia, Tesla, Tencent, Bloomberg, Capital 15 | * One 16 | *

17 | * Related Topics: Hash Table, Math 18 | *

19 | * Similar Questions: (E) Ugly Number, (M) Ugly Number II, (M) Perfect Squares 20 | */ 21 | public class CountPrimes { 22 | 23 | public int countPrimes(int n) { 24 | if (n <= 2) return 0; 25 | 26 | int res = n >> 1; 27 | int m = (int) Math.sqrt(n - 1); 28 | boolean[] notPrime = new boolean[n]; 29 | 30 | for (int i = 3; i <= m; i += 2) { 31 | if (!notPrime[i]) { 32 | for (int j = i * i, step = i << 1; j < n; j += step) { 33 | if (!notPrime[j]) { 34 | notPrime[j] = true; 35 | --res; 36 | } 37 | } 38 | } 39 | } 40 | 41 | return res; 42 | } 43 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/RangeSumQueryImmutable.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 5 | * 6 | * Example: 7 | * 8 | * Given nums = [-2, 0, 3, -5, 2, -1] 9 | * 10 | * sumRange(0, 2) -> 1 11 | * 12 | * sumRange(2, 5) -> -1 13 | * 14 | * sumRange(0, 5) -> -3 15 | * 16 | * Note: 17 | * 18 | * You may assume that the array does not change. 19 | * 20 | * There are many calls to sumRange function. 21 | * 22 | * Tags: Dynamic Programming 23 | * 24 | * Similar Problems: (M) Range Sum Query 2D - Immutable, (M) Range Sum Query - Mutable, (E) Maximum Size Subarray Sum 25 | * Equals k 26 | */ 27 | public class RangeSumQueryImmutable { 28 | 29 | class NumArray { 30 | 31 | private int[] nums; 32 | 33 | public NumArray(int[] nums) { 34 | for (int i = 1; i < nums.length; i++) { 35 | nums[i] += nums[i - 1]; 36 | } 37 | this.nums = nums; 38 | } 39 | 40 | public int sumRange(int i, int j) { 41 | return i == 0 ? nums[j] : nums[j] - nums[i - 1]; 42 | } 43 | 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/DeepestNode.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Returns the deepest node in a binary tree. If the tree is complete, having 5 | * two same depth of node, return the rightmost node. 6 | * 7 | * Tags: Tree, DFS, Backtracking 8 | */ 9 | class DeepestNode { 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public Node deepestNode(Node root) { 15 | Node res = null; 16 | findDeepest(root, res, 0, 0); 17 | return res; 18 | } 19 | 20 | /** 21 | * Backtracking 22 | * If level > max, means a deeper node, update result and max level 23 | * Find more possibility in left and right subtrees 24 | */ 25 | private void findDeepest(Node root, Node res, int level, int max) { 26 | if (root == null) return; 27 | if (level > max) { 28 | res = root; 29 | max = level; 30 | return; 31 | } 32 | findDeepest(root.left, res, level + 1, max); 33 | findDeepest(root.right, res, level + 1, max); 34 | } 35 | 36 | class Node { 37 | int val; 38 | Node left; 39 | Node right; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/LongestIncreasingSubsequenceTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class LongestIncreasingSubsequenceTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[]{10, 9, 2, 5, 3, 7, 101, 18}, 4}, 13 | new Object[]{new int[]{1, 2, 3, 4, 5}, 5}, 14 | new Object[]{new int[]{5, 4, 3, 2, 1}, 1}, 15 | new Object[]{new int[]{}, 0} 16 | }; 17 | } 18 | 19 | @Test(dataProvider = "examples") 20 | public void testLengthOfLIS(int[] nums, int expected) { 21 | LongestIncreasingSubsequence l = new LongestIncreasingSubsequence(); 22 | Assert.assertEquals(l.lengthOfLIS(nums), expected); 23 | } 24 | 25 | @Test(dataProvider = "examples") 26 | public void testLengthOfLIS2(int[] nums, int expected) { 27 | LongestIncreasingSubsequence l = new LongestIncreasingSubsequence(); 28 | Assert.assertEquals(l.lengthOfLIS2(nums), expected); 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/CoinChange.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * You are given coins of different denominations and a total amount of money amount. Write a function to compute the 7 | * fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any 8 | * combination of the coins, return -1. 9 | *

10 | * Example 1: 11 | * coins = [1, 2, 5], amount = 11 12 | * return 3 (11 = 5 + 5 + 1) 13 | *

14 | * Example 2: 15 | * coins = [2], amount = 3 16 | * return -1. 17 | *

18 | * Note: 19 | * You may assume that you have an infinite number of each kind of coin. 20 | *

21 | * Tags: Dynamic Programming 22 | */ 23 | public class CoinChange { 24 | 25 | public int coinChange(int[] coins, int amount) { 26 | int[] res = new int[amount + 1]; 27 | Arrays.fill(res, 1, amount + 1, amount + 1); 28 | for (int coin : coins) { 29 | for (int i = coin; i < res.length; i++) { 30 | res[i] = Math.min(res[i], res[i - coin] + 1); 31 | } 32 | } 33 | return res[amount] == amount + 1 ? -1 : res[amount]; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/ClosestLeafInABinaryTreeTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import com.freetymekiyan.algorithms.utils.Utils.TreeNode; 5 | import org.testng.Assert; 6 | import org.testng.annotations.Test; 7 | 8 | import java.util.Set; 9 | 10 | public class ClosestLeafInABinaryTreeTest { 11 | 12 | @Test 13 | public void testFindClosestLeaf() { 14 | TreeNode root = Utils.buildBinaryTree(new Integer[]{1, 3, 2}); 15 | int k = 1; 16 | ClosestLeafInABinaryTree c = new ClosestLeafInABinaryTree(); 17 | int closestLeaf = c.findClosestLeaf(root, k); 18 | Assert.assertTrue(Set.of(2, 3).contains(closestLeaf)); 19 | 20 | root = Utils.buildBinaryTree(new Integer[]{1}); 21 | k = 1; 22 | Assert.assertEquals(c.findClosestLeaf(root, k), 1); 23 | 24 | root = Utils.buildBinaryTree(new Integer[]{1, 2, 3, null, null, 4, null, 5}); 25 | k = 5; 26 | Assert.assertEquals(c.findClosestLeaf(root, k), 5); 27 | 28 | root = Utils.buildBinaryTree(new Integer[]{1, 2}); 29 | k = 1; 30 | Assert.assertEquals(c.findClosestLeaf(root, k), 2); 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/InsertionSortList.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | /** 4 | * Sort a linked list using insertion sort. 5 | *

6 | * Tags: Linkedlist, Sort 7 | */ 8 | class InsertionSortList { 9 | 10 | /** 11 | * Check the list one by one to find a node that has smaller value than 12 | * nodes before it and swap 13 | */ 14 | public ListNode insertionSortList(ListNode head) { 15 | if (head == null || head.next == null) return head; 16 | ListNode pre = new ListNode(0); 17 | pre.next = head; 18 | 19 | for (ListNode p = head.next, prev = head; p != null; prev = p, p = p.next) { 20 | for (ListNode c = pre; c.next != p; c = c.next) { 21 | if (c.next.val > p.val) { 22 | prev.next = p.next; // skip p 23 | p.next = c.next; // insert between cur and cur.next 24 | c.next = p; 25 | p = prev; // p is inserted to somewhere in the front, reset 26 | break; 27 | } 28 | } 29 | } 30 | return pre.next; 31 | } 32 | 33 | public static class ListNode { 34 | int val; 35 | ListNode next; 36 | 37 | ListNode(int x) { 38 | val = x; 39 | next = null; 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/WordSearchTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.junit.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class WordSearchTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | char[][] board = { 12 | {'A', 'B', 'C', 'E'}, 13 | {'S', 'F', 'C', 'S'}, 14 | {'A', 'D', 'E', 'E'} 15 | }; 16 | return new Object[][]{ 17 | new Object[]{board, "ABCCED", true}, 18 | new Object[]{board, "SEE", true}, 19 | new Object[]{board, "ABCB", false} 20 | }; 21 | } 22 | 23 | @Test(dataProvider = "examples") 24 | public void testExist(char[][] board, String word, boolean expected) { 25 | WordSearch w = new WordSearch(); 26 | Assert.assertEquals(w.exist(board, word), expected); 27 | } 28 | 29 | @Test(dataProvider = "examples") 30 | public void testExist2(char[][] board, String word, boolean expected) { 31 | WordSearch w = new WordSearch(); 32 | Assert.assertEquals(w.exist2(board, word), expected); 33 | } 34 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/BestTimeStock2.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | /** 4 | * Say you have an array for which the ith element is the price of a given 5 | * stock on day i. 6 | *

7 | * Design an algorithm to find the maximum profit. You may complete 8 | * as many transactions as you like (ie, buy one and sell 9 | * one share of the stock multiple times). However, you may not engage in 10 | * multiple transactions at the same time (ie, you must sell the stock 11 | * before you buy again). 12 | *

13 | * Tags: Array, Greedy 14 | */ 15 | class BestTimeStock2 { 16 | 17 | public static void main(String[] args) { 18 | int[] prices = {1, 2, 10, 100}; 19 | System.out.println(maxProfit(prices)); 20 | } 21 | 22 | /** 23 | * Sell whenever there is profit. 24 | * If next value is bigger, add the difference up to the profit 25 | */ 26 | public static int maxProfit(int[] prices) { 27 | int max = 0; 28 | for (int i = 0; i < prices.length - 1; i++) { 29 | if (prices[i + 1] > prices[i]) { 30 | max += prices[i + 1] - prices[i]; 31 | } 32 | } 33 | return max; 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/RateLimiter.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | class RateLimiter { 4 | 5 | private long lastTime = System.currentTimeMillis(); 6 | private int count; 7 | 8 | public static void main(String[] args) { 9 | final RateLimiter r = new RateLimiter(); 10 | Thread t = new Thread(() -> { 11 | while (true) { 12 | try { 13 | Thread.sleep(100); 14 | int count = r.rateLimiter(); 15 | System.out.println("rate is: " + count); 16 | } catch (InterruptedException e) { 17 | e.printStackTrace(); 18 | } 19 | } 20 | }); 21 | t.start(); 22 | } 23 | 24 | private int rateLimiter() { 25 | if (System.currentTimeMillis() - lastTime > 1000) { 26 | count = 0; 27 | lastTime = System.currentTimeMillis(); 28 | } 29 | count++; 30 | if (count > 5) { 31 | // do something 32 | return count; 33 | } 34 | api(); 35 | return count; 36 | } 37 | 38 | private void api() { 39 | System.out.println("API called"); 40 | } 41 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/MissingRangesTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.junit.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | import java.util.Collections; 8 | import java.util.List; 9 | 10 | public class MissingRangesTest { 11 | 12 | @DataProvider 13 | public Object[][] successExamples() { 14 | return new Object[][]{ 15 | new Object[]{new int[]{0, 1, 3, 50, 75}, 0, 99, List.of("2", "4->49", "51->74", "76->99")}, 16 | new Object[]{new int[]{-1}, -2, -1, List.of("-2")}, 17 | new Object[]{new int[]{1, 1, 1}, 1, 1, Collections.emptyList()}, 18 | new Object[]{new int[]{1, 3}, 0, 9, List.of("0", "2", "4->9")}, 19 | new Object[]{new int[]{-2147483648, 2147483647}, -2147483648, 2147483647, List.of("-2147483647->2147483646")}, 20 | new Object[]{new int[]{-1}, -1, 0, List.of("0")} 21 | }; 22 | } 23 | 24 | @Test(dataProvider = "successExamples") 25 | public void testFindMissingRanges(int[] nums, int lower, int upper, List expected) { 26 | final MissingRanges m = new MissingRanges(); 27 | Assert.assertEquals(expected, m.findMissingRanges(nums, lower, upper)); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/NthDigit.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * 400. Nth Digit 5 | *

6 | * Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 7 | *

8 | * Note: 9 | * n is positive and will fit within the range of a 32-bit signed integer (n < 231). 10 | *

11 | * Example 1: 12 | *

13 | * Input: 14 | * 3 15 | *

16 | * Output: 17 | * 3 18 | * Example 2: 19 | *

20 | * Input: 21 | * 11 22 | *

23 | * Output: 24 | * 0 25 | *

26 | * Explanation: 27 | * The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. 28 | *

29 | * Companies: Adobe, Google, Works Application 30 | *

31 | * Related Topics: Math 32 | */ 33 | public class NthDigit { 34 | 35 | public int findNthDigit(int n) { 36 | int len = 1; 37 | long count = 9; 38 | int start = 1; 39 | 40 | while (n > len * count) { 41 | n -= len * count; 42 | len += 1; 43 | count *= 10; 44 | start *= 10; 45 | } 46 | 47 | start += (n - 1) / len; 48 | String s = Integer.toString(start); 49 | return Character.getNumericValue(s.charAt((n - 1) % len)); 50 | } 51 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/CountAndSay.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * 38. Count and Say 5 | *

6 | * The count-and-say sequence is the sequence of integers beginning as follows: 7 | * 1, 11, 21, 1211, 111221, ... 8 | *

9 | * 1 is read off as "one 1" or 11. 10 | * 11 is read off as "two 1s" or 21. 11 | * 21 is read off as "one 2, then one 1" or 1211. 12 | * Given an integer n, generate the nth sequence. 13 | *

14 | * Note: The sequence of integers will be represented as a string. 15 | *

16 | * Company Tags: Facebook 17 | * Tags: String 18 | * Similar Problems: (M) Encode and Decode Strings 19 | */ 20 | class CountAndSay { 21 | 22 | /** 23 | * String. Simulate the process. 24 | * Generate the next sequence. 25 | * Repeat n-1 times. 26 | */ 27 | public String countAndSay(int n) { 28 | String res = "1"; 29 | while (n > 1) { 30 | StringBuilder s = new StringBuilder(); 31 | for (int i = 0, j = i; i < res.length(); i = j) { 32 | while (j < res.length() && res.charAt(i) == res.charAt(j)) { 33 | j++; 34 | } 35 | s.append(j - i).append(res.charAt(i)); 36 | } 37 | res = s.toString(); 38 | n--; 39 | } 40 | return res; 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/database/medium/RankScores.sql: -------------------------------------------------------------------------------- 1 | Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks. 2 | 3 | +----+-------+ 4 | | Id | Score | 5 | +----+-------+ 6 | | 1 | 3.50 | 7 | | 2 | 3.65 | 8 | | 3 | 4.00 | 9 | | 4 | 3.85 | 10 | | 5 | 4.00 | 11 | | 6 | 3.65 | 12 | +----+-------+ 13 | For example, given the above Scores table, your query should generate the following report (order by highest score): 14 | 15 | +-------+------+ 16 | | Score | Rank | 17 | +-------+------+ 18 | | 4.00 | 1 | 19 | | 4.00 | 1 | 20 | | 3.85 | 2 | 21 | | 3.65 | 3 | 22 | | 3.65 | 3 | 23 | | 3.50 | 4 | 24 | +-------+------+ 25 | 26 | ------ 27 | COUNT() 28 | Select Distinct values from Scores table 29 | Put in Ranking Table 30 | Choose Scores.Score <= Ranking.Score 31 | ------ 32 | 33 | SELECT Scores.Score, COUNT(Ranking.Score) AS Rank 34 | FROM Scores 35 | , ( 36 | SELECT DISTINCT Score 37 | FROM Scores 38 | ) Ranking 39 | WHERE Scores.Score <= Ranking.Score 40 | GROUP BY Scores.Id 41 | ORDER BY Scores.Score DESC; 42 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/datastructures/LinkedListQueue.java: -------------------------------------------------------------------------------- 1 | /** 2 | * void enqueue(Item item) 3 | * Item dequeue() 4 | * int size() 5 | * boolean isEmpty() 6 | */ 7 | public class LinkedListQueue { 8 | 9 | private Node first; // link to least recently added node 10 | private Node last; // link to most recently added node 11 | private int N; // number of items on the queue 12 | 13 | public void enqueue(Item item) { 14 | Node oldLast = last; 15 | last = new Node(); 16 | last.item = item; 17 | last.next = null; // unnecessary 18 | if (isEmpty()) { 19 | first = last; // only 1 node 20 | } else { 21 | oldLast.next = last; 22 | } 23 | N++; 24 | } 25 | 26 | public Item dequeue() { 27 | Item item = first.item; 28 | first = first.next; 29 | N--; 30 | if (isEmpty()) { 31 | last = null; // no more node 32 | } 33 | return item; 34 | } 35 | 36 | public int size() { 37 | return N; 38 | } 39 | 40 | public boolean isEmpty() { 41 | return first == null; 42 | } 43 | 44 | private class Node { 45 | 46 | Item item; 47 | Node next; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/SqrtTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class SqrtTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | int[] nums = {0, 1, 2, 4, 9, 16, 25}; 12 | int[] res = {0, 1, 1, 2, 3, 4, 5}; 13 | Object[][] examples = new Object[nums.length][2]; 14 | for (int i = 0; i < examples.length; i++) { 15 | examples[i][0] = nums[i]; 16 | examples[i][1] = res[i]; 17 | } 18 | return examples; 19 | } 20 | 21 | @Test(dataProvider = "examples") 22 | public void testMySqrt(int x, int r) { 23 | Sqrt s = new Sqrt(); 24 | Assert.assertEquals(s.mySqrt(x), r); 25 | } 26 | 27 | @Test(dataProvider = "examples") 28 | public void testMySqrt2(int x, int r) { 29 | Sqrt s = new Sqrt(); 30 | Assert.assertEquals(s.mySqrt2(x), r); 31 | } 32 | 33 | @Test(dataProvider = "examples") 34 | public void testMySqrt3(int x, int r) { 35 | Sqrt s = new Sqrt(); 36 | Assert.assertEquals(s.mySqrt3(x), r); 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/cpp/083_Remove_Duplicates_from_Sorted_List.cpp: -------------------------------------------------------------------------------- 1 | //083 Remove Duplicates from Sorted List 2 | /* 3 | *Given a sorted linked list, delete all duplicates such that each element appear only once. 4 | * 5 | *For example, 6 | *Given 1->1->2, return 1->2. 7 | *Given 1->1->2->3->3, return 1->2->3. 8 | * 9 | *Tag: Linked List 10 | * 11 | *Author: Linsen Wu 12 | */ 13 | 14 | #include "stdafx.h" 15 | 16 | //Definition for singly-linked list. 17 | struct ListNode { 18 | int val; 19 | ListNode *next; 20 | ListNode(int x) : val(x), next(NULL) {} 21 | }; 22 | 23 | class Solution { 24 | public: 25 | ListNode* deleteDuplicates(ListNode* head) { 26 | if (head == NULL) 27 | { 28 | return NULL; 29 | } 30 | 31 | ListNode* current = head->next; 32 | ListNode* previous = head; 33 | 34 | while (current != NULL) 35 | { 36 | if (previous->val == current->val) 37 | { 38 | current = current->next; 39 | if (current == NULL) 40 | { 41 | previous->next = NULL; 42 | } 43 | 44 | } else 45 | { 46 | previous->next = current; 47 | previous = current; 48 | current = current->next; 49 | } 50 | } 51 | 52 | return head; 53 | } 54 | }; 55 | 56 | 57 | int _tmain(int argc, _TCHAR* argv[]) 58 | { 59 | return 0; 60 | } 61 | 62 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/RemoveElement.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * Given an array and a value, remove all instances of that value in place and 5 | * return the new length. 6 | * 7 | * The order of elements can be changed. It doesn't matter what you leave 8 | * beyond the new length. 9 | * 10 | * Tags: Array, Two pointers 11 | */ 12 | class RemoveElement { 13 | public static void main(String[] args) { 14 | RemoveElement r = new RemoveElement(); 15 | // int[] A = { 1 }; 16 | // int[] A = { 1, 2, 3, 4 }; 17 | int[] A = { 1, 2, 1 }; 18 | int elem = 1; 19 | System.out.println(r.removeElement(A, elem)); 20 | } 21 | 22 | /** 23 | * Order is not important 24 | * Just move the last elem to removed position 25 | */ 26 | public int removeElement(int[] A, int elem) { 27 | if (A == null || A.length == 0) return 0; 28 | int i = 0; 29 | int j = A.length; 30 | while (i < j) { 31 | if (A[i] == elem) { 32 | A[i] = A[j - 1]; // move last element 33 | j--; // decrease length 34 | } else i++; // move on 35 | } 36 | return j; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/RemoveNthNodeFromEnd.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils.ListNode; 4 | 5 | /** 6 | * Given a linked list, remove the nth node from the end of list and return its 7 | * head. 8 | *

9 | * For example, 10 | *

11 | * Given linked list: 1->2->3->4->5, and n = 2. 12 | *

13 | * After removing the second node from the end, the linked list becomes 14 | * 1->2->3->5. 15 | *

16 | * Note: 17 | * Given n will always be valid. 18 | * Try to do this in one pass. 19 | *

20 | * Tags: Linked list, Two pointers 21 | */ 22 | class RemoveNthNodeFromEnd { 23 | 24 | /** 25 | * Dummy head and Runner's technique 26 | */ 27 | public ListNode removeNthFromEnd(ListNode head, int n) { 28 | ListNode pre = new ListNode(0); 29 | pre.next = head; 30 | ListNode p1 = pre; 31 | ListNode p2 = pre; 32 | int i = 0; 33 | while (i < n) { 34 | p2 = p2.next; 35 | i++; 36 | } 37 | while (p2.next != null) { 38 | p1 = p1.next; 39 | p2 = p2.next; 40 | } 41 | 42 | p1.next = p1.next.next; 43 | return pre.next; 44 | } 45 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/SumOfTwoIntegers.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * 371. Sum of Two Integers 5 | *

6 | * Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 7 | *

8 | * Example: 9 | * Given a = 1 and b = 2, return 3. 10 | *

11 | * Tags: Bit Manipulation 12 | * Similar Problems: (M) Add Two Numbers 13 | */ 14 | public class SumOfTwoIntegers { 15 | 16 | /** 17 | * For example, a = 0001, b = 0011. 18 | * First, we can use "and"("&") operation between a and b to find a carry. 19 | * carry = a & b, then carry = 0001 20 | * Second, we can use "xor" ("^") operation between a and b to find the different bit, and assign it to a. 21 | * Then, we shift carry one position left and assign it to b, b = 0010. 22 | * Iterate until there is no carry (or b == 0) 23 | */ 24 | public int getSum(int a, int b) { 25 | if (b == 0) return a; 26 | 27 | while (b != 0) { 28 | int carry = a & b; 29 | a = a ^ b; 30 | b = carry << 1; 31 | } 32 | 33 | return a; 34 | } 35 | 36 | public int getSumRecursive(int a, int b) { 37 | if (b == 0) return a; 38 | return getSumRecursive(a ^ b, (a & b) << 1); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/cpp/104_Maximum_Depth_of_Binary_Tree.cpp: -------------------------------------------------------------------------------- 1 | // 104 Maximum Depth of Binary Tree 2 | /** 3 | * Given a binary tree, find its maximum depth. 4 | * 5 | * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 6 | * 7 | * Author: Yanbin Lu 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | using namespace std; 20 | 21 | struct TreeNode { 22 | int val; 23 | TreeNode *left; 24 | TreeNode *right; 25 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 26 | }; 27 | 28 | class Solution { 29 | public: 30 | int maxDepth(TreeNode* root) { 31 | if(root) 32 | return 1 + max(maxDepth(root->left), maxDepth(root->right)); 33 | else 34 | return 0; 35 | } 36 | }; 37 | 38 | int main() 39 | { 40 | 41 | TreeNode* root = new TreeNode(0); 42 | root->left = new TreeNode(1); 43 | root->right = new TreeNode(2); 44 | root->left->right = new TreeNode(3); 45 | 46 | Solution* sol = new Solution(); 47 | cout << sol->maxDepth(root) << endl; 48 | 49 | char c; 50 | std::cin>>c; 51 | 52 | return 0; 53 | } -------------------------------------------------------------------------------- /src/main/cpp/058_Length_of_Last_Word.cpp: -------------------------------------------------------------------------------- 1 | // 58. Length of Last Word 2 | /** 3 | * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. 4 | * 5 | * If the last word does not exist, return 0. 6 | * 7 | * Note: A word is defined as a character sequence consists of non-space characters only. 8 | * 9 | * For example, 10 | * Given s = "Hello World", 11 | * return 5. 12 | * 13 | * Tags: String 14 | * 15 | * Author: Kuang Qin 16 | */ 17 | 18 | #include "stdafx.h" 19 | #include 20 | 21 | using namespace std; 22 | 23 | class Solution { 24 | public: 25 | int lengthOfLastWord(string s) { 26 | int n = s.size(); 27 | if (n == 0) 28 | { 29 | return 0; 30 | } 31 | 32 | // remove trailing spaces 33 | int last = n - 1; 34 | while (last >= 0 && s[last] == ' ') 35 | { 36 | last--; 37 | } 38 | 39 | // start to count of the last word 40 | int len = 0; 41 | while (last >= 0 && s[last] != ' ') 42 | { 43 | len++; 44 | last--; 45 | } 46 | 47 | return len; 48 | } 49 | }; 50 | 51 | int _tmain(int argc, _TCHAR* argv[]) 52 | { 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/PrefixAndSuffixSearchTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | public class PrefixAndSuffixSearchTest { 7 | 8 | @Test 9 | public void testWordFilterExample() { 10 | String[] words = {"apple"}; 11 | PrefixAndSuffixSearch.WordFilter w = new PrefixAndSuffixSearch.WordFilter(words); 12 | Assert.assertEquals(0, w.f("a", "e")); 13 | Assert.assertEquals(-1, w.f("b", "")); 14 | Assert.assertEquals(0, w.f("", "")); 15 | Assert.assertEquals(0, w.f("", "le")); 16 | 17 | words = new String[]{"abbbababbb", "baaabbabbb", "abababbaaa", "abbbbbbbba", "bbbaabbbaa", "ababbaabaa", "baaaaabbbb", "babbabbabb", "ababaababb", "bbabbababa"}; 18 | String[][] inputs = {{"", "abaa"}, {"babbab", ""}, {"ab", "baaa"}, {"baaabba", "b"}, {"abab", "abbaabaa"}, {"", "aa"}, {"", "bba"}, {"", "baaaaabbbb"}, {"ba", "aabbbb"}, {"baaa", "aabbabbb"}}; 19 | int[] expected = {5, 7, 2, 1, 5, 5, 3, 6, 6, 1}; 20 | w = new PrefixAndSuffixSearch.WordFilter(words); 21 | for (int i = 0; i < inputs.length; i++) { 22 | Assert.assertEquals(expected[i], w.f(inputs[i][0], inputs[i][1])); 23 | } 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /src/main/cpp/190_Reverse_Bits.cpp: -------------------------------------------------------------------------------- 1 | //190. Reverse Bits 2 | /* 3 | *Reverse bits of a given 32 bits unsigned integer. 4 | * 5 | *For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). 6 | * 7 | *Follow up: 8 | *If this function is called many times, how would you optimize it? 9 | * 10 | *Related problem: Reverse Integer 11 | * 12 | *Tag: Bit Manipulation 13 | * 14 | *Author: Linsen Wu 15 | */ 16 | 17 | #include "stdafx.h" 18 | #include 19 | 20 | class Solution { 21 | public: 22 | uint32_t reverseBits(uint32_t n) { 23 | uint32_t left = 0x80000000; 24 | uint32_t right = 0x00000001; 25 | 26 | for (int i = 0; i < 16; i++) 27 | { 28 | uint32_t leftbit = n & left; 29 | uint32_t rightbit = n & right; 30 | leftbit = leftbit >> 31-i*2; 31 | rightbit = rightbit << 31-i*2; 32 | 33 | n = n & ~left & ~right; 34 | n = n | leftbit | rightbit; 35 | 36 | left = left >> 1; 37 | right = right << 1; 38 | 39 | } 40 | 41 | return n; 42 | } 43 | }; 44 | 45 | 46 | int _tmain(int argc, _TCHAR* argv[]) 47 | { 48 | uint32_t input = 0x80000000; 49 | 50 | Solution _solution; 51 | _solution.reverseBits(input); 52 | 53 | return 0; 54 | } 55 | 56 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/FindSecondLargest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Find second largest element from a given array 5 | *

6 | * Example: 7 | * Input: {5, 2, 3, 4} 8 | * Output: 4 9 | *

10 | * Tags: Array 11 | */ 12 | class FindSecondLargest { 13 | 14 | /** 15 | * Second largest element is smaller than or equal to max. 16 | * When current number is >= max, update second max and max. 17 | * Note the equal sign since when another max is found, second max would be the same as max. 18 | * When current element is < max but > second max, update second max only. 19 | */ 20 | public int findSecondLargest(int[] nums) { 21 | if (nums == null || nums.length < 2) 22 | throw new IllegalArgumentException("Input array must exist and have at least 2 numbers."); 23 | int max = Math.max(nums[0], nums[1]); 24 | int sec = Math.min(nums[0], nums[1]); 25 | for (int i = 2; i < nums.length; i++) { 26 | if (nums[i] >= max) { // Update both max and second max. 27 | sec = max; 28 | max = nums[i]; 29 | } else if (nums[i] > sec) { 30 | sec = nums[i]; 31 | } 32 | } 33 | return sec; 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/PascalsTriangle2.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 119. Pascal's Triangle II 8 | *

9 | * Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. 10 | *

11 | * Note that the row index starts from 0. 12 | *

13 | * https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif 14 | *

15 | * In Pascal's triangle, each number is the sum of the two numbers directly above it. 16 | *

17 | * Example: 18 | *

19 | * Input: 3 20 | * Output: [1,3,3,1] 21 | * Follow up: 22 | *

23 | * Could you optimize your algorithm to use only O(k) extra space? 24 | *

25 | * Related Topics: Array 26 | *

27 | * Similar Questions: Pascal's Triangle (E) 28 | */ 29 | public class PascalsTriangle2 { 30 | 31 | public List getRow(int rowIndex) { 32 | List row = new ArrayList<>(rowIndex + 1); 33 | row.add(1); 34 | for (int i = 1; i <= rowIndex; i++) { 35 | for (int j = i - 1; j >= 1; j--) { // backwards 36 | row.set(j, row.get(j - 1) + row.get(j)); 37 | } 38 | row.add(1); // add 1 at the end 39 | } 40 | return row; 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/Pow.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | /** 4 | * 50. Pow(x, n) 5 | *

6 | * Implement pow(x, n). 7 | *

8 | * Company Tags: LinkedIn, Google, Bloomberg, Facebook 9 | * Tags: Binary Search, Math 10 | * Similar Problems: (M) Sqrt(x), (M) Super Pow 11 | */ 12 | public class Pow { 13 | 14 | /** 15 | * Binary Search. Math. 16 | * Decompose the exponent into powers of 2, so that you can keep dividing the problem in half. 17 | * N = 9 = 2^3 + 2^0 = 1001 in binary. Then: x^9 = x^(2^3) * x^(2^0). 18 | * Every time we encounter a 1 in the binary representation of N, multiply the answer with x^(2^i). 19 | * To handle N = Integer.MIN_VALUE, use a long (64-bit) variable. 20 | */ 21 | public double myPow(double x, int n) { 22 | double ans = 1; // Might be a fraction. 23 | long absN = Math.abs((long) n); // Must convert n to long first to avoid overflow. 24 | while (absN > 0) { 25 | if ((absN & 1) == 1) { // Check lowest bit. 26 | ans *= x; 27 | } 28 | absN >>= 1; // Right shift a bit. 29 | x *= x; // x^(2^N) -> x^(2^(N+1)). 30 | } 31 | return n < 0 ? 1 / ans : ans; // Deal with n < 0. 32 | } 33 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/LongestSubstringWithAtMostTwoDistinctCharactersTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class LongestSubstringWithAtMostTwoDistinctCharactersTest { 8 | 9 | @DataProvider 10 | public Object[][] exampleCases() { 11 | return new Object[][]{ 12 | new Object[]{"eceba", 3}, 13 | new Object[]{"ccaabbb", 5}, 14 | new Object[]{"aaa", 3} 15 | }; 16 | } 17 | 18 | @Test(dataProvider = "exampleCases") 19 | public void testLengthOfLongestSubstringTwoDistinct(String s, int length) { 20 | final LongestSubstringWithAtMostTwoDistinctCharacters l = new LongestSubstringWithAtMostTwoDistinctCharacters(); 21 | Assert.assertEquals(l.lengthOfLongestSubstringTwoDistinct(s), length); 22 | } 23 | 24 | @DataProvider 25 | public Object[][] edgeCases() { 26 | return new Object[][]{ 27 | new Object[]{null, 0}, 28 | new Object[]{"", 0}, 29 | new Object[]{"a", 1}, 30 | }; 31 | } 32 | 33 | @Test(dataProvider = "edgeCases") 34 | public void testEdgeCases(String s, int length) { 35 | testLengthOfLongestSubstringTwoDistinct(s, length); 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/other/MinimumDistanceOfTwoSortedArraysTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class MinimumDistanceOfTwoSortedArraysTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[]{1, 4, 7}, new int[]{0, 2, 10}, 1}, 13 | new Object[]{new int[]{1, 2, 3}, new int[]{4, 5, 6}, 1}, 14 | new Object[]{new int[]{1, 2, 3, 4}, new int[]{4, 5, 6}, 0}, 15 | new Object[]{new int[]{2, 2, 2}, new int[]{1, 1, 1, 1, 1}, 1}, 16 | new Object[]{new int[]{}, new int[]{}, Integer.MAX_VALUE}, 17 | new Object[]{new int[]{1}, new int[]{}, Integer.MAX_VALUE}, 18 | new Object[]{new int[]{}, new int[]{2}, Integer.MAX_VALUE} 19 | }; 20 | } 21 | 22 | @Test(dataProvider = "examples") 23 | public void testGetMinDistance(int[] nums1, int[] nums2, int expected) { 24 | MinimumDistanceOfTwoSortedArrays m = new MinimumDistanceOfTwoSortedArrays(); 25 | Assert.assertEquals(m.getMinDistance(nums1, nums2), expected); 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/PowerOfFour.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * 342. Power of Four 5 | *

6 | * Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 7 | *

8 | * Example: 9 | * Given num = 16, return true. Given num = 5, return false. 10 | *

11 | * Follow up: Could you solve it without loops/recursion? 12 | *

13 | * Tags: Bit Manipulation 14 | * Similar Problems: (E) Power of Two, (E) Power of Three 15 | */ 16 | public class PowerOfFour { 17 | 18 | /** 19 | * Power of 4 has only a single bit 1 on the highest bit. 20 | * Plus, this single bit should be on odd digit. 21 | * So create a number that has 1 on each and every digit, which is 0x55555555. 22 | * num & 0x55555555 should not be 0. 23 | */ 24 | public boolean isPowerOfFour(int num) { 25 | return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555) != 0; 26 | } 27 | 28 | /** 29 | * Math 30 | * 4^n % 3 = 1 31 | * Prove by induction. 32 | * Suppose 4^n - 1 can be divided by 3. 33 | * 4^(n + 1) - 1 = 4 * 4^n - 1 = 3 * 4^n + (4^n - 1) 34 | * So (4^n - 1) % 3 = 0 35 | */ 36 | public boolean isPowerOfFourB(int num) { 37 | return (num & (num - 1)) == 0 && num % 3 == 1; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/ProductofArrayExceptSelfTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import org.junit.Assert; 5 | import org.testng.annotations.DataProvider; 6 | import org.testng.annotations.Test; 7 | 8 | public class ProductofArrayExceptSelfTest { 9 | 10 | @DataProvider(name = "examples") 11 | public Object[][] getExamples() { 12 | return new Object[][]{ 13 | new Object[]{new int[]{1, 2, 3, 4}, new int[]{24, 12, 8, 6}}, 14 | new Object[]{new int[]{1, 2, 3}, new int[]{6, 3, 2}}, 15 | new Object[]{new int[]{1, 2}, new int[]{2, 1}}, 16 | }; 17 | } 18 | 19 | 20 | @Test(dataProvider = "examples") 21 | public void testProductExceptSelf(int[] input, int[] output) { 22 | ProductofArrayExceptSelf p = new ProductofArrayExceptSelf(); 23 | Assert.assertTrue(Utils.compareArrays(p.productExceptSelf(input), output)); 24 | } 25 | 26 | @Test(dataProvider = "examples") 27 | public void testProductExceptSelf2(int[] input, int[] output) { 28 | ProductofArrayExceptSelf p = new ProductofArrayExceptSelf(); 29 | Assert.assertTrue(Utils.compareArrays(p.productExceptSelf2(input), output)); 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/MovingAverageFromDataStream.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * 346. Moving Average from Data Stream 5 | *

6 | * Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. 7 | *

8 | * Example: 9 | *

10 | * MovingAverage m = new MovingAverage(3); 11 | * m.next(1) = 1 12 | * m.next(10) = (1 + 10) / 2 13 | * m.next(3) = (1 + 10 + 3) / 3 14 | * m.next(5) = (10 + 3 + 5) / 3 15 | *

16 | * Companies: Google, Amazon, Microsoft, Uber, Bloomberg, Indeed, Facebook, Twitter 17 | *

18 | * Relatede Topics: Design, Queue 19 | */ 20 | public class MovingAverageFromDataStream { 21 | 22 | public class MovingAverage { 23 | private int[] window; 24 | private int n, insert; 25 | private long sum; 26 | 27 | /** Initialize your data structure here. */ 28 | public MovingAverage(int size) { 29 | window = new int[size]; 30 | insert = 0; 31 | sum = 0; 32 | } 33 | 34 | public double next(int val) { 35 | if (n < window.length) n++; 36 | sum -= window[insert]; 37 | sum += val; 38 | window[insert] = val; 39 | insert = (insert + 1) % window.length; 40 | 41 | return (double) sum / n; 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/main/cpp/010_Regular_Expression_Matching.cpp: -------------------------------------------------------------------------------- 1 | //10. Regular Expression Matching 2 | /* 3 | '.' Matches any single character. 4 | '*' Matches zero or more of the preceding element. 5 | 6 | The matching should cover the entire input string (not partial). 7 | 8 | The function prototype should be: 9 | bool isMatch(const char *s, const char *p) 10 | 11 | Some examples: 12 | isMatch("aa","a") → false 13 | isMatch("aa","aa") → true 14 | isMatch("aaa","aa") → false 15 | isMatch("aa", "a*") → true 16 | isMatch("aa", ".*") → true 17 | isMatch("ab", ".*") → true 18 | isMatch("aab", "c*a*b") → true 19 | 20 | Tag: Dynamic Programming, Backtracking, String 21 | 22 | Author: Xinyu Liu 23 | */ 24 | 25 | #include 26 | #include 27 | using namespace std; 28 | 29 | class Solution{ 30 | public: 31 | bool isMatch(string s, string p){ 32 | if (p.empty()) return s.empty(); 33 | 34 | if (p[1] == '*') 35 | return ((!s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1),p))|| isMatch(s,p.substr(2))); 36 | else 37 | return (!s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1),p.substr(1))); 38 | } 39 | }; 40 | 41 | 42 | 43 | void main(){ 44 | string s ("aaa"); 45 | string p ("a*"); 46 | Solution sol; 47 | bool b = sol.isMatch(s,p); 48 | } 49 | -------------------------------------------------------------------------------- /src/main/cpp/011_Container_With_Most_Water.cpp: -------------------------------------------------------------------------------- 1 | //11. Container With Most Water 2 | /* 3 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) 4 | and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 5 | 6 | Note: You may not slant the container. 7 | 8 | Tag: Array, Two Pointers 9 | 10 | Author: Xinyu Liu 11 | */ 12 | #include 13 | #include 14 | #include 15 | using namespace std; 16 | 17 | class Solution { 18 | public: 19 | int maxArea(vector& height) { 20 | if(height.empty()) return 0; 21 | int max_container = 0; 22 | int i = 0, h = 0; 23 | int j = height.size() - 1; 24 | while (i < j){ 25 | h = min(height[i], height[j]); 26 | max_container = max(max_container, (j - i) * h); 27 | while (height[i] <= h && i < j) i++; 28 | while (height[j] <= h && i < j) j--; 29 | } 30 | return max_container; 31 | } 32 | }; 33 | 34 | void main(){ 35 | int a[] = {1,2,4,3}; 36 | vector height(a, a + sizeof(a)/sizeof(int)); 37 | Solution sol; 38 | int max_container = sol.maxArea(height); 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/IntegerBreak.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | /** 4 | * 343. Integer Break 5 | *

6 | * Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those 7 | * integers. Return the maximum product you can get. 8 | *

9 | * For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4). 10 | *

11 | * Note: You may assume that n is not less than 2 and not larger than 58. 12 | *

13 | * Hint: 14 | *

15 | * There is a simple O(n) solution to this problem. 16 | * You may check the breaking results of n ranging from 7 to 10 to discover the regularities. 17 | *

18 | * Tags: Dynamic Programming, Math 19 | */ 20 | public class IntegerBreak { 21 | 22 | /** 23 | * Math. 24 | * If factor x >= 4, we can decompose it into 2 and (x-2), 2 * (x-2)= 2x - 4 > x. 25 | * So the final product will be larger, means that the product won't exceed 4. 26 | */ 27 | public int integerBreak(int n) { 28 | if (n == 2) { 29 | return 1; 30 | } 31 | if (n == 3) { 32 | return 2; 33 | } 34 | int product = 1; 35 | while (n > 4) { 36 | product *= 3; 37 | n -= 3; 38 | } 39 | return product * n; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/SingleNumber3.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | /** 4 | * 260. Single Number III 5 | *

6 | * Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear 7 | * exactly twice. Find the two elements that appear only once. 8 | *

9 | * Example: 10 | *

11 | * Input: [1,2,1,3,2,5] 12 | * Output: [3,5] 13 | * Note: 14 | *

15 | * The order of the result is not important. So in the above example, [5, 3] is also correct. 16 | * Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? 17 | *

18 | * Related Topics: Bit Manipulation 19 | *

20 | * Similar Questions: Single Number (E), Single Number II (M) 21 | */ 22 | public class SingleNumber3 { 23 | 24 | public int[] singleNumber(int[] nums) { 25 | if (nums.length < 3) return nums; 26 | int xor = 0; 27 | for (int i = 0; i < nums.length; i++) { 28 | xor ^= nums[i]; 29 | } 30 | 31 | xor &= -xor; 32 | 33 | int val1 = 0; 34 | int val2 = 0; 35 | for (int i = 0; i < nums.length; i++) { 36 | if ((nums[i] & xor) != 0) val1 ^= nums[i]; 37 | else val2 ^= nums[i]; 38 | } 39 | return new int[]{val1, val2}; 40 | } 41 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/DeepestLeftLeafNode.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils.TreeNode; 4 | 5 | /** 6 | * Given a Binary Tree, find the deepest leaf node that is left child of its 7 | * parent. 8 | *

9 | * Tags: Tree, DFS, Backtracking 10 | */ 11 | class DeepestLeftLeafNode { 12 | public static void main(String[] args) { 13 | 14 | } 15 | 16 | /** 17 | * 18 | */ 19 | public TreeNode deepestLeftLeaf(TreeNode root) { 20 | TreeNode res = null; 21 | deepestLeftLeaf(root, 0, 0, false, res); 22 | return res; 23 | } 24 | 25 | /** 26 | * Backtracking 27 | * If is left child, is leaf node, and level > maxLevel 28 | * Update result and maxLevel, then return 29 | */ 30 | public void deepestLeftLeaf(TreeNode root, int level, int maxLevel, boolean isLeft, TreeNode res) { 31 | if (root == null) return; 32 | 33 | if (isLeft && root.left == null && root.right == null && level > maxLevel) { 34 | res = root; 35 | maxLevel = level; 36 | return; 37 | } 38 | 39 | deepestLeftLeaf(root.left, level + 1, maxLevel, true, res); 40 | deepestLeftLeaf(root.right, level + 1, maxLevel, false, res); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/PowerOfThree.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * Given an integer, write a function to determine if it is a power of three. 5 | *

6 | * Follow up: 7 | * Could you do it without using any loop / recursion? 8 | *

9 | * Tags: Math 10 | * Similar Problems: (E) Power of Two, (E) Power of Four 11 | */ 12 | public class PowerOfThree { 13 | 14 | int maxPow3 = (int) Math.pow(3, (int) (Math.log(Integer.MAX_VALUE) / Math.log(3))); 15 | 16 | /** 17 | * Check if n's modular of 3 is zero. 18 | * If yes, divide n by 3 and check again. 19 | * Stop till n is 1. 20 | */ 21 | public boolean isPowerOfThree(int n) { 22 | if (n <= 0) return false; 23 | while (n > 1 && n % 3 == 0) { 24 | n /= 3; 25 | } 26 | return n == 1; 27 | } 28 | 29 | /** 30 | * Recursive version. 31 | */ 32 | public boolean isPowerOfThreeRecursive(int n) { 33 | return n > 0 && n == 1 && n % 3 == 0 && isPowerOfThreeRecursive(n / 3); 34 | } 35 | 36 | /** 37 | * Find the max power of 3 within int range. 38 | * It should be divisible by all power of 3s. 39 | */ 40 | public boolean isPowerOfThreeB(int n) { 41 | return n > 0 && maxPow3 % n == 0; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/PalindromePairsTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import org.testng.Assert; 5 | import org.testng.annotations.DataProvider; 6 | import org.testng.annotations.Test; 7 | 8 | import java.util.List; 9 | 10 | public class PalindromePairsTest { 11 | 12 | @DataProvider(name = "examples") 13 | public Object[][] getExamples() { 14 | return new Object[][]{ 15 | new Object[]{new String[]{"bat", "tab", "cat"}, List.of(List.of(0, 1), List.of(1, 0))}, 16 | new Object[]{new String[]{"abcd", "dcba", "lls", "s", "sssll"}, List.of(List.of(0, 1), List.of(1, 0), List.of(3, 2), List.of(2, 4))}, 17 | }; 18 | } 19 | 20 | @Test(dataProvider = "examples") 21 | public void testPalindromePairs(String[] words, List> expected) { 22 | PalindromePairs p = new PalindromePairs(); 23 | Assert.assertEquals(p.palindromePairs(words), expected); 24 | } 25 | 26 | @Test(dataProvider = "examples") 27 | public void testPalindromePairs2(String[] words, List> expected) { 28 | PalindromePairs p = new PalindromePairs(); 29 | Assert.assertTrue(Utils.compareListsIgnoreOrder(p.palindromePairs2(words), expected)); 30 | } 31 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/NumberOfCornerRectanglesTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class NumberOfCornerRectanglesTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[][]{new int[]{1, 0, 0, 1, 0}, new int[]{0, 0, 1, 0, 1}, new int[]{0, 0, 0, 1, 0}, new int[]{1, 0, 1, 0, 1}}, 1}, 13 | new Object[]{new int[][]{new int[]{1, 1, 1}, new int[]{1, 1, 1}, new int[]{1, 1, 1}}, 9}, 14 | new Object[]{new int[][]{new int[]{1, 1, 1, 1}}, 0} 15 | }; 16 | } 17 | 18 | @Test(dataProvider = "examples") 19 | public void testCountCornerRectangles(int[][] grid, int expected) { 20 | NumberOfCornerRectangles n = new NumberOfCornerRectangles(); 21 | Assert.assertEquals(n.countCornerRectangles(grid), expected); 22 | } 23 | 24 | @Test(dataProvider = "examples") 25 | public void testCountCornerRectangles2(int[][] grid, int expected) { 26 | NumberOfCornerRectangles n = new NumberOfCornerRectangles(); 27 | Assert.assertEquals(n.countCornerRectangles2(grid), expected); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/RansomNote.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * 383. Ransom Note 5 | *

6 | * Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function 7 | * that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. 8 | *

9 | * Each letter in the magazine string can only be used once in your ransom note. 10 | *

11 | * Note: 12 | * You may assume that both strings contain only lowercase letters. 13 | *

14 | * canConstruct("a", "b") -> false 15 | * canConstruct("aa", "ab") -> false 16 | * canConstruct("aa", "aab") -> true 17 | *

18 | * Companies: Microsoft, Hulu, Apple, Facebook, Google, Yahoo 19 | *

20 | * Related Topics: String 21 | *

22 | * Similar Questions: (H) Stickers to Spell Word 23 | */ 24 | public class RansomNote { 25 | 26 | public boolean canConstruct(String ransomNote, String magazine) { 27 | int[] arr = new int[26]; 28 | for (int i = 0; i < magazine.length(); i++) { 29 | arr[magazine.charAt(i) - 'a']++; 30 | } 31 | for (int i = 0; i < ransomNote.length(); i++) { 32 | if (--arr[ransomNote.charAt(i) - 'a'] < 0) { 33 | return false; 34 | } 35 | } 36 | return true; 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/MostFrequentElementInArray.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * // [1,1,1,2,2,3,3,3,3,3,3,4,4,5,5,6] 5 | * // [1,1,1,1,1,1,1,2,2,2,2,2,2,3,3] 6 | */ 7 | public class MostFrequentElementInArray { 8 | 9 | public static void main(String[] args) { 10 | int[] a = {1, 2}; 11 | System.out.println(mostFrequent(a)); 12 | } 13 | 14 | public static int mostFrequent(int[] array) { 15 | if (array == null || array.length == 0) throw new IllegalArgumentException(); 16 | int max = 1; 17 | int res = array[0]; 18 | for (int i = 0; i < array.length - max; i++) { 19 | int start = i; 20 | if (array[start] != array[start + max]) { 21 | int end = start + max; 22 | while (array[end] == array[end - 1]) { 23 | end--; 24 | } 25 | i = end - 1; 26 | continue; 27 | } 28 | while (i < array.length - max && array[i] == array[i + 1]) { 29 | i++; 30 | } 31 | int length = i - start + 1; 32 | if (length > max) { 33 | max = length; 34 | res = array[start]; 35 | } 36 | } 37 | return res; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/other/DoublyLinkedListToBinarySearchTreeTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import com.freetymekiyan.algorithms.utils.Utils.TreeNode; 5 | import org.testng.Assert; 6 | import org.testng.annotations.Test; 7 | 8 | public class DoublyLinkedListToBinarySearchTreeTest { 9 | 10 | @Test 11 | public void testConvert() { 12 | int[] values = {10, 12, 15, 25, 30, 36}; 13 | TreeNode dummy = null; 14 | TreeNode prev = null; 15 | for (int v : values) { 16 | TreeNode node = new TreeNode(v); 17 | if (dummy == null) { 18 | dummy = new TreeNode(-1); 19 | dummy.right = node; 20 | } 21 | if (prev != null) { 22 | prev.right = node; 23 | node.left = prev; 24 | } 25 | prev = node; 26 | } 27 | dummy.right.left = prev; 28 | prev.right = dummy.right; 29 | DoublyLinkedListToBinarySearchTree d = new DoublyLinkedListToBinarySearchTree(); 30 | TreeNode root = d.convert(dummy.right); 31 | 32 | TreeNode expected = Utils.buildBinaryTree(new Integer[]{25, 12, 36, 10, 15, 30, null}); 33 | Assert.assertTrue(Utils.compareTrees(root, expected)); 34 | } 35 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/AverageOfLevelsInBinaryTreeTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import com.freetymekiyan.algorithms.utils.Utils.TreeNode; 5 | import org.junit.Assert; 6 | import org.testng.annotations.Test; 7 | 8 | import java.util.List; 9 | 10 | public class AverageOfLevelsInBinaryTreeTest { 11 | 12 | @Test 13 | public void testAverageOfLevelsExample() { 14 | TreeNode root = Utils.buildBinaryTree(new Integer[]{3, 9, 20, null, null, 15, 7}); 15 | AverageOfLevelsInBinaryTree a = new AverageOfLevelsInBinaryTree(); 16 | List output = List.of((double) 3, 14.5, (double) 11); 17 | Assert.assertEquals(a.averageOfLevels(root), output); 18 | Assert.assertEquals(a.averageOfLevels2(root), output); 19 | } 20 | 21 | @Test 22 | public void testOverflow() { 23 | TreeNode root = Utils.buildBinaryTree(new Integer[]{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE}); 24 | AverageOfLevelsInBinaryTree a = new AverageOfLevelsInBinaryTree(); 25 | List output = List.of((double) Integer.MAX_VALUE, (double) Integer.MAX_VALUE); 26 | Assert.assertEquals(a.averageOfLevels(root), output); 27 | Assert.assertEquals(a.averageOfLevels2(root), output); 28 | } 29 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/FindSmallestLetterGreaterThanTargetTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | public class FindSmallestLetterGreaterThanTargetTest { 7 | 8 | @Test 9 | public void testNextGreatestLetterExamples() { 10 | char[] letters = {'c', 'f', 'j'}; 11 | FindSmallestLetterGreaterThanTarget f = new FindSmallestLetterGreaterThanTarget(); 12 | char[] targets = {'a', 'c', 'd', 'g', 'j', 'k'}; 13 | char[] outputs = {'c', 'f', 'f', 'j', 'c', 'c'}; 14 | 15 | for (int i = 0; i < targets.length; i++) { 16 | Assert.assertEquals(f.nextGreatestLetter(letters, targets[i]), outputs[i]); 17 | Assert.assertEquals(f.nextGreatestLetter2(letters, targets[i]), outputs[i]); 18 | Assert.assertEquals(f.nextGreatestLetter3(letters, targets[i]), outputs[i]); 19 | } 20 | 21 | letters = new char[]{'e', 'e', 'e', 'e', 'e', 'e', 'n', 'n', 'n', 'n'}; 22 | char target = 'e'; 23 | char output = 'n'; 24 | Assert.assertEquals(f.nextGreatestLetter(letters, target), output); 25 | Assert.assertEquals(f.nextGreatestLetter2(letters, target), output); 26 | Assert.assertEquals(f.nextGreatestLetter3(letters, target), output); 27 | } 28 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/PascalsTriangle.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Given numRows, generate the first numRows of Pascal's triangle. 8 | *

9 | * For example, given numRows = 5, 10 | * Return 11 | *

12 | * [ 13 | * [1], 14 | * [1,1], 15 | * [1,2,1], 16 | * [1,3,3,1], 17 | * [1,4,6,4,1] 18 | * ] 19 | *

20 | * Tags: Array 21 | */ 22 | class PascalsTriangle { 23 | public static void main(String[] args) { 24 | 25 | } 26 | 27 | /** 28 | * Definition 29 | */ 30 | public List> generate(int numRows) { 31 | List> triangle = new ArrayList>(); 32 | if (numRows <= 0) return triangle; 33 | 34 | List firstRow = new ArrayList(); 35 | firstRow.add(1); 36 | triangle.add(firstRow); 37 | 38 | for (int i = 1; i < numRows; i++) { 39 | List lastRow = triangle.get(i - 1); 40 | List row = new ArrayList(i + 1); 41 | 42 | for (int j = 0; j < i + 1; j++) { 43 | if (j == 0 || j == i) { 44 | row.add(1); 45 | } else { 46 | row.add(lastRow.get(j - 1) + lastRow.get(j)); 47 | } 48 | } 49 | triangle.add(row); 50 | } 51 | return triangle; 52 | } 53 | } -------------------------------------------------------------------------------- /src/main/cpp/019_Remove_Nth_Node_From_End_of_List.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a linked list, remove the nth node from the end of list and return its head. 3 | * For example, 4 | 5 | * Given linked list: 1->2->3->4->5, and n = 2. 6 | 7 | * After removing the second node from the end, the linked list becomes 1->2->3->5. 8 | 9 | * Note: 10 | * Given n will always be valid. 11 | * Try to do this in one pass. 12 | * 13 | * Date: 03/04/2016 14 | * Author: SaSa150 15 | */ 16 | 17 | /** 18 | * Definition for singly-linked list. 19 | * struct ListNode { 20 | * int val; 21 | * ListNode *next; 22 | * ListNode(int x) : val(x), next(NULL) {} 23 | * }; 24 | */ 25 | class Solution { 26 | public: 27 | ListNode* removeNthFromEnd(ListNode* head, int n) { 28 | ListNode dum(0), *slow=&dum, *fast=head; 29 | dum.next=head; //get the dum connected 30 | 31 | // move the fast pointer according to the offset 32 | for(int i=0; inext; 33 | while(fast) { 34 | fast=fast->next; 35 | slow=slow->next; 36 | } 37 | //now the slow pointer will be the n+1 th node from the end (may be the dum head) 38 | fast=slow->next; 39 | slow->next=fast->next; 40 | delete fast; //remove the specified node 41 | 42 | return dum.next; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/IntegerToEnglishWordsTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.Test; 5 | 6 | public class IntegerToEnglishWordsTest { 7 | 8 | @Test 9 | public void testNumberToWords() { 10 | int[] inputs = { 11 | 0, 12 | 1, 13 | 2, 14 | 10, 15 | 20, 16 | 21, 17 | 100, 18 | 123, 19 | 1000, 20 | 1100, 21 | 1123, 22 | 1000100 23 | }; 24 | String[] outputs = { 25 | "Zero", 26 | "One", 27 | "Two", 28 | "Ten", 29 | "Twenty", 30 | "Twenty One", 31 | "One Hundred", 32 | "One Hundred Twenty Three", 33 | "One Thousand", 34 | "One Thousand One Hundred", 35 | "One Thousand One Hundred Twenty Three", 36 | "One Million One Hundred" 37 | }; 38 | IntegerToEnglishWords i = new IntegerToEnglishWords(); 39 | for (int j = 0; j < inputs.length; j++) { 40 | Assert.assertEquals(i.numberToWords(inputs[j]), outputs[j]); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/LongestConsecutiveSeqTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class LongestConsecutiveSeqTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[]{100, 4, 200, 3, 1, 2}, 4}, 13 | new Object[]{new int[]{-7, -1, 3, -9, -4, 7, -3, 2, 4, 9, 4, -9, 8, -7, 5, -1, -7}, 4}, 14 | new Object[]{new int[]{-2, -3, -3, 7, -3, 0, 5, 0, -8, -4, -1, 2}, 5}, 15 | new Object[]{new int[]{7, -2, 9, 9, 1, 9, 8, -4, 6, -6, -6, 4, 1, 3, 6, 3, 5, -2, 3, 4, -6, 1, 5, -9, 6, 1, 2, -2, 1}, 9} 16 | }; 17 | } 18 | 19 | @Test(dataProvider = "examples") 20 | public void testLongestConsecutive(int[] nums, int output) { 21 | LongestConsecutiveSeq l = new LongestConsecutiveSeq(); 22 | Assert.assertEquals(l.longestConsecutive(nums), output); 23 | } 24 | 25 | @Test(dataProvider = "examples") 26 | public void testLongestConsecutive2(int[] nums, int output) { 27 | LongestConsecutiveSeq l = new LongestConsecutiveSeq(); 28 | Assert.assertEquals(l.longestConsecutive2(nums), output); 29 | } 30 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/PathSum.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * Given a binary tree and a sum, determine if the tree has a root-to-leaf path 5 | * such that adding up all the values along the path equals the given sum. 6 | * 7 | * For example: 8 | * Given the below binary tree and sum = 22, 9 | * 5 10 | * / \ 11 | * 4 8 12 | * / / \ 13 | * 11 13 4 14 | * / \ \ 15 | * 7 2 1 16 | * 17 | * return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. 18 | * 19 | * Tags: Tree, DFS 20 | */ 21 | class PathSum { 22 | 23 | /** 24 | * Substract root value from sum every time 25 | * Return leaf node with sum == 0 26 | * Or result in left subtree or right subtree 27 | */ 28 | public boolean hasPathSum(TreeNode root, int sum) { 29 | if (root == null) return false; // root == null 30 | sum -= root.val; // update sum 31 | // leaf? sum == 0? left subtree? right subtree? 32 | return root.left == null && root.right == null && sum == 0 || hasPathSum(root.left, sum) || hasPathSum(root.right, sum); 33 | } 34 | 35 | public class TreeNode { 36 | int val; 37 | TreeNode left; 38 | TreeNode right; 39 | 40 | TreeNode(int x) { 41 | val = x; 42 | } 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/MoveZeroesTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | import java.util.Arrays; 8 | 9 | public class MoveZeroesTest { 10 | 11 | @DataProvider(name = "examples") 12 | public Object[][] getExamples() { 13 | return new Object[][]{ 14 | new Object[]{null, null}, 15 | new Object[]{new int[]{}, new int[]{}}, 16 | new Object[]{new int[]{1}, new int[]{1}}, 17 | new Object[]{new int[]{1, 2, 3}, new int[]{1, 2, 3}}, 18 | new Object[]{new int[]{0, 0, 0}, new int[]{0, 0, 0}}, 19 | new Object[]{new int[]{0, 1, 0, 3, 12}, new int[]{1, 3, 12, 0, 0}}, 20 | }; 21 | } 22 | 23 | @Test(dataProvider = "examples") 24 | public void testMoveZeroes(int[] input, int[] output) { 25 | MoveZeroes m = new MoveZeroes(); 26 | m.moveZeroes(input); 27 | Assert.assertTrue(Arrays.equals(input, output)); 28 | } 29 | 30 | @Test(dataProvider = "examples") 31 | public void testMoveZeroesB(int[] input, int[] output) { 32 | MoveZeroes m = new MoveZeroes(); 33 | m.moveZeroes2(input); 34 | Assert.assertTrue(Arrays.equals(input, output)); 35 | } 36 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/MaxProductSubArr.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | /** 4 | * Find the contiguous subarray within an array (containing at least one 5 | * number) which has the largest product. 6 | *

7 | * For example, given the array [2,3,-2,4], 8 | * the contiguous subarray [2,3] has the largest product = 6. 9 | *

10 | * Tags: Array, DP 11 | */ 12 | class MaxProductSubArr { 13 | 14 | public static void main(String[] args) { 15 | 16 | } 17 | 18 | /** 19 | * DP, update according to A[i] 20 | * f(k) = Largest product subarray, from index 0 up to k. 21 | * g(k) = Smallest product subarray, from index 0 up to k. 22 | *

23 | * f(k) = max( f(k-1) * A[k], A[k], g(k-1) * A[k] ) 24 | * g(k) = min( g(k-1) * A[k], A[k], f(k-1) * A[k] ) 25 | */ 26 | public int maxProduct(int[] A) { 27 | if (A == null || A.length == 0) return 0; 28 | 29 | int max = A[0], min = A[0], res = A[0]; 30 | for (int i = 1; i < A.length; i++) { 31 | int preMax = max, preMin = min; // results of last loop 32 | max = Math.max(Math.max(A[i], preMax * A[i]), preMin * A[i]); 33 | min = Math.min(Math.min(A[i], preMax * A[i]), preMin * A[i]); 34 | res = Math.max(max, res); 35 | } 36 | return res; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/cpp/141_Linked_List_Cycle.cpp: -------------------------------------------------------------------------------- 1 | // 141 Linked List Cycle 2 | /** 3 | * Given a linked list, determine if it has a cycle in it. 4 | * 5 | * Follow up: 6 | * Can you solve it without using extra space? 7 | * 8 | * Tag: Linked List, Two Pointers 9 | * 10 | * Author: Yanbin Lu 11 | */ 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | using namespace std; 22 | struct ListNode { 23 | int val; 24 | ListNode *next; 25 | ListNode(int x) : val(x), next(NULL) {} 26 | }; 27 | 28 | class Solution { 29 | public: 30 | bool hasCycle(ListNode *head) { 31 | ListNode* slow = head; 32 | ListNode* fast = head; 33 | while(fast && fast->next){ 34 | fast = fast->next->next; 35 | slow = slow->next; 36 | if(fast == slow) return true; 37 | } 38 | return false; 39 | } 40 | }; 41 | 42 | int main() 43 | { 44 | // creat a cycle list 45 | ListNode* list = new ListNode(3); 46 | list->next = new ListNode(2); 47 | list->next->next = new ListNode(1); 48 | list->next->next->next = new ListNode(4); 49 | list->next->next->next->next = list; 50 | 51 | Solution* sol = new Solution(); 52 | cout<hasCycle(list)<>c; 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/GetNumberOfOnes.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Given a matrix of 1's and 0's, return the number of ones in a random rectangle. 5 | *

6 | * Company: Facebook 7 | */ 8 | public class GetNumberOfOnes { 9 | 10 | private final int[][] nums; 11 | 12 | /** 13 | * Save cumulative sum. 14 | * The sum is the number of ones. 15 | * A rectangle can be represented by 4 other rectangles. 16 | */ 17 | public GetNumberOfOnes(int[][] matrix) { 18 | if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { 19 | throw new IllegalArgumentException("Input matrix should have at least 1 row and 1 column."); 20 | } 21 | int m = matrix.length; 22 | int n = matrix[0].length; 23 | nums = new int[m][n]; 24 | int num = 0; 25 | for (int r = 0; r < m; r++) { 26 | for (int c = 0; c < n; c++) { 27 | if (matrix[r][c] == 1) { 28 | num++; 29 | } 30 | nums[r][c] = num; 31 | } 32 | } 33 | } 34 | 35 | public int getNumberOfOnes(int[] topLeft, int[] bottomRight) { 36 | return nums[bottomRight[0]][bottomRight[1]] - nums[bottomRight[0]][topLeft[1]] - nums[topLeft[0]][bottomRight[1]] + nums[topLeft[0]][topLeft[1]]; 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/AddWithoutOperators.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Write a function addRecursive() that returns sum of two integers. The function should not use any of the arithmetic 5 | * operators 6 | * (+, ++, –, -, .. etc). 7 | *

8 | * http://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/ 9 | *

10 | * Created by kiyan on 6/3/16. 11 | */ 12 | public class AddWithoutOperators { 13 | 14 | /** 15 | * Sum of two bits can be obtained by performing XOR (^) of the two bits. 16 | * Carry bit can be obtained by performing AND (&) of two bits. 17 | */ 18 | public int add(int x, int y) { 19 | // Iterate till there is no carry 20 | while (y != 0) { 21 | // carry now contains common set bits of x and y 22 | int carry = x & y; 23 | // Sum of bits of x and y where at least one of the bits is not set 24 | x = x ^ y; 25 | // Carry is shifted by one so that adding it to x gives the required sum 26 | y = carry << 1; 27 | } 28 | return x; 29 | } 30 | 31 | /** 32 | * Recursive 33 | */ 34 | public int addRecursive(int x, int y) { 35 | if (y == 0) 36 | return x; 37 | else 38 | return addRecursive(x ^ y, (x & y) << 1); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/BinaryTreeLongestPath.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | 4 | import com.freetymekiyan.algorithms.utils.Utils.TreeNode; 5 | 6 | /** 7 | * Given a binary tree, find the longest path from root to a leaf. 8 | * The path can be arrow concatenated string like 1->2->3. 9 | */ 10 | public class BinaryTreeLongestPath { 11 | 12 | /** 13 | * Backtracking. 14 | * Maintain a max length, a current length and current values. 15 | * When at a leaf node, compare with existing max to see if the path is longest. 16 | */ 17 | public String longestPath(TreeNode root) { 18 | String[] res = new String[1]; 19 | dfs(root, new StringBuilder(), new int[1], 0, res); 20 | return res[0]; 21 | } 22 | 23 | private void dfs(TreeNode root, StringBuilder sb, int[] max, int current, String[] res) { 24 | if (root == null) { 25 | if (current > max[0]) { 26 | max[0] = current; 27 | res[0] = sb.delete(sb.length() - 2, sb.length()).toString(); 28 | } 29 | return; 30 | } 31 | sb.append(root.val).append("->"); 32 | int len = sb.length(); 33 | dfs(root.left, sb, max, current + 1, res); 34 | sb.setLength(len); 35 | dfs(root.right, sb, max, current + 1, res); 36 | sb.setLength(len); 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/RemoveDuplicatesFromSortedArray2.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | /** 4 | * 80. Remove Duplicates from Sorted Array II 5 | *

6 | * Follow up for "Remove Duplicates": 7 | * What if duplicates are allowed at most twice? 8 | *

9 | * For example, 10 | * Given sorted array A = [1,1,1,2,2,3], 11 | *

12 | * Your function should return length = 5, and A is now [1,1,2,2,3]. 13 | *

14 | * Tags: Array, Two pointers 15 | */ 16 | class RemoveDuplicatesFromSortedArray2 { 17 | 18 | /** 19 | * Two Pointers. 20 | * When there are less than 2 elements, there cannot be more than 2 duplicates. So just return length. 21 | * Compare current element with second last element of the new array. 22 | * If they are the same, there will be more than 2 duplicates, skip. 23 | * If they are different, copy the element to the front and increment the new array length by 1. 24 | */ 25 | public int removeDuplicates(int[] nums) { 26 | if (nums == null) return 0; 27 | int n = nums.length; 28 | if (n <= 2) 29 | return n; 30 | int length = 2; 31 | for (int i = 2; i < n; i++) { 32 | if (nums[i] != nums[length - 2]) { // Compare with the second last element of the new array. 33 | nums[length] = nums[i]; 34 | length++; 35 | } 36 | } 37 | return length; 38 | } 39 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/FindDup.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Find duplicates in O(n) time and O(1) extra space 5 | * 6 | * Given an array of n elements which contains elements from 0 to n-1, with any 7 | * of these numbers appearing any number of times. Find these repeating numbers 8 | * in O(n) and using only constant memory space. 9 | * 10 | * For example, let n be 7 and array be {1, 2, 3, 1, 3, 6, 6}, the answer 11 | * should be 1, 3 and 6. 12 | * 13 | * Tags: Array 14 | */ 15 | class FindDup { 16 | public static void main(String[] args) { 17 | int[] num = {1, 2, 3, 1, 3, 6, 6}; 18 | new FindDup().printRepeating(num); 19 | 20 | } 21 | 22 | /** 23 | * Check the sign of A[abs(A[i])] 24 | * if positive then make it negative by A[abs(A[i])] = -A[abs(A[i])] 25 | * else this element (ith element of list) is a duplication 26 | */ 27 | public void printRepeating(int[] num) { 28 | if (num == null || num.length == 0) return; 29 | for (int i = 0; i < num.length; i++) { 30 | if (num[Math.abs(num[i])] < 0) { // duplicate 31 | System.out.println(Math.abs(num[i])); // print dups 32 | } else { // set flag 33 | num[Math.abs(num[i])] = -num[Math.abs(num[i])]; // mark 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/datastructures/LinkedListStack.java: -------------------------------------------------------------------------------- 1 | /** 2 | * void push(Item item) 3 | * Item pop() 4 | * boolean isEmpty() 5 | * int size() 6 | */ 7 | public class LinkedListStack { 8 | 9 | private Node first; 10 | private int N; 11 | 12 | public static void main(String[] args) { 13 | LinkedListStack stack = new LinkedListStack<>(); 14 | stack.push("to"); 15 | stack.push("be"); 16 | stack.push("or"); 17 | stack.push("not"); 18 | stack.pop(); 19 | stack.pop(); 20 | stack.push("to"); 21 | stack.push("be"); 22 | stack.pop(); 23 | stack.push("that"); 24 | stack.pop(); 25 | stack.pop(); 26 | System.out.println("stack = " + stack); 27 | } 28 | 29 | public void push(Item item) { 30 | Node oldFirst = first; 31 | first = new Node(); 32 | first.item = item; 33 | first.next = oldFirst; 34 | N++; 35 | } 36 | 37 | public Item pop() { 38 | Item item = first.item; 39 | first = first.next; 40 | N--; 41 | return item; 42 | } 43 | 44 | public int size() { 45 | return N; 46 | } 47 | 48 | public boolean isEmpty() { 49 | return first == null; 50 | } 51 | 52 | private class Node { 53 | 54 | Item item; 55 | Node next; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/hard/FindMinimumInRotatedSortedArray2.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | /** 4 | * 154. Find Minimum in Rotated Sorted Array II 5 | *

6 | * Follow up for "Find Minimum in Rotated Sorted Array": 7 | * What if duplicates are allowed? 8 | * Would this affect the run-time complexity? How and why? 9 | *

10 | * Suppose a sorted array is rotated at some pivot unknown to you beforehand. 11 | * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). 12 | *

13 | * Find the minimum element. 14 | * The array may contain duplicates. 15 | *

16 | * Tags: Array, Binary Search 17 | */ 18 | class FindMinimumInRotatedSortedArray2 { 19 | 20 | /** 21 | * Binary Search. 22 | * Compare nums[mid] with nums[hi]. 23 | * When nums[mid] = nums[hi], we are not sure which side contains the min. 24 | * So we just shrink the solution space by 1. 25 | * Since nums[mid] is still there, this is fine. 26 | * The complexity becomes O(n) in worst case. 27 | */ 28 | public int findMin(int[] nums) { 29 | int lo = 0, hi = nums.length - 1; 30 | while (lo < hi) { 31 | int mid = lo + (hi - lo) / 2; 32 | if (nums[mid] > nums[hi]) { 33 | lo = mid + 1; 34 | } else if (nums[mid] < nums[hi]) { 35 | hi = mid; 36 | } else { 37 | hi--; 38 | } 39 | } 40 | return nums[lo]; 41 | } 42 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/LargestNumber_shuna.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import java.util.Comparator; 4 | import java.util.PriorityQueue; 5 | import java.util.Queue; 6 | 7 | /** 8 | * Largest Number 9 | * Given a list of non negative integers, arrange them such that they form the largest number. 10 | * For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. 11 | * Note: The result may be very large, so you need to return a string instead of an integer. 12 | * Tags: Sort 13 | * Notes: PriorityQueue and Comparator 14 | * 15 | * @author chenshuna 16 | */ 17 | 18 | class LargestNumber_Shuna { 19 | 20 | public String largestNumber(int[] nums) { 21 | Queue queue = new PriorityQueue<>(new Comparator() { 22 | public int compare(String num1, String num2) { 23 | return (num2 + num1).compareTo(num1 + num2); 24 | } 25 | }); 26 | for (int num : nums) { 27 | queue.offer(num + ""); 28 | } 29 | StringBuilder sb = new StringBuilder(); 30 | while (queue.size() > 0) { 31 | sb.append(queue.poll()); 32 | } 33 | //Need care the special case like [0,0], return 0; 34 | if (sb.toString().charAt(0) == '0') { 35 | return "0"; 36 | } 37 | return sb.toString(); 38 | } 39 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/BestTimetoBuyandSellStock1.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * Best Time to Buy and Sell Stock 5 | * Say you have an array for which the ith element is the price of a given stock on day i. 6 | * If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design 7 | * an algorithm to find the maximum profit. 8 | * Tags: Array Dynamic Programming 9 | * Similar Problems: (M) Maximum Subarray (M) Best Time to Buy and Sell Stock II (H) Best Time to Buy and Sell Stock 10 | * III (H) Best Time to Buy and Sell Stock IV (M) Best Time to Buy and Sell Stock with Cooldown 11 | * O(n) time, O(1) space 12 | * 13 | * @author chenshuna 14 | */ 15 | 16 | class BestTimetoBuyandSellStock_shuna { 17 | 18 | public static int maxProfit(int[] prices) { 19 | if (prices == null || prices.length < 2) { 20 | return 0; 21 | } 22 | int max = 0; 23 | int minPrice = prices[0]; 24 | for (int i = 1; i < prices.length; i++) { 25 | minPrice = Math.min(minPrice, prices[i]); 26 | max = Math.max(max, prices[i] - minPrice); 27 | } 28 | return max; 29 | } 30 | 31 | public static void main(String arg[]) { 32 | int[] prices = {2, 5, 8, 9, 1, 6}; 33 | System.out.print(maxProfit(prices)); 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/MeetingRooms.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils.Interval; 4 | 5 | import java.util.Arrays; 6 | import java.util.Comparator; 7 | 8 | /** 9 | * 251. Meeting Rooms 10 | *

11 | * Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine 12 | * if a person could attend all meetings. 13 | *

14 | * For example, 15 | * Given [[0, 30],[5, 10],[15, 20]], 16 | * return false. 17 | *

18 | * Company Tags: Facebook 19 | * Tags: Sort 20 | * Similar Problems: (H) Merge Intervals, (M) Meeting Rooms II 21 | */ 22 | public class MeetingRooms { 23 | 24 | /** 25 | * Sort. 26 | * The actual problem is detecting whether there is any overlap between meetings. 27 | * Sort the intervals. 28 | * From second interval, check each interval with the previous one. 29 | * If current interval's start < previous interval's end, return false. 30 | */ 31 | public boolean canAttendMeetings(Interval[] intervals) { 32 | Arrays.sort(intervals, Comparator.comparingInt(i -> i.start)); 33 | for (int i = 1; i < intervals.length; i++) { 34 | if (intervals[i].start < intervals[i - 1].end) { 35 | return false; 36 | } 37 | } 38 | return true; 39 | } 40 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/PeekIterator.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * Google: 7 | * Implement peek() for java iterator() 8 | * 9 | * Example [1,2,3,4,5] 10 | * peek() = 1, peek() = 1, next() = 1, peek() = 2, next() = 2, peek() = 3 11 | * hasNext() = true, 12 | * 13 | * Tags: Data Structures 14 | */ 15 | class PeekIterator implements Iterator { 16 | 17 | private final Iterator iterator; 18 | 19 | /** 20 | * Store next item 21 | */ 22 | private T nextItem; 23 | 24 | public PeekIterator(Iterator iterator) { 25 | this.iterator = iterator; 26 | } 27 | 28 | @Override 29 | public boolean hasNext() { 30 | if (nextItem != null) return true; // check next item 31 | if (iterator.hasNext()) nextItem = iterator.next(); // set next item 32 | return nextItem != null; 33 | } 34 | 35 | @Override 36 | public T next() { 37 | if (!hasNext()) throw new NullPointerException(); 38 | T temp = nextItem; 39 | nextItem = null; // reset next 40 | return temp; 41 | } 42 | 43 | public T peek() { 44 | if (!hasNext()) throw new NullPointerException(); 45 | return nextItem; 46 | } 47 | 48 | @Override 49 | public void remove() { 50 | throw new UnsupportedOperationException(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/NonOverlappingIntervalsTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import com.freetymekiyan.algorithms.utils.Utils.Interval; 5 | import org.testng.Assert; 6 | import org.testng.annotations.Test; 7 | 8 | public class NonOverlappingIntervalsTest { 9 | 10 | @Test 11 | public void testEraseOverlapIntervalsExamples() { 12 | NonOverlappingIntervals n = new NonOverlappingIntervals(); 13 | 14 | int[][] input = {{1, 2}, {2, 3}, {3, 4}, {1, 3}}; 15 | Interval[] intervals = Utils.toIntervalArray(input); 16 | int output = 1; 17 | Assert.assertEquals(n.eraseOverlapIntervals(intervals), output); 18 | 19 | input = new int[][]{{1, 2}, {1, 2}, {1, 2}}; 20 | intervals = Utils.toIntervalArray(input); 21 | output = 2; 22 | Assert.assertEquals(n.eraseOverlapIntervals(intervals), output); 23 | 24 | input = new int[][]{{1, 2}, {2, 3}}; 25 | intervals = Utils.toIntervalArray(input); 26 | output = 0; 27 | Assert.assertEquals(n.eraseOverlapIntervals(intervals), output); 28 | 29 | input = new int[][]{{1, 3}, {2, 4}, {2, 3}}; 30 | intervals = Utils.toIntervalArray(input); 31 | output = 2; 32 | Assert.assertEquals(n.eraseOverlapIntervals(intervals), output); 33 | } 34 | 35 | 36 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/ConvertSortedArrToBST.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | /** 4 | * Given an array where elements are sorted in ascending order, convert it to a 5 | * height balanced BST. 6 | *

7 | * Tags: Tree, DFS 8 | */ 9 | class ConvertSortedArrToBST { 10 | 11 | public static void main(String[] args) { 12 | int[] arr = {1, 2, 3, 4, 5}; 13 | TreeNode root = sortedArrayToBST(arr); 14 | System.out.println(root.val); 15 | } 16 | 17 | public static TreeNode sortedArrayToBST(int[] num) { 18 | if (num == null || num.length == 0) return null; 19 | return helper(num, 0, num.length - 1); 20 | } 21 | 22 | /** 23 | * Recursive, DFS 24 | * Divide into left subtree and right subtree with indices range 25 | * Choose mid point as the root of subtree 26 | */ 27 | public static TreeNode helper(int[] num, int left, int right) { 28 | if (left > right) return null; 29 | int mid = left + (right - left) / 2; 30 | TreeNode root = new TreeNode(num[mid]); 31 | root.left = helper(num, left, mid - 1); // left and mid -1 32 | root.right = helper(num, mid + 1, right); // mid + 1 and right 33 | return root; 34 | } 35 | 36 | public static class TreeNode { 37 | int val; 38 | TreeNode left; 39 | TreeNode right; 40 | 41 | TreeNode(int x) { 42 | val = x; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/LineReflection.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * 356. Line Reflection 8 | *

9 | * Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points. 10 | *

11 | * Example 1: 12 | *

13 | * Input: [[1,1],[-1,1]] 14 | * Output: true 15 | * Example 2: 16 | *

17 | * Input: [[1,1],[-1,-1]] 18 | * Output: false 19 | * Follow up: 20 | * Could you do better than O(n^2) ? 21 | *

22 | * Companies: Microsoft, Apple, Google 23 | *

24 | * Related Topics: Hash Table, Math 25 | *

26 | * Similar Questions: (H) Max Points on a Line, (E) Number of Boomerangs 27 | */ 28 | public class LineReflection { 29 | 30 | public boolean isReflected(int[][] points) { 31 | int max = Integer.MIN_VALUE; 32 | int min = Integer.MAX_VALUE; 33 | Set set = new HashSet<>(); 34 | for (int[] p : points) { 35 | max = Math.max(max, p[0]); 36 | min = Math.min(min, p[0]); 37 | String str = p[0] + "a" + p[1]; 38 | set.add(str); 39 | } 40 | int sum = max + min; 41 | for (int[] p : points) { 42 | //int[] arr = {sum-p[0],p[1]}; 43 | String str = (sum - p[0]) + "a" + p[1]; 44 | if (!set.contains(str)) 45 | return false; 46 | 47 | } 48 | return true; 49 | } 50 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/hard/WordLadder2Test.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | import java.util.Arrays; 8 | import java.util.List; 9 | 10 | public class WordLadder2Test { 11 | 12 | @DataProvider(name = "examples") 13 | public Object[][] getExamples() { 14 | return new Object[][]{ 15 | new Object[]{"hit", "cog", Arrays.asList("hot", "dot", "dog", "lot", "log", "cog"), 16 | List.of(List.of("hit", "hot", "dot", "dog", "cog"), List.of("hit", "hot", "lot", "log", "cog"))}, 17 | new Object[]{"a", "c", Arrays.asList("a", "b", "c"), List.of(List.of("a", "c"))}, 18 | new Object[]{"red", "tax", Arrays.asList("ted", "tex", "red", "tax", "tad", "den", "rex", "pee"), 19 | List.of(List.of("red", "ted", "tad", "tax"), List.of("red", "ted", "tex", "tax"), List.of("red", "rex", "tex", "tax"))} 20 | }; 21 | } 22 | 23 | @Test(dataProvider = "examples") 24 | public void testFindLadders(String beginWord, String endWord, List dict, List> expected) { 25 | WordLadder2 w = new WordLadder2(); 26 | List> ladders = w.findLadders(beginWord, endWord, dict); 27 | Assert.assertEquals(ladders, expected); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/easy/FindTheDifference.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | /** 4 | * 389. Find the Difference 5 | *

6 | * Given two strings s and t which consist of only lowercase letters. 7 | *

8 | * String t is generated by random shuffling string s and then add one more letter at a random position. 9 | *

10 | * Find the letter that was added in t. 11 | *

12 | * Example: 13 | *

14 | * Input: 15 | * s = "abcd" 16 | * t = "abcde" 17 | *

18 | * Output: 19 | * e 20 | *

21 | * Explanation: 22 | * 'e' is the letter that was added. 23 | *

24 | * Companies: Google, Adobe 25 | *

26 | * Related Topics: Hash Table, Bit Manipulation 27 | *

28 | * Similar Questions: (E) Single Number 29 | */ 30 | public class FindTheDifference { 31 | 32 | public char findTheDifference(String s, String t) { 33 | int n = t.length(); 34 | char c = t.charAt(n - 1); 35 | for (int i = 0; i < n - 1; ++i) { 36 | c ^= s.charAt(i); 37 | c ^= t.charAt(i); 38 | } 39 | return c; 40 | } 41 | 42 | public char findTheDifference2(String s, String t) { 43 | int charCode = t.charAt(s.length()); 44 | // Iterate through both strings and char codes 45 | for (int i = 0; i < s.length(); ++i) { 46 | charCode -= (int) s.charAt(i); 47 | charCode += (int) t.charAt(i); 48 | } 49 | return (char) charCode; 50 | } 51 | } -------------------------------------------------------------------------------- /src/main/cpp/108_Convert_Sorted_Array_to_Binary_Search_Tree.cpp: -------------------------------------------------------------------------------- 1 | // 108. Convert Sorted Array to Binary Search Tree 2 | /** 3 | * Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 4 | * 5 | * Tags: Tree, Depth-first Search 6 | * 7 | * Similar Problems: (M) Convert Sorted List to Binary Search Tree 8 | * 9 | * Author: Kuang Qin 10 | */ 11 | 12 | #include "stdafx.h" 13 | #include 14 | 15 | using namespace std; 16 | 17 | /** 18 | * Definition for a binary tree node. 19 | */ 20 | struct TreeNode { 21 | int val; 22 | TreeNode *left; 23 | TreeNode *right; 24 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 25 | }; 26 | 27 | class Solution { 28 | TreeNode* dfs(vector& nums, int start, int end) { 29 | if (start > end) 30 | { 31 | return NULL; 32 | } 33 | 34 | int mid = (start + end) / 2; 35 | TreeNode *root = new TreeNode(nums[mid]); 36 | 37 | root->left = dfs(nums, start, mid - 1); 38 | root->right = dfs(nums, mid + 1, end); 39 | 40 | return root; 41 | } 42 | public: 43 | TreeNode* sortedArrayToBST(vector& nums) { 44 | int n = nums.size(); 45 | if (n == 0) 46 | { 47 | return NULL; 48 | } 49 | 50 | return dfs(nums, 0, n - 1); 51 | } 52 | }; 53 | 54 | int _tmain(int argc, _TCHAR* argv[]) 55 | { 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /src/main/cpp/150_Evaluate_Reverse_Polish_Notation.cpp: -------------------------------------------------------------------------------- 1 | //150. Evaluate Reverse Polish Notation 2 | /* 3 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. 4 | 5 | Valid operators are +, -, *, /. Each operand may be an integer or another expression. 6 | 7 | Some examples: 8 | ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 9 | ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 10 | Subscribe to see which companies asked this question 11 | 12 | Tag: Stack 13 | 14 | Author: Xinyu Liu 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | using namespace std; 22 | 23 | class Solution { 24 | public: 25 | int evalRPN(vector& tokens) { 26 | if (tokens.empty()) 27 | return 0; 28 | 29 | string s = tokens.back(); 30 | tokens.pop_back(); 31 | 32 | if (s == "+" || s == "-" || s == "*" || s == "/"){ 33 | int r = evalRPN(tokens); 34 | int l = evalRPN(tokens); 35 | if (s == "+") return l + r; 36 | else if (s == "-") return l - r; 37 | else if (s == "*") return l * r; 38 | else return l / r; 39 | } 40 | 41 | else 42 | return atoi( s.c_str() ); 43 | } 44 | }; 45 | 46 | void main(){ 47 | const char* test[] = {"0","3","/"}; 48 | vector test_s(begin(test), end(test)); 49 | Solution sol; 50 | int result = sol.evalRPN(test_s); 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/hard/FirstMissingPositive.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.hard; 2 | 3 | /** 4 | * Given an unsorted integer array, find the first missing positive integer. 5 | *

6 | * For example, 7 | * Given [1,2,0] return 3, 8 | * and [3,4,-1,1] return 2. 9 | *

10 | * Your algorithm should run in O(n) time and uses constant space. 11 | *

12 | * Tags: Array 13 | */ 14 | class FirstMissingPositive { 15 | public static void main(String[] args) { 16 | int[] A = {1, 2, 0}; 17 | System.out.println(new FirstMissingPositive().firstMissingPositive(A)); 18 | } 19 | 20 | /** 21 | * Position of integer n should be n - 1 if sorted 22 | * Correct form [1, 2, 3, 4, ..., #, n] 23 | * If not in position swap it with nums[nums[p]-1] 24 | */ 25 | public int firstMissingPositive(int[] nums) { 26 | if (nums == null || nums.length == 0) { 27 | return 1; 28 | } 29 | int length = nums.length; 30 | for (int i = 0; i < length; i++) { 31 | int num = nums[i]; 32 | while (nums[i] <= length && nums[i] > 0 && nums[num - 1] != num) { 33 | nums[i] = nums[num - 1]; 34 | nums[num - 1] = num; 35 | num = nums[i]; 36 | } 37 | } 38 | for (int i = 0; i < length; i++) { 39 | if (nums[i] != i + 1) { 40 | return i + 1; 41 | } 42 | } 43 | return length + 1; // Nothing in middle missing, return largest 44 | } 45 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/Astroid01.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * 01*0*, * can be 0 or 1 7 | * Generate all possible outputs 8 | * 9 | * Tags: Backtracking 10 | */ 11 | class Astroid01 { 12 | 13 | public static void main(String[] args) { 14 | Astroid01 a = new Astroid01(); 15 | System.out.println(a.astroid("01*0*")); 16 | } 17 | 18 | public List astroid(String s) { 19 | List res = new ArrayList(); 20 | if (s == null || s.length() == 0) return res; 21 | astroid(s, 0, new StringBuilder(s), res); 22 | return res; 23 | } 24 | 25 | /** 26 | * Backtracking, generate all possible result 27 | * Replace if current char is * 28 | * Otherwise, go to next position 29 | */ 30 | public void astroid(String s, int pos, StringBuilder sb, List res) { 31 | if (pos == sb.length()) { 32 | res.add(sb.toString()); // found a result 33 | return; 34 | } 35 | if (s.charAt(pos) == '*') { 36 | sb.setCharAt(pos, '0'); // replace with 0 37 | astroid(s, pos + 1, sb, res); // recurse 38 | sb.setCharAt(pos, '1'); // replace with 1 39 | astroid(s, pos + 1, sb, res); // recurse 40 | } else { 41 | astroid(s, pos + 1, sb, res); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/IsGraphBipartiteTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class IsGraphBipartiteTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{new int[][]{{1, 3}, {0, 2}, {1, 3}, {0, 2}}, true}, 13 | new Object[]{new int[][]{{1}, {0, 2, 3}, {1}, {1}}, true}, 14 | new Object[]{new int[][]{{1, 2, 3}, {0, 2}, {0, 1, 3}, {0, 2}}, false}, 15 | new Object[]{new int[][]{{}, {2, 4, 6}, {1, 4, 8, 9}, {7, 8}, {1, 2, 8, 9}, {6, 9}, {1, 5, 7, 8, 9}, {3, 6, 9}, {2, 3, 4, 6, 9}, {2, 4, 5, 6, 7, 8}}, false}, 16 | new Object[]{new int[][]{{4}, {}, {4}, {4}, {0, 2, 3}}, true} 17 | 18 | }; 19 | } 20 | 21 | @Test(dataProvider = "examples") 22 | public void testIsBipartite(int[][] graph, boolean expected) { 23 | IsGraphBipartite i = new IsGraphBipartite(); 24 | Assert.assertEquals(i.isBipartite(graph), expected); 25 | } 26 | 27 | @Test(dataProvider = "examples") 28 | public void testIsBipartite2(int[][] graph, boolean expected) { 29 | IsGraphBipartite i = new IsGraphBipartite(); 30 | Assert.assertEquals(i.isBipartite2(graph), expected); 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/cpp/092_Reverse_Linked_List_II.cpp: -------------------------------------------------------------------------------- 1 | //92. Reverse Linked List II 2 | /* 3 | Reverse a linked list from position m to n. Do it in-place and in one-pass. 4 | 5 | For example: 6 | Given 1->2->3->4->5->NULL, m = 2 and n = 4, 7 | 8 | return 1->4->3->2->5->NULL. 9 | 10 | Note: 11 | Given m, n satisfy the following condition: 12 | 1 ≤ m ≤ n ≤ length of list. 13 | 14 | Tag: Linked List 15 | 16 | Author: Xinyu Liu 17 | */ 18 | 19 | #include 20 | using namespace std; 21 | struct ListNode { 22 | int val; 23 | ListNode *next; 24 | ListNode(int x) : val(x), next(NULL) {} 25 | }; 26 | 27 | 28 | 29 | class Solution { 30 | public: 31 | ListNode *reverseBetween(ListNode *head, int m, int n) { 32 | if (m == n) return head; 33 | n -= m; 34 | ListNode dumbnode(0); 35 | dumbnode.next = head; 36 | ListNode* pre = &dumbnode; 37 | while (--m) 38 | pre = pre->next; 39 | ListNode* start = pre->next; 40 | while (n--){ 41 | ListNode* p = start->next; 42 | start->next = p->next; 43 | p->next = pre->next; 44 | pre->next = p; 45 | } 46 | return dumbnode.next; 47 | } 48 | }; 49 | 50 | void main(){ 51 | ListNode n1(1),n2(2),n3(3),n4(4),n5(5); 52 | n1.next = &n2; 53 | n2.next = &n3; 54 | n3.next = &n4; 55 | n4.next = &n5; 56 | Solution sol; 57 | ListNode* head = sol.reverseBetween(&n1, 2, 4); 58 | } 59 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/other/AlmostBalancedTreeTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import com.freetymekiyan.algorithms.utils.Utils.TreeNode; 5 | import org.testng.Assert; 6 | import org.testng.annotations.DataProvider; 7 | import org.testng.annotations.Test; 8 | 9 | public class AlmostBalancedTreeTest { 10 | 11 | @DataProvider(name = "examples") 12 | public Object[][] getExamples() { 13 | return new Object[][]{ 14 | new Object[]{Utils.buildBinaryTree(new Integer[]{1}), true}, 15 | new Object[]{Utils.buildBinaryTree(new Integer[]{1, 2}), true}, 16 | new Object[]{Utils.buildBinaryTree(new Integer[]{1, 2, 3}), true}, 17 | new Object[]{Utils.buildBinaryTree(new Integer[]{1, 2, null, 3, null, null, null, 4}), true}, 18 | new Object[]{Utils.buildBinaryTree(new Integer[]{1, null, 2, null, null, null, 3, null, null, null, null, null, null, 4}), true}, 19 | new Object[]{Utils.buildBinaryTree(new Integer[]{1, 2, 3, 4, null, null, null, 5, null, null, null, null, null, null, 6}), false} 20 | }; 21 | } 22 | 23 | @Test(dataProvider = "examples") 24 | public void testIsAlmostBalanced(TreeNode root, boolean expected) { 25 | AlmostBalancedTree a = new AlmostBalancedTree(); 26 | Assert.assertEquals(a.isAlmostBalanced(root), expected); 27 | } 28 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/other/LCAOfDeepestLeavesTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import com.freetymekiyan.algorithms.utils.Utils.GTNode; 5 | import org.testng.Assert; 6 | import org.testng.annotations.DataProvider; 7 | import org.testng.annotations.Test; 8 | 9 | import java.util.List; 10 | 11 | public class LCAOfDeepestLeavesTest { 12 | 13 | @DataProvider(name = "examples") 14 | public Object[][] getExamples() { 15 | return new Object[][]{ 16 | new Object[]{Utils.buildTree(List.of(List.of(new int[]{1, 0}))), 1}, 17 | new Object[]{Utils.buildTree(List.of(List.of(new int[]{1, 1}), List.of(new int[]{2, 0}))), 2}, 18 | new Object[]{Utils.buildTree(List.of(List.of(new int[]{1, 2}), List.of(new int[]{2, 0}, new int[]{3, 0}))), 1}, 19 | new Object[]{Utils.buildTree(List.of(List.of(new int[]{1, 3}), List.of(new int[]{2, 0}, new int[]{3, 0}, new int[]{4, 0}))), 1}, 20 | new Object[]{Utils.buildTree(List.of(List.of(new int[]{1, 3}), List.of(new int[]{2, 1}, new int[]{3, 0}, new int[]{4, 0}), List.of(new int[]{5, 0}))), 5} 21 | }; 22 | } 23 | 24 | @Test(dataProvider = "examples") 25 | public void testFindLca(GTNode root, int expected) { 26 | LCAOfDeepestLeaves l = new LCAOfDeepestLeaves(); 27 | Assert.assertEquals(l.findLca(root).val, expected); 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/Fib.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Fibonnaci Number 5 | * 6 | * Tags: Math, Recursion, DP 7 | */ 8 | class Fib { 9 | public static void main(String[] args) { 10 | Fib f = new Fib(); 11 | for (int n = 0; n <= 10; n++) { 12 | System.out.println(f.fib(n, new int[n+1])); 13 | System.out.println(f.fib2(n)); 14 | System.out.println(f.fib3(n)); 15 | System.out.println("--------"); 16 | } 17 | } 18 | 19 | /** 20 | * DP, top-down approach 21 | */ 22 | public int fib(int n, int[] res) { 23 | if (n == 0) return 0; 24 | if (n == 1) return 1; 25 | if (res[n] == 0) res[n] = fib(n - 1, res) + fib(n - 2, res); 26 | return res[n]; 27 | } 28 | 29 | /** 30 | * DP, bottom-up approach 31 | */ 32 | public int fib2(int n) { 33 | if (n == 0) return 0; 34 | if (n == 1) return 1; 35 | int prev = 0; 36 | int res = 1; 37 | for (int i = 2; i <= n; i++) { 38 | int temp = res; 39 | res += prev; 40 | prev = temp; 41 | } 42 | return res; 43 | } 44 | 45 | /** 46 | * Recursion 47 | */ 48 | public int fib3(int n) { 49 | if (n == 0) return 0; 50 | if (n == 1) return 1; 51 | return fib3(n - 1) + fib3(n - 2); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/easy/ValidPalindrome2Test.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.easy; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | import static org.testng.Assert.assertFalse; 8 | import static org.testng.Assert.assertTrue; 9 | 10 | public class ValidPalindrome2Test { 11 | 12 | @DataProvider(name = "examples") 13 | public Object[][] getExamples() { 14 | return new Object[][]{ 15 | new Object[]{"aba", true}, 16 | new Object[]{"abca", true}, 17 | new Object[]{"acac", true}, 18 | new Object[]{"aacc", false}, 19 | new Object[]{"a", true}, 20 | new Object[]{"ab", true}, 21 | new Object[]{"abc", false} 22 | }; 23 | } 24 | 25 | @Test(dataProvider = "examples") 26 | public void testValidPalindromeExamples(String s, boolean expected) { 27 | ValidPalindrome2 v = new ValidPalindrome2(); 28 | Assert.assertEquals(v.validPalindrome(s), expected); 29 | } 30 | 31 | @Test 32 | public void testNullString() { 33 | ValidPalindrome2 v = new ValidPalindrome2(); 34 | assertFalse(v.validPalindrome(null)); 35 | } 36 | 37 | @Test 38 | public void testEmptyString() { 39 | ValidPalindrome2 v = new ValidPalindrome2(); 40 | assertTrue(v.validPalindrome("")); 41 | } 42 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/NumberOfIslandsTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.testng.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class NumberOfIslandsTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{buildGrid(new String[]{"11110", "11010", "11000", "00000"}), 1}, 13 | new Object[]{buildGrid(new String[]{"11000", "11000", "00100", "00011"}), 3}, 14 | }; 15 | } 16 | 17 | @Test(dataProvider = "examples") 18 | public void testNumIslands(char[][] grid, int output) { 19 | NumberOfIslands n = new NumberOfIslands(); 20 | Assert.assertEquals(n.numIslands(grid), output); 21 | } 22 | 23 | @Test(dataProvider = "examples") 24 | public void testNumIslandsUnionFind(char[][] grid, int output) { 25 | NumberOfIslands n = new NumberOfIslands(); 26 | Assert.assertEquals(n.numIslandsUnionFind(grid), output); 27 | } 28 | 29 | private char[][] buildGrid(String[] val) { 30 | char[][] grid = new char[val.length][val[0].length()]; 31 | for (int i = 0; i < val.length; i++) { 32 | for (int j = 0; j < val[i].length(); j++) { 33 | grid[i][j] = val[i].charAt(j); 34 | } 35 | } 36 | return grid; 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/RestoreIpAddresses.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 93. Restore IP Addresses 8 | *

9 | * Given a string containing only digits, restore it by returning all possible valid IP address combinations. 10 | *

11 | * Example: 12 | *

13 | * Input: "25525511135" 14 | * Output: ["255.255.11.135", "255.255.111.35"] 15 | *

16 | * Related Topics: String, Backtracking 17 | * Similar Questions: IP to CIDR 18 | */ 19 | public class RestoreIpAddresses { 20 | 21 | public List restoreIpAddresses(String s) { 22 | List res = new ArrayList<>(); 23 | if (s.length() > 12) return res; 24 | backtrack(s, 3, res, ""); 25 | return res; 26 | } 27 | 28 | public void backtrack(String s, int dot, List res, String ip) { 29 | if (dot == 0) { 30 | if (isValid(s)) { 31 | ip += s; 32 | System.out.println(ip); 33 | res.add(ip); 34 | } 35 | return; 36 | } 37 | 38 | for (int i = 1; i < 4 && i < s.length(); i++) { 39 | String pre = s.substring(0, i); 40 | if (!isValid(pre)) continue; 41 | backtrack(s.substring(i), dot - 1, res, ip + pre + "."); 42 | } 43 | } 44 | 45 | public boolean isValid(String s) { 46 | if (s.startsWith("0") && s.length() > 1 || Integer.valueOf(s) > 255) return false; 47 | return true; 48 | } 49 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/other/LowestCommonAncestor.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.other; 2 | 3 | /** 4 | * Given a binary tree (not a binary search tree) and two values say n1 and n2, 5 | * write a program to find the least common ancestor. 6 | * Allow a node to be a descendant of itself 7 | * 8 | * Tags: Tree 9 | */ 10 | class LowestCommonAncestor { 11 | public static void main(String[] args) { 12 | 13 | } 14 | 15 | /** 16 | * If root is null, just return null 17 | * If root's value matches with n1 or n2, return root 18 | * If not, find lca recursively in both left and right subtrees 19 | * If both are not null, one value in left and the other in right, 20 | * return root 21 | * If one is not null, return that one 22 | */ 23 | public Node findLca(Node root, int n1, int n2) { 24 | if (root == null) return null; 25 | if (root.val == n1 || root.val == n2) return root; 26 | 27 | Node leftLca = findLca(root.left, n1, n2); 28 | Node rightLca = findLca(root.right, n1, n2); 29 | if (leftLca != null && rightLca != null) return root; 30 | return leftLca != null ? leftLca : rightLca; 31 | } 32 | 33 | class Node { 34 | int val; 35 | Node left; 36 | Node right; 37 | 38 | public Node() {} 39 | 40 | public Node(int v) { 41 | val = v; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/FindRightIntervalTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils; 4 | import com.freetymekiyan.algorithms.utils.Utils.Interval; 5 | import org.testng.Assert; 6 | import org.testng.annotations.DataProvider; 7 | import org.testng.annotations.Test; 8 | 9 | import java.util.Arrays; 10 | 11 | public class FindRightIntervalTest { 12 | 13 | @DataProvider(name = "examples") 14 | public Object[][] createExamples() { 15 | return new Object[][]{ 16 | new Object[]{Utils.toIntervalArray(new int[][]{{1, 2}}), new int[]{-1}}, 17 | new Object[]{Utils.toIntervalArray(new int[][]{{3, 4}, {2, 3}, {1, 2}}), new int[]{-1, 0, 1}}, 18 | new Object[]{Utils.toIntervalArray(new int[][]{{1, 4}, {2, 3}, {3, 4}}), new int[]{-1, 2, -1}} 19 | }; 20 | } 21 | 22 | @Test(dataProvider = "examples") 23 | public void testFindRightIntervalExamples(Interval[] intervals, int[] output) { 24 | FindRightInterval f = new FindRightInterval(); 25 | Assert.assertTrue(Arrays.equals(f.findRightInterval(intervals), output)); 26 | } 27 | 28 | @Test(dataProvider = "examples") 29 | public void testFindRightInterval2Examples(Interval[] intervals, int[] output) { 30 | FindRightInterval f = new FindRightInterval(); 31 | Assert.assertTrue(Arrays.equals(f.findRightInterval2(intervals), output)); 32 | } 33 | } -------------------------------------------------------------------------------- /src/test/java/com/freetymekiyan/algorithms/level/medium/PermutationInStringTest.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import org.junit.Assert; 4 | import org.testng.annotations.DataProvider; 5 | import org.testng.annotations.Test; 6 | 7 | public class PermutationInStringTest { 8 | 9 | @DataProvider(name = "examples") 10 | public Object[][] getExamples() { 11 | return new Object[][]{ 12 | new Object[]{"ab", "eidbaooo", true}, 13 | new Object[]{"ab", "eidboaoo", false}, 14 | new Object[]{"hello", "ooolleoooleh", false}, 15 | new Object[]{"adc", "dcda", true} 16 | }; 17 | } 18 | 19 | @Test(dataProvider = "examples") 20 | public void testCheckInclusion(String s1, String s2, boolean expected) { 21 | PermutationInString p = new PermutationInString(); 22 | Assert.assertEquals(p.checkInclusion(s1, s2), expected); 23 | } 24 | 25 | @Test(dataProvider = "examples") 26 | public void testCheckInclusion2(String s1, String s2, boolean expected) { 27 | PermutationInString p = new PermutationInString(); 28 | Assert.assertEquals(p.checkInclusion2(s1, s2), expected); 29 | } 30 | 31 | @Test(dataProvider = "examples") 32 | public void testCheckInclusion3(String s1, String s2, boolean expected) { 33 | PermutationInString p = new PermutationInString(); 34 | Assert.assertEquals(p.checkInclusion3(s1, s2), expected); 35 | } 36 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/ReorderList.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils.ListNode; 4 | 5 | /** 6 | * 143. Reorder List 7 | *

8 | * Given a singly linked list L: L0→L1→…→Ln-1→Ln, 9 | * reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… 10 | *

11 | * You may not modify the values in the list's nodes, only nodes itself may be changed. 12 | *

13 | * Example 1: 14 | *

15 | * Given 1->2->3->4, reorder it to 1->4->2->3. 16 | * Example 2: 17 | *

18 | * Given 1->2->3->4->5, reorder it to 1->5->2->4->3. 19 | *

20 | * Related Topics: Linked List 21 | */ 22 | public class ReorderList { 23 | 24 | public void reorderList(ListNode head) { 25 | if (head == null) return; 26 | if (head.next == null) return; 27 | 28 | ListNode mid = head; 29 | ListNode tail = head; 30 | while (tail != null && tail.next != null) { 31 | mid = mid.next; 32 | tail = tail.next.next; 33 | } 34 | ListNode cur = mid.next; 35 | mid.next = null; 36 | while (cur != null) { 37 | ListNode temp = cur.next; 38 | cur.next = mid.next; 39 | mid.next = cur; 40 | cur = temp; 41 | } 42 | ListNode left = head; 43 | ListNode right = mid.next; 44 | while (right != null) { 45 | mid.next = right.next; 46 | right.next = left.next; 47 | left.next = right; 48 | left = right.next; 49 | right = mid.next; 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /src/main/java/com/freetymekiyan/algorithms/level/medium/SumRootToLeafNumbers.java: -------------------------------------------------------------------------------- 1 | package com.freetymekiyan.algorithms.level.medium; 2 | 3 | import com.freetymekiyan.algorithms.utils.Utils.TreeNode; 4 | 5 | /** 6 | * Given a binary tree containing digits from 0-9 only, each root-to-leaf path 7 | * could represent a number. 8 | *

9 | * An example is the root-to-leaf path 1->2->3 which represents the number 123. 10 | *

11 | * Find the total sum of all root-to-leaf numbers. 12 | *

13 | * For example, 14 | * 1 15 | * / \ 16 | * 2 3 17 | * The root-to-leaf path 1->2 represents the number 12. 18 | * The root-to-leaf path 1->3 represents the number 13. 19 | * Return the sum = 12 + 13 = 25. 20 | *

21 | * Tags: Tree, DFS 22 | */ 23 | class SumRootToLeafNumbers { 24 | 25 | public int sumNumbers(TreeNode root) { 26 | int res = 0; 27 | if (root == null) return res; 28 | return helper(root, 0); 29 | } 30 | 31 | /** 32 | * Recursive, DFS 33 | * Build a helper function to pass cur result 34 | * If its leaf node, just return the val 35 | * Otherwise, goes to left root first then right root with current value 36 | */ 37 | public int helper(TreeNode root, int x) { 38 | if (root.right == null && root.left == null) return 10 * x + root.val; 39 | 40 | int val = 0; 41 | if (root.left != null) val += helper(root.left, 10 * x + root.val); 42 | if (root.right != null) val += helper(root.right, 10 * x + root.val); 43 | return val; 44 | } 45 | } 46 | --------------------------------------------------------------------------------