├── .gitignore ├── cpp ├── Makefile ├── GrayCode.cpp ├── OnesInBinary.cpp ├── Fibonacci.cpp ├── ClockAngle.cpp ├── FizzBuzz.cpp ├── ConsecutiveArray.cpp ├── PrintReversedList.cpp ├── SwapVariables.cpp ├── IntToRoman.cpp ├── ReverseStack.cpp ├── FindDuplicates.cpp ├── autocomplete.cpp ├── LinkedListCycle.cpp ├── AutocompleteModern.cpp └── TwoMissing.cpp ├── python ├── RotateBits.py ├── Sum.py ├── OnesInBinary.py ├── Fibonacci.py ├── GrayCode.py ├── StringDeletion.py ├── BigIntMod.py ├── LineIntersection.py ├── ClockAngle.py ├── ReverseStack.py ├── InorderTraversal.py ├── FizzBuzz.py ├── Anagrams.py ├── SwapVariables.py ├── StringCompression.py ├── ConsecutiveArray.py ├── IntToRoman.py ├── TreeLevelOrder.py ├── PrintReverseList.py ├── MaxStack.py ├── MatrixProduct.py ├── BuildOrder.py ├── FindDuplicates.py ├── DedupLinkedList.py ├── RandomLinkedList.py ├── TwoMissingNumbers.py ├── ZeroMatrix.py ├── SmallestChange.py ├── LinkedListCycle.py ├── NthToLast.py ├── SquareSubmatrix.py └── Knapsack.py ├── java ├── RotateBits.java ├── Sum.java ├── GrayCode.java ├── OnesInBinary.java ├── Fibonacci.java ├── FizzBuzz.java ├── ClockAngle.java ├── StringCompression.java ├── TreeLevelOrder.java ├── BigIntMod.java ├── LineIntersection.java ├── Anagrams.java ├── StringDeletion.java ├── SwapVariables.java ├── ConsecutiveArray.java ├── IntToRoman.java ├── NthToLast.java ├── ReverseStack.java ├── PrintReversedList.java ├── MaxStack.java ├── InorderTraversal.java ├── SmallestChange.java ├── MatrixProduct.java ├── LinkedListCycle.java ├── FindDuplicates.java ├── DedupLinkedList.java ├── BuildOrder.java ├── RandomTree.java ├── PriorityQueue.java ├── Autocomplete.java ├── ShortestPath.java ├── TwoMissingNumbers.java ├── Knapsack.java ├── ZeroMatrix.java ├── RandomLinkedList.java └── SquareSubmatrix.java ├── php └── IntToRoman.php └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.class 3 | *~ 4 | -------------------------------------------------------------------------------- /cpp/Makefile: -------------------------------------------------------------------------------- 1 | CC= g++ 2 | 3 | CPP11_PROGRAMS= AutocompleteModern \ 4 | IntToRoman \ 5 | LinkedListCycle \ 6 | autocomplete 7 | 8 | PROGRAMS= ClockAngle \ 9 | ConsecutiveArray \ 10 | Fibonacci \ 11 | FindDuplicates \ 12 | FizzBuzz \ 13 | GrayCode \ 14 | OnesInBinary \ 15 | PrintReversedList \ 16 | ReverseStack \ 17 | SwapVariables \ 18 | TwoMissing 19 | 20 | all: $(CPP11_PROGRAMS) $(PROGRAMS) 21 | 22 | $(CPP11_PROGRAMS): 23 | $(CC) -std=c++11 $@.cpp -o $@ 24 | 25 | $(PROGRAMS): 26 | $(CC) $@.cpp -o $@ 27 | 28 | clean: 29 | rm -v $(CPP11_PROGRAMS) $(PROGRAMS) 30 | 31 | -------------------------------------------------------------------------------- /python/RotateBits.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Rotate bits. 3 | 4 | Given a number, write a function to rotate the bits (ie circular shift). 5 | 6 | Execution: python RotateBits.py 7 | 8 | For more details, check out http://www.byte-by-byte.com/rotatebits 9 | 10 | """ 11 | import unittest 12 | 13 | BITS_IN_INTEGER = 32 14 | 15 | 16 | def rotate(n, d): 17 | return (n >> d) | (n << (BITS_IN_INTEGER - d)) & 0xFFFFFFFF 18 | 19 | 20 | class TestRotateBits(unittest.TestCase): 21 | def test_1(self): 22 | self.assertEqual(rotate(0xFFFF0000, 8), 0x00FFFF00) 23 | 24 | def test_2(self): 25 | self.assertEqual(rotate(0x13579BDF, 12), 0xBDF13579) 26 | 27 | 28 | if __name__ == '__main__': 29 | unittest.main() 30 | -------------------------------------------------------------------------------- /java/RotateBits.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Rotate bits 3 | * 4 | * Given a number, write a function to rotate the bits (ie circular shift). 5 | * 6 | * Execution: javac RotateBits.java && java RotateBits 7 | * 8 | * For more details, check out http://www.byte-by-byte.com/rotatebits/ 9 | */ 10 | 11 | 12 | 13 | public class RotateBits { 14 | private static final int BITS_IN_INTEGER = 32; 15 | public static int rotate(int x, int N) { 16 | N = N % BITS_IN_INTEGER; 17 | return (x >> N | x << (BITS_IN_INTEGER - N)); 18 | } 19 | 20 | public static void main(String[] args) { 21 | assert rotate(0xFFFF0000, 8) == 0x00FFFF00; 22 | assert rotate(0x13579BDF, 12) == 0xBDF13579; 23 | assert rotate(0b10110011100011110000111110000000, 17) == 0b00011111000000010110011100011110; 24 | 25 | System.out.println("Passed all test cases"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /java/Sum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Sum 3 | * 4 | * Given two integers, write a function to sum the numbers without using any arithmetic operators. 5 | * 6 | * Execution: javac Sum.java && java Sum 7 | 8 | * For more details, check out http://www.byte-by-byte.com/sum 9 | */ 10 | 11 | public class Sum { 12 | public static int sum(int a, int b) { 13 | if (b == 0){ 14 | return a; 15 | } 16 | int partialSum = a ^ b; 17 | int carry = (a & b) << 1; 18 | return sum(partialSum, carry); 19 | } 20 | 21 | // Sample test cases 22 | public static void main(String[] args) { 23 | assert sum(1, 1) == 2: 24 | "1 + 1 = 2"; 25 | 26 | assert sum(5, 10) == 15: 27 | "10 + 5 = 15"; 28 | 29 | assert sum(100, 200) == 300: 30 | "100 + 200 = 300"; 31 | 32 | assert sum(3, 2) == 5: 33 | "3 + 2 = 5"; 34 | 35 | System.out.println("Passed all test cases"); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /cpp/GrayCode.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Gray Code 3 | * 4 | * Execution: g++ GrayCode.cpp -o GrayCode 5 | * 6 | * For more details, check out http://www.byte-by-byte.com/graycode/ 7 | */ 8 | 9 | #include 10 | 11 | using namespace std; 12 | 13 | bool gray_1(int a, int b) { 14 | int x = a ^ b; 15 | while (x > 0) { 16 | if (x % 2 == 1 && x >> 1 > 0) { 17 | return false; 18 | } 19 | x = x >> 1; 20 | } 21 | return true; 22 | } 23 | 24 | bool gray_2(int a, int b) { 25 | int x = a ^ b; 26 | return (x & (x-1)) == 0; 27 | } 28 | 29 | int main() { 30 | assert(gray_1(0, 1) == true); 31 | cout << "Passed: gray_1(0, 1) == true" << endl; 32 | 33 | assert(gray_1(1, 2) == false); 34 | cout << "Passed: gray_1(1, 2) == false" << endl; 35 | 36 | assert(gray_2(0, 1) == true); 37 | cout << "Passed: gray_2(0, 1) == true" << endl; 38 | 39 | assert(gray_2(1, 2) == false); 40 | cout << "Passed: gray_2(1, 2) == false" << endl; 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /python/Sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Sum problem 3 | 4 | Given two integers, write a function to sum the numbers without using any arithmetic operators. 5 | 6 | Execution: python Sum.py 7 | 8 | For more details, check out http://www.byte-by-byte.com/sum/ 9 | 10 | """ 11 | import unittest 12 | 13 | 14 | def sum_func(a: int, b: int): 15 | if b == 0: 16 | return a 17 | partial_sum = a ^ b 18 | carry = (a & b) << 1 19 | return sum_func(partial_sum, carry) 20 | 21 | 22 | class TestSum(unittest.TestCase): 23 | def test_1_1_2(self): 24 | self.assertEqual(sum_func(1, 1), 2) 25 | print("1 + 1 = 2") 26 | 27 | def test_10_5_15(self): 28 | self.assertEqual(sum_func(10, 5), 15) 29 | print("10 + 5 = 15") 30 | 31 | def test_100_200_300(self): 32 | self.assertEqual(sum_func(100, 200), 300) 33 | print("100 + 200 = 300") 34 | 35 | def test_3_2_5(self): 36 | self.assertEqual(sum_func(3, 2), 5) 37 | print("3 + 2 = 5") 38 | 39 | 40 | if __name__ == '__main__': 41 | unittest.main() 42 | -------------------------------------------------------------------------------- /cpp/OnesInBinary.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Number of ones in binary representation. 3 | * 4 | * Given an integer, write a function to compute the number of ones in 5 | * the binary representation of the number. 6 | * 7 | * Execution: g++ OnesInBinary.cpp -o OnesInBinary 8 | * 9 | * For more details, check out http://www.byte-by-byte.com/onesinbinary 10 | */ 11 | #include 12 | 13 | using namespace std; 14 | 15 | int onesInBinary(int x) { 16 | int sum = 0; 17 | while (x > 0) { 18 | sum += x & 1; 19 | x >>= 1; 20 | } 21 | return sum; 22 | } 23 | 24 | int main() { 25 | assert(onesInBinary(5) == 2); 26 | cout << "Binary representation of 5 has 2 ones" << endl; 27 | 28 | assert(onesInBinary(12) == 2); 29 | cout << "Binary representation of 12 has 2 ones" << endl; 30 | 31 | assert(onesInBinary(255) == 8); 32 | cout << "Binary representation of 255 has 8 ones" << endl; 33 | 34 | assert(onesInBinary(256) == 1); 35 | cout << "Binary representation of 256 has 1 ones" << endl; 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /java/GrayCode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Gray Code 3 | * 4 | * Given two integers, write a function to determine whether or not their 5 | * binary representations differ by a single bit. 6 | * 7 | * Execution: javac GrayCode.java && java GrayCode 8 | * 9 | * For more details, check out http://www.byte-by-byte.com/graycode/ 10 | */ 11 | 12 | public class GrayCode { 13 | 14 | public static boolean gray_1(int a, int b) { 15 | int x = a ^ b; 16 | while (x > 0) { 17 | if (x % 2 == 1 && x >> 1 > 0) { 18 | return false; 19 | } 20 | } 21 | return true; 22 | } 23 | 24 | public static boolean gray_2(int a, int b) { 25 | int x = a ^ b; 26 | return (x & (x - 1)) == 0; 27 | } 28 | 29 | // Sample test cases 30 | public static void main(String[] args) { 31 | assert gray_1(0, 1) == true; 32 | assert gray_1(1, 2) == false; 33 | 34 | assert gray_2(0, 1) == true; 35 | assert gray_2(1, 2) == false; 36 | 37 | System.out.println("Passed all test cases"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /cpp/Fibonacci.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Fibonacci 3 | * 4 | * Execution: g++ Fibonacci.cpp -o Fibonacci 5 | * 6 | * For more details, check out http://www.byte-by-byte.com/fibonacci 7 | */ 8 | 9 | #include 10 | #include 11 | 12 | using namespace std; 13 | 14 | long fibonacci_recur(int x, vector cache) { 15 | if (cache[x] > -1) { 16 | return cache[x]; 17 | } 18 | cache[x] = fibonacci_recur(x-1, cache) + fibonacci_recur(x-2, cache); 19 | return cache[x]; 20 | } 21 | 22 | long fibonacci(int x) { 23 | if (x < 0) { 24 | return -1; 25 | } 26 | if (x == 0) { 27 | return 0; 28 | } 29 | std::vector cache(x+1); 30 | for (int i = 1; i < cache.size(); i++) { 31 | cache[i] = -1; 32 | } 33 | cache[1] = 1; 34 | return fibonacci_recur(x, cache); 35 | } 36 | 37 | int main() { 38 | assert(fibonacci(1) == 1); 39 | cout << "fib(1) = 1" << endl; 40 | 41 | assert(fibonacci(5) == 5); 42 | cout << "fib(5) = 5" << endl; 43 | 44 | assert(fibonacci(10) == 55); 45 | cout << "fib(10) = 55" << endl; 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /java/OnesInBinary.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Number of ones in binary representation. 3 | * 4 | * Given an integer, write a function to compute the number of ones 5 | * in the binary representation of the number. 6 | * 7 | * Execution: javac OnesInBinary.java && java OnesInBinary 8 | 9 | * For more details, check out http://www.byte-by-byte.com/fizzbuzz 10 | */ 11 | 12 | public class OnesInBinary { 13 | public static int onesInBinary(int x) { 14 | int sum = 0; 15 | while (x > 0) { 16 | sum += x & 1; 17 | x >>= 1; 18 | } 19 | return sum; 20 | } 21 | 22 | // Sample test cases 23 | public static void main(String[] args) { 24 | assert onesInBinary(5) == 2: 25 | "Binary representation of 5 has 2 ones."; 26 | assert onesInBinary(12) == 2: 27 | "Binary representation of 12 has 2 ones."; 28 | assert onesInBinary(255) == 8: 29 | "Binary representation of 255 has 8 ones."; 30 | assert onesInBinary(256) == 1: 31 | "Binary representation of 256 has 1 ones."; 32 | 33 | System.out.println("Passed all test cases"); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /python/OnesInBinary.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Number of ones in binary representation. 3 | 4 | Given an integer, write a function to compute the number of ones in 5 | the binary representation of the number. 6 | 7 | Execution: python OnesInBinary.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/onesinbinary 10 | 11 | """ 12 | import unittest 13 | 14 | 15 | def ones_binary(x: int): 16 | sum = 0 17 | while x > 0: 18 | sum += x & 1 19 | x >>= 1 20 | return sum 21 | 22 | 23 | class TestOnesBinary(unittest.TestCase): 24 | def test_5(self): 25 | self.assertEqual(ones_binary(5), 2) 26 | print("Binary representation of 5 has 2 ones.") 27 | 28 | def test_12(self): 29 | self.assertEqual(ones_binary(12), 2) 30 | print("Binary representation of 12has 2 ones.") 31 | 32 | def test_255(self): 33 | self.assertEqual(ones_binary(255), 8) 34 | print("Binary representation of 255 has 8 ones.") 35 | 36 | def test_256(self): 37 | self.assertEqual(ones_binary(256), 1) 38 | print("Binary representation of 256 has 1 ones.") 39 | 40 | 41 | if __name__ == '__main__': 42 | unittest.main() 43 | 44 | -------------------------------------------------------------------------------- /php/IntToRoman.php: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Integer to Roman Numerals 3 | * Date: 29/08/2019 4 | * 5 | * Write a function to convert an integer into its roman numeral representation 6 | * 7 | * Execution: php php\IntToRoman.php 8 | * 9 | * For more details, check out http://www.byte-by-byte.com/inttoroman/ 10 | */ 11 | 12 | 1000, 21 | 'CM' => 900, 22 | 'D' => 500, 23 | 'CD' => 400, 24 | 'C' => 100, 25 | 'XC' => 90, 26 | 'L' => 50, 27 | 'XL' => 40, 28 | 'X' => 10, 29 | 'IX' => 9, 30 | 'V' => 5, 31 | 'IV' => 4, 32 | 'I' => 1, 33 | ); 34 | foreach($lookup as $roman => $value) 35 | { 36 | $matches = intval($integer/$value); 37 | 38 | $result .= str_repeat($roman, $matches); 39 | 40 | $integer = $integer % $value; 41 | } 42 | 43 | return $result; 44 | } 45 | } 46 | 47 | echo IntToRoman::integerToRoman(1)."\n"; 48 | echo IntToRoman::integerToRoman(4)."\n"; 49 | echo IntToRoman::integerToRoman(49)."\n"; 50 | 51 | ?> -------------------------------------------------------------------------------- /python/Fibonacci.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Fibonacci number. 3 | 4 | Given an integer n, write a function to compute the nth Fibonacci number. 5 | 6 | Execution: python Fibonacci.py 7 | 8 | For more details, check out http://www.byte-by-byte.com/fibonacci 9 | 10 | """ 11 | import unittest 12 | 13 | 14 | def fibonacci(x: int): 15 | if x < 0: 16 | return -1 17 | if x == 0: 18 | return 0 19 | cache = [0] * (x + 1) 20 | for i in range(1, len(cache)): 21 | cache[i] = -1 22 | cache[1] = 1 23 | return fibonacci_recur(x, cache) 24 | 25 | 26 | def fibonacci_recur(x: int, cache: list): 27 | if cache[x] > -1: 28 | return cache[x] 29 | cache[x] = fibonacci_recur(x-1, cache) + fibonacci_recur(x-2, cache) 30 | return cache[x] 31 | 32 | 33 | class TestFibonacci(unittest.TestCase): 34 | def test_1(self): 35 | self.assertEqual(fibonacci(1), 1) 36 | print("fib(1) = 1") 37 | 38 | def test_5(self): 39 | self.assertEqual(fibonacci(5), 5) 40 | print("fib(5) = 5") 41 | 42 | def test_10(self): 43 | self.assertEqual(fibonacci(10), 55) 44 | print("fib(10) = 55") 45 | 46 | 47 | if __name__ == '__main__': 48 | unittest.main() 49 | -------------------------------------------------------------------------------- /python/GrayCode.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Gray code 3 | 4 | Given two integers, write a function to determine whether or not their 5 | binary representations differ by a single bit. 6 | 7 | Execution: python GrayCode.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/graycode/ 10 | 11 | """ 12 | import unittest 13 | 14 | 15 | def gray_1(a: int, b: int): 16 | x = a ^ b 17 | while x > 0: 18 | if x % 2 == 1 and x >> 1 > 0: 19 | return False 20 | x = x >> 1 21 | return True 22 | 23 | 24 | def gray_2(a: int, b: int): 25 | x = a ^ b 26 | return (x & (x-1)) == 0 27 | 28 | 29 | class TestGrayCode(unittest.TestCase): 30 | def test_gray_1_1(self): 31 | self.assertEqual(gray_1(0, 1), True) 32 | print("gray_1(0, 1) == True") 33 | 34 | def test_gray_1_2(self): 35 | self.assertEqual(gray_1(1, 2), False) 36 | print("gray_1(1, 2) == False") 37 | 38 | def test_gray_2_1(self): 39 | self.assertEqual(gray_2(0, 1), True) 40 | print("gray_2(0, 1) == True") 41 | 42 | def test_gray_2_2(self): 43 | self.assertEqual(gray_2(1, 2), False) 44 | print("gray_2(1, 2) == False") 45 | 46 | if __name__ == '__main__': 47 | unittest.main() 48 | -------------------------------------------------------------------------------- /cpp/ClockAngle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Clock Angle 3 | * 4 | * Given two integers, write a function that swaps them without using any 5 | * temporary variables. 6 | * 7 | * Execution: g++ ClockAngle.cpp -o ClockAngle 8 | * 9 | * For more details, check out http://www.byte-by-byte.com/clockangle 10 | */ 11 | 12 | #include 13 | #include 14 | 15 | using namespace std; 16 | 17 | 18 | double clockAngle(int hour, int minutes) { 19 | double MINUTES_PER_HOUR = 60; 20 | double DEGREES_PER_MINUTE = 360 / MINUTES_PER_HOUR; 21 | double DEGREES_PER_HOUR = 360 / 12; 22 | 23 | double minuteAngle = minutes * DEGREES_PER_MINUTE; 24 | double hourAngle = hour * DEGREES_PER_HOUR + (minutes / MINUTES_PER_HOUR) * DEGREES_PER_HOUR; 25 | 26 | double diff = std::abs(minuteAngle - hourAngle); 27 | if (diff > 180) { 28 | return 360 - diff; 29 | } 30 | 31 | return diff; 32 | } 33 | 34 | int main() { 35 | assert(clockAngle(3, 40) == 130); 36 | cout << "3:40 is 130 degrees." << endl; 37 | 38 | assert(clockAngle(1, 20) == 80); 39 | cout << "1:20 is 80 degrees." << endl; 40 | 41 | assert(clockAngle(5, 15) == 67.5); 42 | cout << "5:15 is 67.5 degrees." << endl; 43 | 44 | return 0; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /java/Fibonacci.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Fibonacci 3 | * 4 | * Given an integer n, write a function to compute the nth Fibonacci number. 5 | * 6 | * Execution: javac Fibonacci.java && java Fibonacci 7 | * 8 | * For more details, check out http://www.byte-by-byte.com/fibonacci/ 9 | */ 10 | 11 | public class Fibonacci { 12 | public static long fibonacci(int x) { 13 | if (x < 0) { 14 | return -1; 15 | } 16 | if (x == 0) { 17 | return 0; 18 | } 19 | long [] cache = new long[x + 1]; 20 | for (int i = 1; i < cache.length; i++) { 21 | cache[i] = -1; 22 | } 23 | cache[1] = 1; 24 | 25 | return fibonacci(x, cache); 26 | } 27 | public static long fibonacci(int x, long[] cache){ 28 | if (cache[x] > -1) { 29 | return cache[x]; 30 | } 31 | cache[x] = fibonacci(x-1, cache) + fibonacci(x-2, cache); 32 | return cache[x]; 33 | } 34 | 35 | 36 | // Sample test cases 37 | public static void main(String[] args) { 38 | assert fibonacci(1) == 1; 39 | assert fibonacci(5) == 5; 40 | assert fibonacci(10) == 55; 41 | 42 | System.out.println("Passed all test cases"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /python/StringDeletion.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: String deletion 3 | 4 | Given a string and a dictionary HashSet, write a function to determine the 5 | minimum number of characters to delete to make a word. 6 | 7 | Execution: python StringDeletion.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/stringdeletion 10 | """ 11 | from collections import deque 12 | import unittest 13 | 14 | 15 | def delete(query: str, dictionary: list): 16 | queue = deque() 17 | queue_elements = set() 18 | 19 | queue.append(query) 20 | queue_elements.add(query) 21 | 22 | while queue: 23 | s = queue.popleft() 24 | queue_elements.remove(s) 25 | if s in dictionary: 26 | return len(query) - len(s) 27 | for i in range(len(s)): 28 | sub = s[0:i] + s[i+1:len(s)] 29 | if len(sub) > 0 and sub not in queue_elements: 30 | queue.append(sub) 31 | queue_elements.add(sub) 32 | return -1 33 | 34 | 35 | class TestStringDeletion(unittest.TestCase): 36 | def test_I(self): 37 | self.assertEqual(delete("abc", ["a", "aa", "aaa"]), 2) 38 | print("Successfully determines 2 strings.") 39 | 40 | 41 | if __name__ == '__main__': 42 | unittest.main() 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /python/BigIntMod.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Big Int Mod 3 | 4 | Given a list of bytes a, each representing one byte of a larger integer 5 | (ie. {0x12, 0x34, 0x56, 0x78} represents the integer 0x12345678), and an 6 | integer b, find a % b. 7 | 8 | Execution: python BigIntMod.py 9 | 10 | For more details, check out http://www.byte-by-byte.com/bigintmod/ 11 | """ 12 | import unittest 13 | 14 | 15 | def big_int_mod(a: list, b: int): 16 | if a is None: 17 | return 0 18 | m = 0 19 | for i in range(len(a)): 20 | m <<= 8 21 | m += (a[i] & 0xFF) 22 | m %= b 23 | return m 24 | 25 | 26 | class TestBigIntMod(unittest.TestCase): 27 | def test_null_value(self): 28 | self.assertEqual(big_int_mod(None, 1), 0) 29 | print("Null value.") 30 | 31 | def test_empty_array(self): 32 | self.assertEqual(big_int_mod([], 1), 0) 33 | print("Empty array.") 34 | 35 | def test_single_element_array(self): 36 | self.assertEqual(big_int_mod([15], 10), 5) 37 | print("Single element array.") 38 | 39 | def test_multi_element_array(self): 40 | self.assertEqual(big_int_mod([0x03, 0xED], 10), 5) 41 | print("Multi-element array") 42 | 43 | 44 | if __name__ == '__main__': 45 | unittest.main() 46 | 47 | 48 | -------------------------------------------------------------------------------- /python/LineIntersection.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Line intersection 3 | 4 | Given two lines on a Cartesian plane, write a function to determine 5 | whether or not the lines intersect. 6 | 7 | Execution: python LineIntersection.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/lineintersection/ 10 | 11 | """ 12 | import unittest 13 | 14 | class Line: 15 | def __init__(self, slope, y_intercept): 16 | self.epsilon = 0.00001 17 | self.slope = slope 18 | self.y_intercept = y_intercept 19 | 20 | self.line = (self.slope, self.y_intercept) 21 | 22 | def intersect(self, line): 23 | if self.is_equal(line): 24 | return True 25 | if abs(self.slope - line.slope) > self.epsilon: 26 | return True 27 | return False 28 | 29 | def is_equal(self, line): 30 | return abs(self.slope - line.slope) < self.epsilon and \ 31 | abs(self.y_intercept - line.y_intercept) < self.epsilon 32 | 33 | 34 | class TestFibonacci(unittest.TestCase): 35 | def test_1(self): 36 | line_1 = Line(2, 5) 37 | line_2 = Line(3, 10) 38 | self.assertEqual(line_1.intersect(line_2), True) 39 | print("Test 1 succeeded.") 40 | 41 | 42 | if __name__ == '__main__': 43 | unittest.main() 44 | -------------------------------------------------------------------------------- /cpp/FizzBuzz.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: FizzBuzz 3 | * 4 | * Output numbers from 1 to x. If the number is divisible by 3, replace it with 5 | * “Fizz”. If it is divisible by 5, replace it with “Buzz”. If it is divisible 6 | * by 3 and 5 replace it with “FizzBuzz”. 7 | * 8 | * Execution: g++ FizzBuzz.cpp -o FizzBuzz 9 | * 10 | * For more details, check out http://www.byte-by-byte.com/fizzbuzz 11 | */ 12 | 13 | #include 14 | 15 | using namespace std; 16 | 17 | std::string fizzBuzz(int i) { 18 | if (i % 3 == 0 && i % 5 == 0) { 19 | return "FizzBuzz"; 20 | } else if (i % 3 == 0) { 21 | return "Fizz"; 22 | } else if (i % 5 == 0) { 23 | return "Buzz"; 24 | } else { 25 | return std::to_string(i); 26 | } 27 | } 28 | 29 | int main() { 30 | assert(fizzBuzz(1) == "1"); 31 | cout << "1 produces 1." << endl; 32 | 33 | assert(fizzBuzz(2) == "2"); 34 | cout << "2 produces 2." << endl; 35 | 36 | assert(fizzBuzz(3) == "Fizz"); 37 | cout << "3 produces Fizz" << endl; 38 | 39 | assert(fizzBuzz(5) == "Buzz"); 40 | cout << "5 produces Buzz" << endl; 41 | 42 | assert(fizzBuzz(9) == "Fizz"); 43 | cout << "9 produces Fizz" << endl; 44 | 45 | assert(fizzBuzz(15) == "FizzBuzz"); 46 | cout << "15 produces FizzBuzz" << endl; 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /python/ClockAngle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Clock Angle 3 | 4 | Given two integers, an hour and a minute, write a function to 5 | calculate the angle between the two hands on a clock representing 6 | that time. 7 | 8 | Execution: python ClockAngle.py 9 | 10 | For more details, check out http://www.byte-by-byte.com/clockangle 11 | """ 12 | import unittest 13 | 14 | 15 | def clock_angle(hour: int, minutes: int): 16 | MINUTES_PER_HOUR = 60 17 | DEGREES_PER_MINUTE = 360 / MINUTES_PER_HOUR 18 | DEGREES_PER_HOUR = 360 / 12 19 | 20 | minute_angle = minutes * DEGREES_PER_MINUTE 21 | hour_angle = hour * DEGREES_PER_HOUR + (minutes / MINUTES_PER_HOUR) * DEGREES_PER_HOUR 22 | 23 | diff = abs(minute_angle - hour_angle) 24 | 25 | if diff > 180: 26 | return 360 - diff 27 | 28 | return diff 29 | 30 | 31 | class TestClockAngle(unittest.TestCase): 32 | def test_340(self): 33 | self.assertEqual(clock_angle(3, 40), 130) 34 | print("3:40 is 130 degrees.") 35 | 36 | def test_120(self): 37 | self.assertEqual(clock_angle(1, 20), 80) 38 | print("1:20 is 80 degrees.") 39 | 40 | def test_515(self): 41 | self.assertEqual(clock_angle(5, 15), 67.5) 42 | print("5:15 is 67.5 degrees.") 43 | 44 | 45 | if __name__ == '__main__': 46 | unittest.main() 47 | -------------------------------------------------------------------------------- /python/ReverseStack.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Reverse Stack 3 | 4 | Given a stack, reverse the items without creating any additional data structures. 5 | 6 | Execution: python ReverseStack.py 7 | 8 | For more details, check out http://www.byte-by-byte.com/reversestack/ 9 | """ 10 | import unittest 11 | 12 | 13 | def reverse(stack): 14 | if stack == []: 15 | return stack 16 | tmp = stack.pop() 17 | reverse(stack) 18 | insert_at_bottom(stack, tmp) 19 | return stack 20 | 21 | 22 | def insert_at_bottom(stack, x): 23 | if stack == []: 24 | stack.append(x) 25 | return 26 | tmp = stack.pop() 27 | insert_at_bottom(stack, x) 28 | stack.append(tmp) 29 | 30 | 31 | class TestReverseStack(unittest.TestCase): 32 | def test_1(self): 33 | stack = [1, 2, 3] 34 | self.assertEqual(reverse(stack), [3, 2, 1]) 35 | print("reverse(1->2->3) = 3->2->1") 36 | 37 | def test_2(self): 38 | stack = [5, 6, 10, 11, 60, 50] 39 | self.assertEqual(reverse(stack), [50, 60, 11, 10, 6, 5]) 40 | print("reverse(5->6->10->11->60->50) = 50->60->11->10->6->5") 41 | 42 | def test_3(self): 43 | stack = [3, 2, 1] 44 | self.assertEqual(reverse(stack), [1, 2, 3]) 45 | print("reverse(3->2->1) = 1->2->3") 46 | 47 | 48 | if __name__ == '__main__': 49 | unittest.main() 50 | -------------------------------------------------------------------------------- /java/FizzBuzz.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: FizzBuzz 3 | * 4 | * Output numbers from 1 to x. If the number is divisible by 3, replace it with 5 | * “Fizz”. If it is divisible by 5, replace it with “Buzz”. If it is divisible 6 | * by 3 and 5 replace it with “FizzBuzz”. 7 | 8 | * Execution: javac FizzBuzz.java && java FizzBuzz 9 | 10 | * For more details, check out http://www.byte-by-byte.com/fizzbuzz 11 | */ 12 | 13 | public class FizzBuzz { 14 | public static String fizzBuzz(int i) { 15 | if (i % 3 == 0 && i % 5 == 0) { 16 | return "FizzBuzz"; 17 | } else if (i % 3 == 0) { 18 | return "Fizz"; 19 | } else if (i % 5 == 0) { 20 | return "Buzz"; 21 | } else { 22 | return Integer.toString(i); 23 | } 24 | } 25 | 26 | // Sample test cases 27 | public static void main(String[] args) { 28 | assert fizzBuzz(1) == "1": 29 | "1 produces 1."; 30 | assert fizzBuzz(2) == "2": 31 | "2 produces 2."; 32 | assert fizzBuzz(3) == "Fizz": 33 | "3 produces Fizz."; 34 | assert fizzBuzz(5) == "Buzz": 35 | "5 produces Buzz"; 36 | assert fizzBuzz(9) == "Fizz": 37 | "9 produces Fizz"; 38 | assert fizzBuzz(15) == "FizzBuzz": 39 | "15 produces FizzBuzz"; 40 | 41 | System.out.println("Passed all test cases"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /java/ClockAngle.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Clock Angle 3 | * 4 | * Given two integers, an hour and a minute, write a function to 5 | * calculate the angle between the two hands on a clock representing 6 | * that time. 7 | * 8 | * Execution: javac ClockAngle.java && java ClockAngle 9 | 10 | * For more details, check out http://www.byte-by-byte.com/clockangle 11 | */ 12 | 13 | public class ClockAngle { 14 | public static double clockAngle(int hour, int minutes) { 15 | final double MINUTES_PER_HOUR = 60; 16 | final double DEGREES_PER_MINUTE = 360 / MINUTES_PER_HOUR; 17 | final double DEGREES_PER_HOUR = 360 / 12; 18 | 19 | double minuteAngle = minutes * DEGREES_PER_MINUTE; 20 | double hourAngle = hour * DEGREES_PER_HOUR + (minutes / MINUTES_PER_HOUR) * DEGREES_PER_HOUR; 21 | 22 | double diff = Math.abs(minuteAngle - hourAngle); 23 | if (diff > 180) { 24 | return 360 - diff; 25 | } 26 | return diff; 27 | } 28 | 29 | // Sample test cases 30 | public static void main(String[] args) { 31 | 32 | assert clockAngle(3, 40) == 130: 33 | "3:40 is 130 degrees"; 34 | 35 | assert clockAngle(1, 20) == 80: 36 | "1:20 is 80 degrees"; 37 | 38 | assert clockAngle(5, 15) == 67.5: 39 | "5:15 is 67.5 degrees"; 40 | 41 | System.out.println("Passed all test cases"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /java/StringCompression.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: String compression 3 | * 4 | * Given a string, write a function to compress it by shortening every 5 | * sequence of the same character to that character followed by the number 6 | * of repetitions. If the compressed string is longer than the original, 7 | * you should return the original string. 8 | * 9 | * Execution: javac StringCompression.java && java StringCompression 10 | * 11 | * For more details, check out http://www.byte-by-byte.com/stringcompression/ 12 | */ 13 | 14 | public class StringCompression { 15 | public static String compress(String s){ 16 | String out = ""; 17 | int sum = 1; 18 | for (int i = 0; i < s.length() - 1; i++) { 19 | if (s.charAt(i) == s.charAt(i+1)) { 20 | sum++; 21 | } else { 22 | out = out + s.charAt(i) + sum; 23 | sum = 1; 24 | } 25 | } 26 | out = out + s.charAt(s.length() - 1) + sum; 27 | return out.length() < s.length() ? out : s; 28 | } 29 | 30 | 31 | // Sample test cases 32 | public static void main(String[] args) { 33 | assert compress("a") == "a"; 34 | assert compress("aaa") == "a3"; 35 | assert compress("aaabbb") == "a3b3"; 36 | assert compress("aaabccc") == "a3b1c3"; 37 | 38 | System.out.println("Passed all test cases"); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /python/InorderTraversal.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | def __init__(self, value): 3 | self.value = value 4 | self.left = None 5 | self.right = None 6 | 7 | 8 | class BinaryTree(object): 9 | def __init__(self, root): 10 | self.root = Node(root) 11 | self.stack = [] 12 | 13 | def traverse(self, node): 14 | curr = node 15 | 16 | while True: 17 | 18 | if curr: 19 | self.stack.append(curr) 20 | curr = curr.left 21 | elif self.stack: 22 | curr = self.stack.pop() 23 | print(curr.value) 24 | 25 | curr = curr.right 26 | else: 27 | break 28 | 29 | 30 | """ 31 | Sample test case 32 | 33 | 8 34 | / \ 35 | 4 12 36 | / \ / \ 37 | 1 6 9 15 38 | / \ 39 | 5 10 40 | 41 | Should print: 42 | 1 43 | 4 44 | 5 45 | 6 46 | 8 47 | 9 48 | 10 49 | 12 50 | 15 51 | """ 52 | 53 | # Set up tree: 54 | tree = BinaryTree(8) 55 | tree.left = Node(4) 56 | tree.left.left = Node(1) 57 | tree.left.right = Node(6) 58 | tree.left.right.left = Node(5) 59 | tree.right = Node(12) 60 | tree.right.left = Node(9) 61 | tree.right.left.right = Node(10) 62 | tree.right.right = Node(15) 63 | tree.traverse(tree) 64 | 65 | #print(tree.print_tree("preorder")) 66 | #print(tree.print_tree("inorder")) 67 | #print(tree.print_tree("postorder")) 68 | 69 | 70 | -------------------------------------------------------------------------------- /python/FizzBuzz.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: FizzBuzz 3 | 4 | Output numbers from 1 to x. If the number is divisible by 3, replace it with 5 | “Fizz”. If it is divisible by 5, replace it with “Buzz”. If it is divisible 6 | by 3 and 5 replace it with “FizzBuzz”. 7 | 8 | Execution: python FizzBuzz.py 9 | 10 | For more details, check out http://www.byte-by-byte.com/fizzbuzz 11 | """ 12 | import unittest 13 | 14 | 15 | def fizz_buzz(i: int): 16 | if i % 3 == 0 and i % 5 == 0: 17 | return "FizzBuzz" 18 | elif i % 3 == 0: 19 | return "Fizz" 20 | elif i % 5 == 0: 21 | return "Buzz" 22 | else: 23 | return i 24 | 25 | 26 | class TestFizzBuzz(unittest.TestCase): 27 | def test_1(self): 28 | self.assertEqual(fizz_buzz(1), 1) 29 | print("1 produces 1") 30 | 31 | def test_2(self): 32 | self.assertEqual(fizz_buzz(2), 2) 33 | print("2 produces 2") 34 | 35 | def test_fizz_3(self): 36 | self.assertEqual(fizz_buzz(3), "Fizz") 37 | print("3 produces Fizz") 38 | 39 | def test_buzz_5(self): 40 | self.assertEqual(fizz_buzz(5), "Buzz") 41 | print("5 produces Buzz") 42 | 43 | def test_fizz_9(self): 44 | self.assertEqual(fizz_buzz(9), "Fizz") 45 | print("9 produces Fizz") 46 | 47 | def test_fizzbuzz_15(self): 48 | self.assertEqual(fizz_buzz(15), "FizzBuzz") 49 | print("15 produces FizzBuzz") 50 | 51 | 52 | if __name__ == '__main__': 53 | unittest.main() 54 | 55 | -------------------------------------------------------------------------------- /python/Anagrams.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Is anagram 3 | 4 | Given two strings, write a function to determine whether they are anagrams. 5 | 6 | Execution: python Anagrams.py 7 | 8 | For more details, check out http://www.byte-by-byte.com/anagrams/ 9 | """ 10 | from collections import defaultdict 11 | import unittest 12 | 13 | 14 | def is_anagram(s1: str, s2: str): 15 | if len(s1) != len(s2): 16 | return False 17 | 18 | s1 = s1.lower() 19 | s2 = s2.lower() 20 | 21 | letters = defaultdict(int) 22 | 23 | for c in s1: 24 | letters[c] += 1 25 | 26 | for c in s2: 27 | letters[c] -= 1 28 | 29 | for i in letters.values(): 30 | if i != 0: 31 | return False 32 | return True 33 | 34 | 35 | class TestAnagram(unittest.TestCase): 36 | def test_1(self): 37 | self.assertEqual(is_anagram("", ""), True) 38 | print("Empty string s1='' and string s2='' are anagrams") 39 | 40 | def test_2(self): 41 | self.assertEqual(is_anagram("A", "B"), False) 42 | print("Empty string s1='A' and string s2='B' are not anagrams") 43 | 44 | def test_3(self): 45 | self.assertEqual(is_anagram("ab", "ba"), True) 46 | print("Empty string s1='ab' and string s2='ba' are anagrams") 47 | 48 | def test_4(self): 49 | self.assertEqual(is_anagram("AB", "ab"), True) 50 | print("Empty string s1='AB' and string s2='ab' are anagrams") 51 | 52 | 53 | if __name__ == '__main__': 54 | unittest.main() 55 | 56 | -------------------------------------------------------------------------------- /python/SwapVariables.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Swap Variables 3 | 4 | Given two integers, write a function that swaps them without using any 5 | temporary variables. 6 | 7 | Execution: python SwapVariables.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/swapvariables 10 | 11 | """ 12 | import unittest 13 | 14 | 15 | def swap_1(x: int, y: int): 16 | x = x + y 17 | y = x - y 18 | x = x - y 19 | return x, y 20 | 21 | 22 | def swap_2(x: int, y: int): 23 | x = x ^ y 24 | y = x ^ y 25 | x = x ^ y 26 | return x, y 27 | 28 | 29 | class TestSwap(unittest.TestCase): 30 | def test_swap_1_1_2(self): 31 | self.assertEqual(swap_1(1, 2), (2, 1)) 32 | print("Swapped (1, 2) with (2, 1)") 33 | 34 | def test_swap_1_5_5(self): 35 | self.assertEqual(swap_1(5, 5), (5, 5)) 36 | print("Swapped (5, 5) with (5, 5)") 37 | 38 | def test_swap_1_neg1_40(self): 39 | self.assertEqual(swap_1(-1, 40), (40, -1)) 40 | print("Swapped (-1, 40) with (40, -1)") 41 | 42 | def test_swap_2_1_2(self): 43 | self.assertEqual(swap_2(1, 2), (2, 1)) 44 | print("Swapped (1, 2) with (2, 1)") 45 | 46 | def test_swap_2_5_5(self): 47 | self.assertEqual(swap_2(5, 5), (5, 5)) 48 | print("Swapped (5, 5) with (5, 5)") 49 | 50 | def test_swap_2_neg1_40(self): 51 | self.assertEqual(swap_2(-1, 40), (40, -1)) 52 | print("Swapped (-1, 40) with (40, -1)") 53 | 54 | 55 | if __name__ == '__main__': 56 | unittest.main() 57 | -------------------------------------------------------------------------------- /python/StringCompression.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: String compression 3 | 4 | Given a string, write a function to compress it by shortening every 5 | sequence of the same character to that character followed by the number 6 | of repetitions. If the compressed string is longer than the original, 7 | you should return the original string. 8 | 9 | Execution: python StringCompression.py 10 | 11 | For more details, check out http://www.byte-by-byte.com/stringcompression/ 12 | 13 | """ 14 | import unittest 15 | 16 | 17 | def string_compress(input_str): 18 | cstring = [] 19 | 20 | curr = input_str[0] 21 | count = 0 22 | 23 | for char in input_str: 24 | if char == curr: 25 | count += 1 26 | else: 27 | cstring.append(curr + str(count)) 28 | curr = char 29 | count = 1 30 | 31 | cstring.append(curr + str(count)) 32 | cstring = ''.join(cstring) 33 | 34 | if len(cstring) < len(input_str): 35 | return cstring 36 | else: 37 | return input_str 38 | 39 | 40 | class TestStringCompress(unittest.TestCase): 41 | def test_1(self): 42 | self.assertEqual(string_compress("a"), "a") 43 | 44 | def test_2(self): 45 | self.assertEqual(string_compress("aaa"), "a3") 46 | 47 | def test_3(self): 48 | self.assertEqual(string_compress("aaabbb"), "a3b3") 49 | 50 | def test_4(self): 51 | self.assertEqual(string_compress("aaabccc"), "a3b1c3") 52 | 53 | 54 | if __name__ == '__main__': 55 | unittest.main() 56 | -------------------------------------------------------------------------------- /python/ConsecutiveArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Consecutive Array 3 | 4 | Given an unsorted array of numbers, find the length of the longest sequence 5 | of consecutive numbers in the array 6 | 7 | Execution: python ConsecutiveArray.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/consecutivearray/ 10 | """ 11 | import unittest 12 | 13 | 14 | def consecutive_array(arr: list): 15 | s = set() 16 | result = 0 17 | 18 | for element in arr: 19 | s.add(element) 20 | 21 | for i in range(len(arr)): 22 | if arr[i] - 1 not in s: 23 | j = arr[i] 24 | while j in s: 25 | j += 1 26 | result = max(result, j - arr[i]) 27 | return result 28 | 29 | 30 | class TestConsecutiveArray(unittest.TestCase): 31 | 32 | def test_single_sequence_sorted(self): 33 | self.assertEqual(consecutive_array([1, 2, 3, 4, 5]), 5) 34 | print("Single sequence, sorted order.") 35 | 36 | def test_single_sequence_unsorted(self): 37 | self.assertEqual(consecutive_array([5, 4, 3, 2, 1]), 5) 38 | print("Single sequence, unsorted order.") 39 | 40 | def test_multiple_sequences_sorted(self): 41 | self.assertEqual(consecutive_array([1, 2, 4, 5, 6]), 3) 42 | print("Multiple sequences, sorted order.") 43 | 44 | def test_multiple_sequences_unsorted(self): 45 | self.assertEqual(consecutive_array([2, 4, 1, 6, 5]), 3) 46 | print("Multiple sequences, unsorted order.") 47 | 48 | 49 | if __name__ == '__main__': 50 | unittest.main() 51 | 52 | 53 | -------------------------------------------------------------------------------- /java/TreeLevelOrder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Tree Level Order 3 | * 4 | * Given a tree, write a function that prints out the nodes of the tree in 5 | * level order. 6 | * 7 | * Execution: javac TreeLevelOrder.java && java TreeLevelOrder 8 | * 9 | * For more details, check out http://www.byte-by-byte.com/fibonacci/ 10 | */ 11 | 12 | import java.util.Queue; 13 | import java.util.LinkedList; 14 | 15 | public class TreeLevelOrder { 16 | 17 | private static class Node { 18 | private int value; 19 | private Node left; 20 | private Node right; 21 | 22 | private Node(int value) { 23 | this.value = value; 24 | } 25 | } 26 | 27 | public static void traverse(Node tree) { 28 | if (tree == null) return; 29 | 30 | Queue toVisit = new LinkedList(); 31 | toVisit.add(tree); 32 | 33 | while (!toVisit.isEmpty()) { 34 | Node curr = toVisit.remove(); 35 | System.out.println(curr.value); 36 | if (curr.left != null) toVisit.add(curr.left); 37 | if (curr.right != null) toVisit.add(curr.right); 38 | } 39 | } 40 | 41 | // Sample test cases 42 | public static void main(String[] args) { 43 | Node n = new Node(1); 44 | n.left = new Node(2); 45 | n.right = new Node(3); 46 | n.left.left = new Node(4); 47 | n.left.right = new Node(5); 48 | n.right.left = new Node(6); 49 | n.right.right = new Node(7); 50 | 51 | traverse(n); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /java/BigIntMod.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Big Int Mod 3 | * Author: Sam Gavis-Hughson 4 | * Date: 11/13/2016 5 | * 6 | * Given a list of bytes a, each representing one byte of a larger integer 7 | * (ie. {0x12, 0x34, 0x56, 0x78} represents the integer 0x12345678), and an 8 | * integer b, find a % b. 9 | * 10 | * Execution: javac BigIntMod.java && java BigIntMod 11 | * 12 | * For more details, check out http://www.byte-by-byte.com/bigintmod/ 13 | */ 14 | 15 | public class BigIntMod { 16 | // Compute the mod. We use a char array as it is equivalent to an array of 17 | // unsigned bytes 18 | public static int mod(char[] a, int b) { 19 | // If input is null, let's just return 0 20 | if (a == null) return 0; 21 | int m = 0; 22 | // Start with modding the most significant byte, then repeatedly shift 23 | // left. This way our value never gets larger than an int 24 | for (int i = 0; i < a.length; i++) { 25 | m <<= 8; 26 | m += (a[i] & 0xFF); 27 | m %= b; 28 | } 29 | return m; 30 | } 31 | 32 | // Sample test cases 33 | public static void main(String[] args) { 34 | assert mod(null, 1) == 0: 35 | "Null value"; 36 | assert mod(new char[]{}, 1) == 0: 37 | "Empty array"; 38 | assert mod(new char[]{15}, 10) == 5: 39 | "Single element array"; 40 | assert mod(new char[]{0x03, 0xED}, 10) == 5: 41 | "Multi-element array"; 42 | 43 | System.out.println("Passed all test cases"); 44 | } 45 | } -------------------------------------------------------------------------------- /java/LineIntersection.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Line intersection 3 | * 4 | * Given two lines on a Cartesian plane, write a function to determine 5 | * whether or not the lines intersect. 6 | * 7 | * Execution: javac LineIntersection.java && java LineIntersection 8 | * 9 | * For more details, check out http://www.byte-by-byte.com/lineintersection/ 10 | */ 11 | 12 | public class LineIntersection { 13 | 14 | private static double epsilon = 0.00001; 15 | private double slope; 16 | private double yIntercept; 17 | 18 | public LineIntersection(double slope, double yIntercept) { 19 | this.slope = slope; 20 | this.yIntercept = yIntercept; 21 | } 22 | 23 | public boolean intersect(LineIntersection line) { 24 | if (this.equals(line)) return true; 25 | if (Math.abs(slope - line.slope) > epsilon) return true; 26 | return false; 27 | } 28 | 29 | @Override 30 | public boolean equals(Object o) { 31 | if (!(o instanceof LineIntersection)) return false; 32 | LineIntersection line = (LineIntersection) o; 33 | return Math.abs(slope - line.slope) < epsilon && 34 | Math.abs(yIntercept - line.yIntercept) < epsilon; 35 | } 36 | 37 | 38 | // Sample test cases 39 | public static void main(String[] args) { 40 | 41 | LineIntersection line_1 = new LineIntersection(2, 5); 42 | LineIntersection line_2 = new LineIntersection(3, 10); 43 | 44 | assert line_1.intersect(line_2) == true; 45 | 46 | System.out.println("Passed all test cases"); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /cpp/ConsecutiveArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Consecutive Array 3 | * 4 | * 5 | * Execution: g++ -std=c++11 ConsecutiveArray.cpp -o ConsecutiveArray 6 | * 7 | * For more details, check out http://www.byte-by-byte.com/consecutivearray 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | // def consecutive_array(arr: list): 16 | // s = set() 17 | // result = 0 18 | // 19 | // for element in arr: 20 | // s.add(element) 21 | // 22 | // for i in range(len(arr)): 23 | // if arr[i] - 1 not in s: 24 | // j = arr[i] 25 | // while j in s: 26 | // j += 1 27 | // result = max(result, j - arr[i]) 28 | // return result 29 | // 30 | using namespace std; 31 | 32 | int consecutiveArray(vector arr) { 33 | set st; 34 | int result = 0; 35 | 36 | for (int i = 0; i < arr.size(); i++) { 37 | st.insert(arr[i]); 38 | } 39 | for (int i = 0; i < arr.size(); i++) { 40 | if (!(std::find(arr.begin(), arr.end(), arr[i] - 1) != arr.end())) { 41 | int j = arr[i]; 42 | while (std::find(st.begin(), st.end(), j) != st.end()) { 43 | j += 1; 44 | } 45 | int result = std::max(result, j - arr[i]); 46 | } 47 | cout << result << endl; 48 | } 49 | 50 | return 0; 51 | } 52 | 53 | int main() { 54 | 55 | vector v; 56 | v.push_back(1); 57 | v.push_back(2); 58 | v.push_back(3); 59 | v.push_back(4); 60 | v.push_back(5); 61 | 62 | consecutiveArray(v); 63 | 64 | 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /java/Anagrams.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Anagrams 3 | * 4 | * Given two strings, write a function to determine whether they are anagrams. 5 | * 6 | * 7 | * Execution: javac Anagrams.java && java Anagrams 8 | 9 | * For more details, check out http://www.byte-by-byte.com/anagrams 10 | */ 11 | 12 | public class Anagrams { 13 | public static boolean isAnagram(String s1, String s2) { 14 | if (s1.length() != s2.length()) return false; 15 | 16 | s1 = s1.toLowerCase(); 17 | s2 = s2.toLowerCase(); 18 | 19 | int[] letters = new int[1<<8]; 20 | 21 | for (char c : s1.toCharArray()) { 22 | letters[c]++; 23 | } 24 | 25 | for (char c : s2.toCharArray()) { 26 | letters[c]--; 27 | } 28 | 29 | for (int i : letters) { 30 | if (i != 0) return false; 31 | } 32 | return true; 33 | } 34 | 35 | // Sample test cases 36 | public static void main(String[] args) { 37 | assert isAnagram("", "") == true: 38 | "Empty string s1='' and string s2='' are anagrams"; 39 | assert isAnagram("A", "A") == true: 40 | "Empty string s1='A' and string s2='A' are anagrams"; 41 | assert isAnagram("A", "B") == false: 42 | "Empty string s1='A' and string s2='B' are not anagrams"; 43 | assert isAnagram("ab", "ba") == true: 44 | "Empty string s1='ab' and string s2='ba' are anagrams"; 45 | assert isAnagram("AB", "ab") == true: 46 | "Empty string s1='AB' and string s2='ab' are anagrams"; 47 | 48 | System.out.println("Passed all test cases"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /cpp/PrintReversedList.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Print reverse list 3 | * 4 | * Execution: g++ PrintReverseList.cpp -o PrintReverseList 5 | * 6 | * For more details, check out http://www.byte-by-byte.com/printreverselist/ 7 | */ 8 | 9 | #include 10 | #include 11 | 12 | using namespace std; 13 | 14 | struct Node { 15 | int value; 16 | Node *next; 17 | }; 18 | 19 | void printReverseList(Node *n) { 20 | if (n == NULL) { 21 | return; 22 | } 23 | printReverseList(n->next); 24 | cout << n->value << endl; 25 | } 26 | 27 | void test_1() { 28 | 29 | cout << "Original list: 1->2->3" << endl; 30 | Node *n1 = new Node(); 31 | Node *n2 = new Node(); 32 | Node *n3 = new Node(); 33 | 34 | n1->value = 1; 35 | n1->next = n2; 36 | 37 | n2->value = 2; 38 | n2->next = n3; 39 | 40 | n3->value = 3; 41 | n3->next = NULL; 42 | 43 | printReverseList(n1); 44 | } 45 | 46 | void test_2() { 47 | 48 | cout << "Original list: 3->2->1" << endl; 49 | Node *n1 = new Node(); 50 | Node *n2 = new Node(); 51 | Node *n3 = new Node(); 52 | 53 | n1->value = 3; 54 | n1->next = n2; 55 | 56 | n2->value = 2; 57 | n2->next = n3; 58 | 59 | n3->value = 1; 60 | n3->next = NULL; 61 | 62 | printReverseList(n1); 63 | } 64 | 65 | void test_3() { 66 | 67 | cout << "Original list: 10->9" << endl; 68 | Node *n1 = new Node(); 69 | Node *n2 = new Node(); 70 | 71 | n1->value = 10; 72 | n1->next = n2; 73 | 74 | n2->value = 9; 75 | n2->next = NULL; 76 | 77 | printReverseList(n1); 78 | } 79 | 80 | int main() { 81 | 82 | test_1(); 83 | test_2(); 84 | test_3(); 85 | 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /python/IntToRoman.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Integer to Roman Numerals 3 | 4 | Write a function to convert an integer into its roman numeral representation 5 | 6 | Execution: python IntToRoman.py 7 | 8 | For more details, check out http://www.byte-by-byte.com/inttoroman/ 9 | 10 | """ 11 | import unittest 12 | 13 | 14 | numerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] 15 | values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] 16 | 17 | 18 | def int_to_roman(value): 19 | if value > 3999 or value < 1: 20 | raise ValueError(f"Value {value} is above 3999 or below 1.") 21 | i = 0 22 | numeral = [] 23 | while value > 0: 24 | if value - values[i] >= 0: 25 | numeral.append(numerals[i]) 26 | value -= values[i] 27 | else: 28 | i += 1 29 | return ''.join(numeral) 30 | 31 | 32 | class TestIntToRoman(unittest.TestCase): 33 | def test_I(self): 34 | self.assertEqual(int_to_roman(1), "I") 35 | print("1 converts to I") 36 | 37 | def test_IV(self): 38 | self.assertEqual(int_to_roman(4), "IV") 39 | print("4 converts to IV") 40 | 41 | def test_VI(self): 42 | self.assertEqual(int_to_roman(6), "VI") 43 | print("6 converts to VI") 44 | 45 | def test_XI(self): 46 | self.assertEqual(int_to_roman(11), "XI") 47 | print("11 converts to XI") 48 | 49 | def test_XLIX(self): 50 | self.assertEqual(int_to_roman(49), "XLIX") 51 | print("49 converts to XLIX") 52 | 53 | def test_MMXX(self): 54 | self.assertEqual(int_to_roman(2020), "MMXX") 55 | print("2020 converts to MMXX") 56 | 57 | 58 | if __name__ == '__main__': 59 | unittest.main() 60 | 61 | -------------------------------------------------------------------------------- /java/StringDeletion.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: String deletion 3 | * 4 | * Given a string and a dictionary HashSet, write a function to determine the 5 | * minimum number of characters to delete to make a word. 6 | * 7 | * Execution: javac StringDeletion.java && java StringDeletion 8 | * 9 | * For more details, check out http://www.byte-by-byte.com/stringdeletion 10 | */ 11 | import java.util.*; 12 | 13 | public class StringDeletion { 14 | public static int delete(String query, HashSet dictionary) { 15 | Queue queue = new LinkedList(); 16 | Set queueElements = new HashSet(); 17 | 18 | queue.add(query); 19 | queueElements.add(query); 20 | 21 | while (!queue.isEmpty()) { 22 | String s = queue.remove(); 23 | queueElements.remove(s); 24 | if (dictionary.contains(s)) { 25 | return query.length() - s.length(); 26 | } 27 | for (int i = 0; i < s.length(); i++) { 28 | String sub = s.substring(0, i) + s.substring(i+1, s.length()); 29 | if (sub.length() > 0 && !queueElements.contains(sub)) { 30 | queue.add(sub); 31 | queueElements.add(sub); 32 | } 33 | } 34 | } 35 | return -1; 36 | } 37 | 38 | // Sample test cases 39 | public static void main(String[] args) { 40 | String query = "abc"; 41 | HashSet hset = new HashSet(); 42 | 43 | hset.add("a"); 44 | hset.add("aa"); 45 | hset.add("aaa"); 46 | 47 | assert delete(query, hset) == 2: 48 | "Successfully determines 2 strings."; 49 | 50 | System.out.println("Passed all test cases"); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /java/SwapVariables.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Swap Variables 3 | * 4 | * Given two integers, write a function that swaps them without using any temporary variables. 5 | * 6 | * Execution: javac SwapVariables.java && java SwapVariables 7 | 8 | * For more details, check out http://www.byte-by-byte.com/swapvariables 9 | */ 10 | 11 | public class SwapVariables { 12 | public static int[] swap_1(int x, int y) { 13 | x = x + y; 14 | y = x - y; 15 | x = x - y; 16 | 17 | int ar[] = new int[2]; 18 | ar[0] = x; 19 | ar[1] = y; 20 | return ar; 21 | } 22 | 23 | public static int[] swap_2(int x, int y) { 24 | x = x ^ y; 25 | y = x ^ y; 26 | x = x ^ y; 27 | 28 | int ar[] = new int[2]; 29 | ar[0] = x; 30 | ar[1] = y; 31 | return ar; 32 | } 33 | 34 | // Sample test cases 35 | public static void main(String[] args) { 36 | int ar_1[] = swap_1(1, 2); 37 | assert ar_1[0] == 2 && ar_1[1] == 1: 38 | "Swapped (1,2) with (2,1)"; 39 | 40 | int ar_2[] = swap_1(5, 5); 41 | assert ar_2[0] == 5 && ar_2[1] == 5: 42 | "Swapped (5,5) with (5,5)"; 43 | 44 | int ar_3[] = swap_1(-1, 40); 45 | assert ar_3[0] == 40 && ar_3[1] == -1: 46 | "Swaped(-1,40) with (40,-1)"; 47 | 48 | int ar_4[] = swap_2(1, 2); 49 | assert ar_4[0] == 2 && ar_4[1] == 1: 50 | "Swapped (1,2) with (2,1)"; 51 | 52 | int ar_5[] = swap_2(5, 5); 53 | assert ar_5[0] == 5 && ar_5[1] == 5: 54 | "Swapped (5,5) with (5,5)"; 55 | 56 | int ar_6[] = swap_2(-1, 40); 57 | assert ar_6[0] == 40 && ar_6[1] == -1: 58 | "Swapped(-1,40) with (40,-1)"; 59 | 60 | System.out.println("Passed all test cases"); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /cpp/SwapVariables.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Swap Variables 3 | * 4 | * Given two integers, write a function that swaps them without using any 5 | * temporary variables. 6 | * 7 | * Execution: g++ SwapVariables.cpp -o SwapVariables 8 | * 9 | * For more details, check out http://www.byte-by-byte.com/swapvariables 10 | */ 11 | 12 | #include 13 | #include 14 | 15 | using namespace std; 16 | 17 | vector swap_1(int x, int y) { 18 | vector vars; 19 | 20 | x = x + y; 21 | y = x - y; 22 | x = x - y; 23 | 24 | vars.push_back(x); 25 | vars.push_back(y); 26 | 27 | return vars; 28 | } 29 | 30 | vector swap_2(int x, int y) { 31 | vector vars; 32 | 33 | x = x ^ y; 34 | y = x ^ y; 35 | x = x ^ y; 36 | 37 | vars.push_back(x); 38 | vars.push_back(y); 39 | return vars; 40 | } 41 | 42 | int main() { 43 | vector test_1 = swap_1(1, 2); 44 | assert(test_1[0] == 2); 45 | assert(test_1[1] == 1); 46 | cout << "Swapped (1,2) with (2,1)" << endl; 47 | 48 | vector test_2 = swap_1(5, 5); 49 | assert(test_2[0] == 5); 50 | assert(test_2[1] == 5); 51 | cout << "Swapped (5,5) with (5,5)" << endl; 52 | 53 | vector test_3 = swap_1(-1, 40); 54 | assert(test_3[0] == 40); 55 | assert(test_3[1] == -1); 56 | cout << "Swapped (40,-1) with (-1,40)" << endl; 57 | 58 | vector test_4 = swap_2(1, 2); 59 | assert(test_4[0] == 2); 60 | assert(test_4[1] == 1); 61 | cout << "Swapped (1,2) with (2,1)" << endl; 62 | 63 | vector test_5 = swap_2(5, 5); 64 | assert(test_5[0] == 5); 65 | assert(test_5[1] == 5); 66 | cout << "Swapped (5,5) with (5,5)" << endl; 67 | 68 | vector test_6 = swap_2(-1, 40); 69 | assert(test_6[0] == 40); 70 | assert(test_6[1] == -1); 71 | cout << "Swapped (40,-1) with (-1,40)" << endl; 72 | 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /python/TreeLevelOrder.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Tree Level Order. 3 | 4 | Given a tree, write a function that prints out the nodes of the tree in level 5 | order. 6 | 7 | Execution: python TreeLevelOrder.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/treelevelorder 10 | 11 | """ 12 | import unittest 13 | 14 | 15 | class Queue: 16 | def __init__(self): 17 | self.items = [] 18 | 19 | def enqueue(self, item): 20 | self.items.insert(0, item) 21 | 22 | def dequeue(self): 23 | if not self.is_empty(): 24 | return self.items.pop() 25 | 26 | def is_empty(self): 27 | return len(self.items) == 0 28 | 29 | def peek(self): 30 | if not self.is_empty(): 31 | return self.items[-1].value 32 | 33 | def __len__(self): 34 | return self.size() 35 | 36 | def size(self): 37 | return len(self.items) 38 | 39 | 40 | class Node: 41 | def __init__(self, value): 42 | self.value = value 43 | self.left = None 44 | self.right = None 45 | 46 | 47 | def traverse(start): 48 | if start is None: 49 | return 50 | 51 | queue = Queue() 52 | queue.enqueue(start) 53 | 54 | traversal = [] 55 | while len(queue) > 0: 56 | traversal.append(queue.peek()) 57 | node = queue.dequeue() 58 | 59 | if node.left: 60 | queue.enqueue(node.left) 61 | if node.right: 62 | queue.enqueue(node.right) 63 | 64 | return traversal 65 | 66 | 67 | class TestTreeLevelOrder(unittest.TestCase): 68 | def test_1(self): 69 | n = Node(1) 70 | n.left = Node(2) 71 | n.right = Node(3) 72 | n.left.left = Node(4) 73 | n.left.right = Node(5) 74 | n.right.left = Node(6) 75 | n.right.right = Node(7) 76 | self.assertEqual(traverse(n), [1, 2, 3, 4, 5, 6, 7]) 77 | 78 | 79 | if __name__ == '__main__': 80 | unittest.main() 81 | -------------------------------------------------------------------------------- /java/ConsecutiveArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Consecutive Array 3 | * Author: Sam Gavis-Hughson 4 | * Date: 9/25/2016 5 | * 6 | * Given an unsorted array of numbers, find the length of the longest sequence 7 | * of consecutive numbers in the array 8 | * 9 | * Execution: javac ConsecutiveArray.java && java ConsecutiveArray 10 | * 11 | * For more details, check out http://www.byte-by-byte.com/consecutivearray/ 12 | */ 13 | 14 | import java.util.HashSet; 15 | 16 | public class ConsecutiveArray { 17 | public static int consecutive(int[] a) { 18 | // Put all the values into a HashSet 19 | HashSet values = new HashSet(); 20 | for (int i : a) { 21 | values.add(i); 22 | } 23 | 24 | // For each value, check if its the first in a sequence of consecutive 25 | // numbers and iterate through to find the length of the consecutive 26 | // sequence 27 | int maxLength = 0; 28 | for (int i : values) { 29 | // If it is not the leftmost value in the sequence, don't bother 30 | if (values.contains(i - 1)) continue; 31 | int length = 0; 32 | 33 | // Iterate through sequence 34 | while (values.contains(i++)) length++; 35 | maxLength = Math.max(maxLength, length); 36 | } 37 | 38 | return maxLength; 39 | } 40 | 41 | // Sample test cases 42 | public static void main(String[] args) { 43 | assert consecutive(new int[]{1,2,3,4,5}) == 5 : 44 | "Single sequence, sorted order"; 45 | assert consecutive(new int[]{5,4,3,2,1}) == 5 : 46 | "Single sequence, unsorted order"; 47 | assert consecutive(new int[]{1,2,4,5,6}) == 3 : 48 | "Multiple sequences, sorted order"; 49 | assert consecutive(new int[]{2,4,1,6,5}) == 3 : 50 | "Multiple sequences, unsorted order"; 51 | System.out.println("Passed all test cases"); 52 | } 53 | } -------------------------------------------------------------------------------- /python/PrintReverseList.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Remove duplicates from linked list. 3 | 4 | Given a linked list, write a function that prints the nodes of 5 | the list in reverse order. 6 | 7 | Execution: python DedupLinkedList.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/printreverselist/ 10 | """ 11 | import unittest 12 | 13 | 14 | class Node: 15 | """ 16 | Node class for Linked List. 17 | """ 18 | def __init__(self, value=None): 19 | self.value = value 20 | self.next = None 21 | 22 | 23 | class LinkedList: 24 | def __init__(self): 25 | self.head = None 26 | 27 | def append(self, data): 28 | new_node = Node(data) 29 | 30 | if self.head is None: 31 | self.head = new_node 32 | return 33 | 34 | last_node = self.head 35 | while last_node.next: 36 | last_node = last_node.next 37 | last_node.next = new_node 38 | 39 | def print_reversed_list(self, node): 40 | if node is None: 41 | return 42 | self.print_reversed_list(node.next) 43 | print(node.value) 44 | 45 | 46 | class TestNthToLast(unittest.TestCase): 47 | 48 | def test_1(self): 49 | print("Before list: 1->2->3->4") 50 | ll = LinkedList() 51 | ll.append(1) 52 | ll.append(2) 53 | ll.append(3) 54 | ll.append(4) 55 | 56 | ll.print_reversed_list(ll.head) 57 | 58 | def test_2(self): 59 | print("Before list: 4->3->2->1") 60 | ll = LinkedList() 61 | ll.append(4) 62 | ll.append(3) 63 | ll.append(2) 64 | ll.append(1) 65 | 66 | ll.print_reversed_list(ll.head) 67 | 68 | def test_3(self): 69 | print("Before list: 10->9->8") 70 | ll = LinkedList() 71 | ll.append(10) 72 | ll.append(9) 73 | ll.append(8) 74 | 75 | ll.print_reversed_list(ll.head) 76 | 77 | if __name__ == '__main__': 78 | unittest.main() 79 | 80 | -------------------------------------------------------------------------------- /java/IntToRoman.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Integer to Roman Numerals 3 | * Author: Sam Gavis-Hughson 4 | * Date: 2/1/2017 5 | * 6 | * Write a function to convert an integer into its roman numeral representation 7 | * 8 | * Execution: javac IntToRoman.java && java IntToRoman 9 | * 10 | * For more details, check out http://www.byte-by-byte.com/inttoroman/ 11 | */ 12 | 13 | public class IntToRoman { 14 | // Parallel arrays of numerals in descending order and their values. We 15 | // include any pairs of numerals where a smaller numeral is subtracted from 16 | // a larger numeral 17 | private static final String[] numerals = 18 | new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", 19 | "V", "IV", "I"}; 20 | private static final int[] values = 21 | new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 22 | 23 | 24 | public static String integerToRoman(int value) { 25 | // We are only considering the range for standard roman numerals 26 | if (value > 3999 || value < 1) throw new IllegalArgumentException(); 27 | 28 | StringBuilder numeral = new StringBuilder(); 29 | int i = 0; 30 | // Greedily append the largest numeral possible until the value is 0 31 | while (value > 0) { 32 | if (value - values[i] >= 0) { 33 | numeral.append(numerals[i]); 34 | value -= values[i]; 35 | } else { 36 | i++; 37 | } 38 | } 39 | 40 | return numeral.toString(); 41 | } 42 | 43 | // Sample test cases 44 | public static void main(String[] args) { 45 | assert integerToRoman(1).equals("I"); 46 | assert integerToRoman(4).equals("IV"); 47 | assert integerToRoman(6).equals("VI"); 48 | assert integerToRoman(11).equals("XI"); 49 | assert integerToRoman(49).equals("XLIX"); 50 | assert integerToRoman(2020).equals("MMXX"); 51 | 52 | System.out.println("Passed all test cases"); 53 | } 54 | } -------------------------------------------------------------------------------- /java/NthToLast.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Nth-to-last Linked List Element 3 | * Author: Sam Gavis-Hughson 4 | * Date: 1/13/2016 5 | * 6 | * Given a linked list, find the nth-to-last value in the list. 7 | * 8 | * Execution: javac NthToLast.java && java NthToLast 9 | * 10 | * For more details, check out http://www.byte-by-byte.com/nthtolastelement/ 11 | */ 12 | 13 | public class NthToLast { 14 | // Private node class 15 | private static class Node { 16 | private int value; 17 | private Node next; 18 | 19 | private Node(int value) { 20 | this.value = value; 21 | } 22 | } 23 | 24 | public static Node nthToLast(Node node, int n) { 25 | Node curr = node; 26 | Node follower = node; 27 | 28 | // Iterate curr forward by n. If you reach the end of the list then it is 29 | // shorter than n, so you can't possible have an nth-to-last node 30 | for (int i = 0; i < n; i++) { 31 | if (curr == null) return null; 32 | curr = curr.next; 33 | } 34 | 35 | // If length is exactly n, the nth-to-last node would be null 36 | if (curr == null) return null; 37 | 38 | // Move both nodes forward in unison until curr is at the end of the list 39 | while (curr.next != null) { 40 | curr = curr.next; 41 | follower = follower.next; 42 | } 43 | 44 | return follower; 45 | } 46 | 47 | // Sample test cases 48 | public static void main(String[] args) { 49 | Node n = new Node(1); 50 | n.next = new Node(2); 51 | n.next.next = new Node(3); 52 | n.next.next.next = new Node(4); 53 | n.next.next.next.next = new Node(5); 54 | 55 | assert nthToLast(n, 0).value == 5; 56 | assert nthToLast(n, 1).value == 4; 57 | assert nthToLast(n, 2).value == 3; 58 | assert nthToLast(n, 3).value == 2; 59 | assert nthToLast(n, 4).value == 1; 60 | assert nthToLast(n, 5) == null; 61 | } 62 | } -------------------------------------------------------------------------------- /java/ReverseStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Reverse stack 3 | * 4 | * Given a stack, reverse the items without creating any additional data structures. 5 | * 6 | * Execution: javac ReverseStack.java && java ReverseStack 7 | * 8 | * For more details, check out http://www.byte-by-byte.com/reversestack/ 9 | */ 10 | 11 | import java.util.Stack; 12 | 13 | public class ReverseStack { 14 | public static Stack reverse(Stack stack) { 15 | if (stack.isEmpty()) return stack; 16 | int temp = stack.pop(); 17 | reverse(stack); 18 | insertAtBottom(stack, temp); 19 | return stack; 20 | } 21 | 22 | private static void insertAtBottom(Stack stack, int x) { 23 | if (stack.isEmpty()) { 24 | stack.push(x); 25 | return; 26 | } 27 | int temp = stack.pop(); 28 | insertAtBottom(stack, x); 29 | stack.push(temp); 30 | } 31 | 32 | public static void test_1() { 33 | Stack s = new Stack(); 34 | s.push(3); 35 | s.push(2); 36 | s.push(1); 37 | assert reverse(s) == s; 38 | System.out.println("reverse(1->2->3) = 3->2->1"); 39 | } 40 | 41 | public static void test_2() { 42 | Stack s = new Stack(); 43 | s.push(5); 44 | s.push(6); 45 | s.push(10); 46 | s.push(11); 47 | s.push(60); 48 | s.push(50); 49 | assert reverse(s) == s; 50 | System.out.println("reverse(5->6->10->11->60->50) = 50->60->11->10->6->5"); 51 | } 52 | 53 | public static void test_3() { 54 | Stack s = new Stack(); 55 | s.push(1); 56 | s.push(2); 57 | s.push(3); 58 | assert reverse(s) == s; 59 | System.out.println("reverse(3->2->1) = 1->2->3"); 60 | } 61 | // Sample test cases 62 | public static void main(String[] args) { 63 | test_1(); 64 | test_2(); 65 | test_3(); 66 | 67 | System.out.println("Passed all test cases"); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /python/MaxStack.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Max Stack 3 | 4 | Implement a LIFO stack that has a push(), pop(), and max() function, where 5 | max() returns the maximum value in the stack. All of these functions should 6 | run in O(1) time. 7 | 8 | Execution: python MaxStack.py 9 | 10 | For more details, check out http://www.byte-by-byte.com/maxstack 11 | """ 12 | import unittest 13 | 14 | 15 | class Node: 16 | def __init__(self, value, nxt=None, old_max=None): 17 | self.value = value 18 | self.nxt = nxt 19 | self.old_max = old_max 20 | 21 | 22 | class MaxStack: 23 | def __init__(self): 24 | self.stack = [] 25 | self.max = None 26 | 27 | def push(self, x: int): 28 | n = Node(x) 29 | if self.stack == []: 30 | stack = n 31 | else: 32 | n.nxt = stack 33 | stack = n 34 | 35 | if self.max is None or n.value > self.max.value: 36 | n.oldMax = self.max 37 | self.max = n 38 | 39 | def pop(self): 40 | try: 41 | if self.stack: 42 | n = self.stack 43 | self.stack = n.nxt 44 | self.max = n.old_max 45 | return n.value 46 | except ValueError: 47 | print("Stack is None") 48 | 49 | def max_val(self): 50 | try: 51 | if self.max: 52 | return self.max.value 53 | except ValueError: 54 | print("Max is None") 55 | 56 | 57 | 58 | class TestMaxStack(unittest.TestCase): 59 | def test_1(self): 60 | ms = MaxStack() 61 | ms.push(1) 62 | ms.push(100) 63 | ms.push(5) 64 | self.assertEqual(ms.max_val(), 100) 65 | 66 | def test_2(self): 67 | ms = MaxStack() 68 | ms.push(1) 69 | ms.push(2) 70 | ms.push(3) 71 | self.assertEqual(ms.max_val(), 3) 72 | 73 | def test_3(self): 74 | ms = MaxStack() 75 | ms.push(-1) 76 | ms.push(2) 77 | ms.push(-3) 78 | self.assertEqual(ms.max_val(), 2) 79 | 80 | 81 | if __name__ == '__main__': 82 | unittest.main() 83 | 84 | -------------------------------------------------------------------------------- /java/PrintReversedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Print reversed list 3 | * 4 | * Given a linked list, write a function that prints the nodes of the 5 | * list in reverse order. 6 | * 7 | * Execution: javac PrintReversedList.java && java PrintReversedList 8 | * 9 | * For more details, check out http://www.byte-by-byte.com/printreversedlist/ 10 | */ 11 | 12 | public class PrintReversedList { 13 | 14 | private static class Node { 15 | private int value; 16 | private Node next; 17 | 18 | private Node(int value) { 19 | this.value = value; 20 | } 21 | } 22 | 23 | public static void printReversedList(Node n) { 24 | if (n == null) { 25 | return; 26 | } 27 | printReversedList(n.next); 28 | System.out.println(n.value); 29 | } 30 | 31 | public static void test_1() { 32 | System.out.println("Original: 1->2->3->4"); 33 | Node n = new Node(1); 34 | n.next = new Node(2); 35 | n.next.next = new Node(3); 36 | n.next.next.next = new Node(4); 37 | 38 | printReversedList(n); 39 | } 40 | 41 | public static void test_2() { 42 | System.out.println("Original: 4->3->2->1"); 43 | Node n = new Node(4); 44 | n.next = new Node(3); 45 | n.next.next = new Node(2); 46 | n.next.next.next = new Node(1); 47 | 48 | printReversedList(n); 49 | } 50 | 51 | public static void test_3() { 52 | System.out.println("Original: 10->9->8"); 53 | Node n = new Node(10); 54 | n.next = new Node(9); 55 | n.next.next = new Node(8); 56 | 57 | printReversedList(n); 58 | } 59 | // Sample test cases 60 | public static void main(String[] args) { 61 | 62 | System.out.println("Test 1:"); 63 | test_1(); 64 | System.out.println("\n"); 65 | 66 | System.out.println("Test 2:"); 67 | test_2(); 68 | System.out.println("\n"); 69 | 70 | System.out.println("Test 3:"); 71 | test_3(); 72 | System.out.println("\n"); 73 | 74 | System.out.println("Passed all test cases"); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /cpp/IntToRoman.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Int to Roman 3 | * 4 | * Write a function to convert an integer into its roman numeral representation 5 | * 6 | * Execution: g++ -std=c++11 IntToRoman.cpp -o IntToRoman 7 | * 8 | * For more details, check out http://www.byte-by-byte.com/inttoroman 9 | */ 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | 15 | // def int_to_roman(value): 16 | // if value > 3999 or value < 1: 17 | // raise ValueError(f"Value {value} is above 3999 or below 1.") 18 | // i = 0 19 | // numeral = [] 20 | // while value > 0: 21 | // if value - values[i] >= 0: 22 | // numeral.append(numerals[i]) 23 | // value -= values[i] 24 | // else: 25 | // i += 1 26 | // return ''.join(numeral) 27 | 28 | string intToRoman(int value) { 29 | vector numerals = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; 30 | vector values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 31 | 32 | if ( (value > 3999) || (value < 1) ) { 33 | cout << "Error: " << value << endl; 34 | } 35 | int i = 0; 36 | vector numeral; 37 | while (value > 0) { 38 | if (value - values[i] >= 0) { 39 | numeral.push_back(numerals[i]); 40 | value -= values[i]; 41 | } 42 | else { 43 | i += 1; 44 | } 45 | } 46 | 47 | string ret = ""; 48 | for (int i = 0; i < numeral.size(); i++) { 49 | ret += numeral[i]; 50 | } 51 | 52 | return ret; 53 | } 54 | 55 | int main() { 56 | 57 | assert(intToRoman(1) == "I"); 58 | cout << "1 converts to I" << endl; 59 | 60 | assert(intToRoman(5) == "V"); 61 | cout << "5 converts to V" << endl; 62 | 63 | assert(intToRoman(4) == "IV"); 64 | cout << "4 converts to IV" << endl; 65 | 66 | assert(intToRoman(6) == "VI"); 67 | cout << "6 converts to VI" << endl; 68 | 69 | assert(intToRoman(11) == "XI"); 70 | cout << "11 converts to XI" << endl; 71 | 72 | assert(intToRoman(49) == "XLIX"); 73 | cout << "49 converts to XLIX" << endl; 74 | 75 | assert(intToRoman(2020) == "MMXX"); 76 | cout << "2020 converts to MMXX" << endl; 77 | 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /python/MatrixProduct.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Matrix Product 3 | 4 | Given a matrix, find the path from top left to bottom right with the greatest 5 | product by moving only down and right. 6 | 7 | Execution: python MatrixProduct.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/matrixproduct/ 10 | 11 | """ 12 | import unittest 13 | 14 | 15 | def matrix_product(mat): 16 | """ 17 | Bottom-up dynamic programming solution. 18 | """ 19 | if len(mat) == 0 or len(mat[0]) == 0: 20 | return 0 21 | 22 | # Create cache of min and max product to a given cell. 23 | max_cache = [[1] * len(mat[0])] * len(mat) 24 | min_cache = [[1] * len(mat[0])] * len(mat) 25 | 26 | # Fill caches. We start at the top left and iteratively find the greatest 27 | # at smallest path to each subsequent cell by considering the greatest and 28 | # smallest path to the cells above and to the left of the current cell. 29 | for i in range(len(mat)): 30 | for j in range(len(mat[0])): 31 | max_val = float("inf") 32 | min_val = float("-inf") 33 | 34 | # If you're in the top left corner, just copy to cache 35 | if i == 0 and j == 0: 36 | max_val = mat[i][j] 37 | min_val = mat[i][j] 38 | 39 | # If we're not at the top, consider the value above. 40 | if i > 0: 41 | temp_max = max(mat[i][j] * max_cache[i-1][j], mat[i][j] * min_cache[i-1][j]) 42 | max_val = max(temp_max, max_val) 43 | temp_min = min(mat[i][j] * max_cache[i-1][j], mat[i][j] * min_cache[i-1][j]) 44 | min_val = min(temp_min, min_val) 45 | 46 | # If we're not on the left, consider the value to the left 47 | if j > 0: 48 | temp_max = max(mat[i][j] * max_cache[i][j-1], mat[i][j] * min_cache[i][j-1]) 49 | max_val = max(temp_max, max_val) 50 | temp_min = min(mat[i][j] * max_cache[i][j-1], mat[i][j] * min_cache[i][j-1]) 51 | min_val = min(temp_min, min_val) 52 | 53 | max_cache[i][j] = max_val 54 | min_cache[i][j] = min_val 55 | return max_cache[len(max_cache) - 1][len(max_cache[0]) - 1] 56 | 57 | 58 | mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 59 | x = matrix_product(mat) 60 | print(x) 61 | -------------------------------------------------------------------------------- /java/MaxStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Max Stack 3 | * 4 | * Implement a LIFO stack that has a push(), pop(), and max() function, where 5 | * max() returns the maximum value in the stack. All of these functions should 6 | * run in O(1) time. 7 | * 8 | * Execution: javac MaxStack.java && java MaxStack 9 | * 10 | * For more details, check out http://www.byte-by-byte.com/maxstack/ 11 | */ 12 | 13 | public class MaxStack { 14 | 15 | private class Node { 16 | private int value; 17 | private Node next; 18 | private Node oldMax; 19 | } 20 | 21 | private Node stack; 22 | private Node max; 23 | 24 | public MaxStack() {} 25 | 26 | public void push(int x) { 27 | Node n = new Node(); 28 | n.value = x; 29 | 30 | if (stack == null) { 31 | stack = n; 32 | } else { 33 | n.next = stack; 34 | stack = n; 35 | } 36 | 37 | if (max == null || n.value > max.value) { 38 | n.oldMax = max; 39 | max = n; 40 | } 41 | } 42 | 43 | public int pop() { 44 | if (stack == null) { 45 | throw new NullPointerException("Stack is Null"); 46 | } 47 | Node n = stack; 48 | stack = n.next; 49 | max = n.oldMax; 50 | return n.value; 51 | } 52 | 53 | public int max() { 54 | if (max == null) { 55 | throw new NullPointerException("Max is Null"); 56 | } 57 | return max.value; 58 | } 59 | 60 | public static void test_1() { 61 | MaxStack s = new MaxStack(); 62 | s.push(1); 63 | s.push(100); 64 | s.push(5); 65 | assert s.max() == 100; 66 | } 67 | 68 | public static void test_2() { 69 | MaxStack s = new MaxStack(); 70 | s.push(1); 71 | s.push(2); 72 | s.push(3); 73 | assert s.max() == 3; 74 | } 75 | 76 | public static void test_3() { 77 | MaxStack s = new MaxStack(); 78 | s.push(-1); 79 | s.push(2); 80 | s.push(-3); 81 | assert s.max() == 2; 82 | } 83 | 84 | // Sample test cases 85 | public static void main(String[] args) { 86 | 87 | test_1(); 88 | test_2(); 89 | test_3(); 90 | System.out.println("Passed all test cases"); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /python/BuildOrder.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Build Order 3 | 4 | Given a list of packages and their dependencies, determine a valid build 5 | order. 6 | 7 | Execution: python BuildOrder.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/buildorder/ 10 | """ 11 | import unittest 12 | 13 | 14 | def build_order(processes: list): 15 | """ 16 | Perform topological sort. Input is a list of dependencies where the index is the process number 17 | and the value is the numbers the processes it depends on. 18 | """ 19 | temporary_marks = set() 20 | permanent_marks = set() 21 | result = [] 22 | 23 | # Recursively search from any unmarked node. 24 | for i in range(len(processes)): 25 | if i not in permanent_marks: 26 | visit(i, processes, temporary_marks, permanent_marks, result) 27 | return result 28 | 29 | 30 | def visit(process, processes, temporary_marks, permanent_marks, result): 31 | """ 32 | Search through all unmarked nodes accessible from process. 33 | """ 34 | 35 | # If we haven't visited the node, recursively search from there. 36 | if process not in permanent_marks: 37 | temporary_marks.add(process) 38 | 39 | # Perform recursive search from children. 40 | for i in processes[process]: 41 | visit(i, processes, temporary_marks, permanent_marks, result) 42 | 43 | # Add permanent mark, remove temporary mark, and add to results list. 44 | permanent_marks.add(process) 45 | temporary_marks.add(process) 46 | 47 | result.append(process) 48 | 49 | 50 | class TestBuildOrder(unittest.TestCase): 51 | def test_simple_sorted_order(self): 52 | self.assertEqual(build_order([[], [0], [1], [2], [3]]), [0, 1, 2, 3, 4]) 53 | print("Simple sorted order.") 54 | 55 | def test_complex_sorted_order(self): 56 | self.assertEqual(build_order([[], [0], [0], [1, 2], [1, 2, 3]]), [0, 1, 2, 3, 4]) 57 | print("Complex sorted order.") 58 | 59 | def test_simple_unsorted_order(self): 60 | self.assertEqual(build_order([[3], [0], [4], [], [1]]), [3, 0, 1, 4, 2]) 61 | print("Simple unsorted order.") 62 | 63 | def test_complex_unsorted_order(self): 64 | self.assertEqual(build_order([[3], [0, 3], [0, 1, 3], [], [1, 2, 3]]), [3, 0, 1, 2, 4]) 65 | print("Complex unsorted order.") 66 | 67 | 68 | if __name__ == '__main__': 69 | unittest.main() 70 | 71 | 72 | -------------------------------------------------------------------------------- /python/FindDuplicates.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Find Duplicates 3 | 4 | Given an array of integers where each value 1 <= x <= len(array), write a 5 | function that finds all the duplicates in the array. 6 | 7 | Execution: python FindDuplicates.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/findduplicates/ 10 | 11 | """ 12 | import unittest 13 | 14 | 15 | def find_duplicates(arr): 16 | """ 17 | Return a list of duplicates in the array. To avoid using extra space, 18 | we flag which elements we've seen before by negating the value at 19 | indexed at that value in the array. 20 | """ 21 | 22 | # Use a set for results to avoid duplicates. 23 | result_set = set() 24 | for i in range(len(arr)): 25 | # Translate the value into an index (1 <= x <= len(arr)) 26 | idx = abs(arr[i]) - 1 27 | 28 | # If the value at that index is negative, then we've already seen 29 | # that value so it's a duplicate. Otherwise, negate the value at 30 | # that index we know we've seen it. 31 | if arr[idx] < 0: 32 | result_set.add(abs(arr[i])) 33 | else: 34 | arr[idx] = -arr[idx] 35 | 36 | # Return the list to it's original state. 37 | for i in range(len(arr)): 38 | arr[i] = abs(arr[i]) 39 | 40 | return list(result_set) 41 | 42 | 43 | class TestFindDuplicates(unittest.TestCase): 44 | 45 | def test_len_1_no_dups(self): 46 | self.assertEqual(find_duplicates([1]), []) 47 | print("Length 1, no duplicates") 48 | 49 | def test_len_2_no_dups(self): 50 | self.assertEqual(find_duplicates([1, 2]), []) 51 | print("Length 2, no duplicates") 52 | 53 | def test_len_2_dups(self): 54 | self.assertEqual(find_duplicates([1, 1]), [1]) 55 | print("Length 2, duplicates") 56 | 57 | def test_len_4_no_dups(self): 58 | self.assertEqual(find_duplicates([1, 2, 3, 4]), []) 59 | print("Length 4, no duplicates") 60 | 61 | def test_len_4_one_dup(self): 62 | self.assertEqual(find_duplicates([1, 1, 2, 3]), [1]) 63 | print("Length 4, one duplicate") 64 | 65 | def test_len_4_two_dups(self): 66 | self.assertEqual(find_duplicates([1, 1, 2, 2]), [1, 2]) 67 | print("Length 4, two duplicates") 68 | 69 | def test_len_4_repeat_dups(self): 70 | self.assertEqual(find_duplicates([1, 1, 1, 1]), [1]) 71 | print("Length 4, repeated 4 times.") 72 | 73 | 74 | if __name__ == '__main__': 75 | unittest.main() 76 | -------------------------------------------------------------------------------- /python/DedupLinkedList.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Remove duplicates from linked list. 3 | 4 | Given an unsorted linked list, write a function to remove all the duplicates. 5 | 6 | Execution: python DedupLinkedList.py 7 | 8 | For more details, check out http://www.byte-by-byte.com/deduplinkedlist 9 | """ 10 | import unittest 11 | 12 | 13 | class Node: 14 | """ 15 | Node class for Linked List. 16 | """ 17 | def __init__(self, value=None): 18 | self.value = value 19 | self.next = None 20 | 21 | 22 | class LinkedList: 23 | def __init__(self): 24 | self.head = None 25 | 26 | def append(self, data): 27 | new_node = Node(data) 28 | 29 | if self.head is None: 30 | self.head = new_node 31 | return 32 | 33 | last_node = self.head 34 | while last_node.next: 35 | last_node = last_node.next 36 | last_node.next = new_node 37 | 38 | def remove_dups(self): 39 | nodes = set() 40 | 41 | prev = None 42 | node = self.head 43 | 44 | while node: 45 | if node.value in nodes: 46 | prev.next = node.next 47 | else: 48 | nodes.add(node.value) 49 | prev = node 50 | node = node.next 51 | prev.next = None 52 | 53 | 54 | class TestNthToLast(unittest.TestCase): 55 | 56 | def test_no_dups(self): 57 | ll = LinkedList() 58 | ll.append(1) 59 | ll.append(2) 60 | ll.append(3) 61 | ll.append(4) 62 | ll.append(5) 63 | 64 | ll.remove_dups() 65 | after_list = [] 66 | node = ll.head 67 | while node: 68 | after_list.append(node.value) 69 | node = node.next 70 | 71 | self.assertEqual(after_list, [1, 2, 3, 4, 5]) 72 | print("1->2->3->4->5 after removal results in 1->2->3->4->5") 73 | 74 | def test_dups(self): 75 | ll = LinkedList() 76 | ll.append(1) 77 | ll.append(2) 78 | ll.append(2) 79 | ll.append(3) 80 | ll.append(4) 81 | ll.append(5) 82 | 83 | ll.remove_dups() 84 | after_list = [] 85 | node = ll.head 86 | while node: 87 | after_list.append(node.value) 88 | node = node.next 89 | 90 | self.assertEqual(after_list, [1, 2, 3, 4, 5]) 91 | print("1->2->2->3->4->5 after removal results in 1->2->3->4->5") 92 | 93 | 94 | if __name__ == '__main__': 95 | unittest.main() 96 | 97 | -------------------------------------------------------------------------------- /java/InorderTraversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Inorder Traversal 3 | * Author: Sam Gavis-Hughson 4 | * Date: 6/16/2017 5 | * 6 | * Given a binary tree, print out the nodes in order without using 7 | * recursion. 8 | * 9 | * Execution: javac InorderTraversal.java && java InorderTraversal 10 | * 11 | * For more details, check out http://www.byte-by-byte.com/inordertraversal/ 12 | */ 13 | 14 | import java.util.Stack; 15 | 16 | public class InorderTraversal { 17 | // Tree node class 18 | public static class Node { 19 | Node left; 20 | Node right; 21 | int value; 22 | 23 | public Node(int value) { 24 | this.value = value; 25 | } 26 | } 27 | 28 | // Traverse tree iteratively. We do this by replicating the same process 29 | // done recursively using an explicit stack 30 | public static void traverse(Node n) { 31 | Stack s = new Stack(); 32 | // Add the leftmost branch to the stack 33 | addLeftToStack(s, n); 34 | 35 | // While there are elements in the stack, pop and move the minimum 36 | // possible distance to the right 37 | while (!s.isEmpty()) { 38 | Node curr = s.pop(); 39 | System.out.println(curr.value); 40 | 41 | // Add the right child and any of its left children to the stack 42 | addLeftToStack(s, curr.right); 43 | } 44 | } 45 | 46 | // As long as the current node has a left pointer, add it to the stack and 47 | // continue 48 | private static void addLeftToStack(Stack s, Node n) { 49 | while (n != null) { 50 | s.push(n); 51 | n = n.left; 52 | } 53 | } 54 | 55 | /* 56 | * Sample test case 57 | * 58 | * 8 59 | * / \ 60 | * 4 12 61 | * / \ / \ 62 | * 1 6 9 15 63 | * / \ 64 | * 5 10 65 | * 66 | * Should print: 67 | * 1 68 | * 4 69 | * 5 70 | * 6 71 | * 8 72 | * 9 73 | * 10 74 | * 12 75 | * 15 76 | */ 77 | 78 | public static void main(String[] args) { 79 | Node n = new Node(8); 80 | n.left = new Node(4); 81 | n.left.left = new Node(1); 82 | n.left.right = new Node(6); 83 | n.left.right.left = new Node(5); 84 | n.right = new Node(12); 85 | n.right.left = new Node(9); 86 | n.right.left.right = new Node(10); 87 | n.right.right = new Node(15); 88 | traverse(n); 89 | } 90 | } -------------------------------------------------------------------------------- /python/RandomLinkedList.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Title: Remove duplicates from linked list. 4 | 5 | Given an unsorted linked list, write a function to remove all the duplicates. 6 | 7 | Execution: python DedupLinkedList.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/deduplinkedlist 10 | """ 11 | import unittest 12 | 13 | 14 | class Node: 15 | """ 16 | Node class for Linked List. 17 | """ 18 | def __init__(self, value=None): 19 | self.value = value 20 | self.next = None 21 | 22 | 23 | class LinkedList: 24 | def __init__(self): 25 | self.head = None 26 | 27 | def append(self, data): 28 | new_node = Node(data) 29 | 30 | if self.head is None: 31 | self.head = new_node 32 | return 33 | 34 | last_node = self.head 35 | while last_node.next: 36 | last_node = last_node.next 37 | last_node.next = new_node 38 | 39 | def remove_dups(self): 40 | nodes = set() 41 | 42 | prev = None 43 | node = self.head 44 | 45 | while node: 46 | if node.value in nodes: 47 | prev.next = node.next 48 | else: 49 | nodes.add(node.value) 50 | prev = node 51 | node = node.next 52 | prev.next = None 53 | 54 | 55 | class TestNthToLast(unittest.TestCase): 56 | 57 | def test_no_dups(self): 58 | ll = LinkedList() 59 | ll.append(1) 60 | ll.append(2) 61 | ll.append(3) 62 | ll.append(4) 63 | ll.append(5) 64 | 65 | ll.remove_dups() 66 | after_list = [] 67 | node = ll.head 68 | while node: 69 | after_list.append(node.value) 70 | node = node.next 71 | 72 | self.assertEqual(after_list, [1, 2, 3, 4, 5]) 73 | print("1->2->3->4->5 after removal results in 1->2->3->4->5") 74 | 75 | def test_dups(self): 76 | ll = LinkedList() 77 | ll.append(1) 78 | ll.append(2) 79 | ll.append(2) 80 | ll.append(3) 81 | ll.append(4) 82 | ll.append(5) 83 | 84 | ll.remove_dups() 85 | after_list = [] 86 | node = ll.head 87 | while node: 88 | after_list.append(node.value) 89 | node = node.next 90 | 91 | self.assertEqual(after_list, [1, 2, 3, 4, 5]) 92 | print("1->2->2->3->4->5 after removal results in 1->2->3->4->5") 93 | 94 | 95 | if __name__ == '__main__': 96 | unittest.main() 97 | 98 | -------------------------------------------------------------------------------- /python/TwoMissingNumbers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Two missing 3 | 4 | Given an array containing all the numbers from 1 to n except two, 5 | find the two missing numbers. 6 | 7 | Execution: python TwoMissing.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/twomissing 10 | """ 11 | 12 | 13 | import unittest 14 | 15 | 16 | def oneMissing(arr): 17 | totalXor = 0 18 | arrXor = 0 19 | 20 | # XOR the numbers from 1 to N, ie. the input if no numbers were missing 21 | for i in range(1, len(arr)+2): 22 | totalXor = totalXor ^ i 23 | 24 | # XOR the array 25 | for i in range(len(arr)): 26 | arrXor = arrXor ^ arr[i] 27 | 28 | return totalXor ^ arrXor 29 | 30 | 31 | def twoMissing(arr): 32 | size = len(arr) + 2 33 | totalSum = size * (size + 1)//2 # we want only the integer portion 34 | arrSum = 0 35 | 36 | for i in range(len(arr)): 37 | arrSum += arr[i] 38 | 39 | pivot = (totalSum - arrSum) // 2 # we want only the integer portion 40 | 41 | totalLeftXor = 0 42 | arrLeftXor = 0 43 | totalRightXor = 0 44 | arrRightXor = 0 45 | 46 | for i in range(1, pivot+1): 47 | totalLeftXor ^= i 48 | 49 | for i in range(pivot+1, size+1): 50 | totalRightXor ^= i 51 | 52 | for i in range(len(arr)): 53 | if (arr[i] <= pivot): 54 | arrLeftXor ^= arr[i] 55 | else: 56 | arrRightXor ^= arr[i] 57 | 58 | return (totalLeftXor ^ arrLeftXor, totalRightXor ^ arrRightXor) 59 | 60 | 61 | class TestMissingNumbers(unittest.TestCase): 62 | 63 | def test_oneMissing(self): 64 | # oneMissing tests 65 | self.assertEqual(oneMissing([1, 2, 4, 5]), 3) 66 | print "oneMissing: Normal case" 67 | self.assertEqual(oneMissing([3, 2, 5, 4]), 1) 68 | print "oneMissing: Missing first element" 69 | self.assertEqual(oneMissing([4, 3, 2, 1]), 5) 70 | print "oneMissing: Missing last element" 71 | print "Passed all oneMissing test cases" 72 | 73 | def test_twoMissing(self): 74 | # twomissing tests 75 | self.assertEqual(twoMissing([1, 3, 5]), (2, 4)) 76 | print "\ntwoMissing: Normal case" 77 | self.assertEqual(twoMissing([2, 4, 5]), (1, 3)) 78 | print "twoMissing: Missing first element" 79 | self.assertEqual(twoMissing([3, 1, 2]), (4, 5)) 80 | print "twoMissing: Missing last two elements" 81 | print "Passed all twoMissing test cases" 82 | 83 | 84 | if __name__ == '__main__': 85 | unittest.main() 86 | -------------------------------------------------------------------------------- /java/SmallestChange.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Smallest Change 3 | * 4 | * Given an input amount of change x, write a function to determine the 5 | * minimum number of coins required to make that amount of change. 6 | 7 | * Execution: javac SmallestChange.java && java SmallestChange 8 | 9 | * For more details, check out http://www.byte-by-byte.com/smallestchange 10 | */ 11 | 12 | public class SmallestChange { 13 | public static int change(int x, int[] coins) { 14 | if (x == 0) { 15 | return 0; 16 | } 17 | int min = x; 18 | for (int coin : coins) { 19 | if (x - coin >= 0) { 20 | int c = change(x - coin, coins); 21 | if (min > c + 1) { 22 | min = c + 1; 23 | } 24 | } 25 | } 26 | return min; 27 | } 28 | 29 | public static int changeDynamic(int x, int[] coins) { 30 | int[] cache = new int[x]; 31 | for (int i = 1; i < x; i++) { 32 | cache[i] = -1; 33 | } 34 | return changeDynamic(x, coins, cache); 35 | } 36 | 37 | public static int changeDynamic(int x, int[] coins, int[] cache) { 38 | if (x == 0) { 39 | return 0; 40 | } 41 | int min = x; 42 | for (int coin : coins) { 43 | if (x - coin >= 0) { 44 | int c; 45 | if (cache[x - coin] >= 0) { 46 | c = cache[x - coin]; 47 | } else { 48 | c = changeDynamic(x - coin, coins, cache); 49 | cache[x - coin] = c; 50 | } 51 | if (min > c + 1) { 52 | min = c + 1; 53 | } 54 | } 55 | } 56 | return min; 57 | } 58 | 59 | // Sample test cases 60 | public static void main(String[] args) { 61 | int[] coins = new int[]{1, 5, 10, 25}; 62 | 63 | // Tests for change: 64 | assert change(1, coins) == 1: 65 | "Smallest from 1 is 1"; 66 | 67 | assert change(3, coins) == 3: 68 | "Smallest from 3 is 3"; 69 | 70 | assert change(7, coins) == 3: 71 | "Smallest from 7 is 3"; 72 | 73 | assert change(32, coins) == 4: 74 | "Smallest from 32 is 4"; 75 | 76 | // Tests for changeDynamic: 77 | assert changeDynamic(1, coins) == 1: 78 | "Smallest from 1 is 1"; 79 | 80 | assert changeDynamic(3, coins) == 3: 81 | "Smallest from 3 is 3"; 82 | 83 | assert changeDynamic(7, coins) == 3: 84 | "Smallest from 7 is 3"; 85 | 86 | assert changeDynamic(32, coins) == 4: 87 | "Smallest from 32 is 4"; 88 | 89 | System.out.println("Passed all test cases"); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /python/ZeroMatrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Zero Matrix 3 | 4 | Given a boolean matrix, update it so that if any cell is true, all the rows 5 | in that cell are true. 6 | 7 | eg. 8 | [true, false, false] [true, true, true ] 9 | [false, false, false] -> [true, false, false] 10 | [false, false, false] [true, false, false] 11 | 12 | Execution: python ZeroMatrix.py 13 | 14 | For more details, check out http://www.byte-by-byte.com/zeromatrix/ 15 | """ 16 | import unittest 17 | 18 | 19 | def zero_matrix(mat): 20 | row_flag = False 21 | col_flag = False 22 | 23 | for i in range(len(mat)): 24 | for j in range(len(mat)): 25 | if i == 0 and mat[i][j]: 26 | row_flag = True 27 | if j == 0 and mat[i][j]: 28 | col_flag = True 29 | if mat[i][j]: 30 | mat[0][j] = True 31 | mat[i][0] = True 32 | for i in range(1, len(mat)): 33 | for j in range(1, len(mat)): 34 | if mat[0][j] or mat[i][0]: 35 | mat[i][j] = True 36 | if row_flag: 37 | for i in range(len(mat)): 38 | mat[0][i] = True 39 | if col_flag: 40 | for i in range(len(mat)): 41 | mat[i][0] = True 42 | return mat 43 | 44 | 45 | class TestBigIntMod(unittest.TestCase): 46 | def test_first_row_first_col(self): 47 | A = [[True, False, False], 48 | [False, False, False], 49 | [False, False, False]] 50 | 51 | B = [[True, True, True], 52 | [True, False, False], 53 | [True, False, False]] 54 | 55 | self.assertEqual(zero_matrix(A), B) 56 | print("First row and first column") 57 | 58 | def test_all_false(self): 59 | A = [[False, False, False], 60 | [False, False, False], 61 | [False, False, False]] 62 | 63 | B = [[False, False, False], 64 | [False, False, False], 65 | [False, False, False]] 66 | 67 | self.assertEqual(zero_matrix(A), B) 68 | print("All false.") 69 | 70 | def test_all_true(self): 71 | A = [[True, True, True], 72 | [True, True, True], 73 | [True, True, True]] 74 | 75 | B = [[True, True, True], 76 | [True, True, True], 77 | [True, True, True]] 78 | 79 | self.assertEqual(zero_matrix(A), B) 80 | print("All true.") 81 | 82 | def test_multiple_true(self): 83 | A = [[True, False, False], 84 | [False, False, False], 85 | [False, False, True]] 86 | 87 | B = [[True, True, True], 88 | [True, False, True], 89 | [True, True, True]] 90 | 91 | self.assertEqual(zero_matrix(A), B) 92 | print("Multiple true.") 93 | 94 | 95 | if __name__ == '__main__': 96 | unittest.main() 97 | 98 | -------------------------------------------------------------------------------- /cpp/ReverseStack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Reverse Stack 3 | * 4 | * Execution: g++ ReverseStack.cpp -o ReverseStack 5 | * 6 | * For more details, check out http://www.byte-by-byte.com/reversestack 7 | */ 8 | 9 | #include 10 | #include 11 | 12 | using namespace std; 13 | 14 | void insertAtBottom(stack s, int x) { 15 | if (s.empty()) { 16 | s.push(x); 17 | return; 18 | } 19 | int temp = s.top(); 20 | s.pop(); 21 | insertAtBottom(s, x); 22 | s.push(temp); 23 | } 24 | 25 | stack reverse(stack s) { 26 | if (s.empty()) { 27 | return s; 28 | } 29 | int temp = s.top(); 30 | s.pop(); 31 | reverse(s); 32 | insertAtBottom(s, temp); 33 | return s; 34 | } 35 | 36 | bool check_stack_equal(stack s1, stack s2) { 37 | if (s1.size() != s2.size()) { 38 | return false; 39 | } 40 | int len = s1.size(); 41 | while(!s1.empty()) { 42 | if (s1.top() != s2.top()) { 43 | return false; 44 | } 45 | s1.pop(); 46 | s2.pop(); 47 | } 48 | return true; 49 | } 50 | 51 | void test_1() { 52 | stack s; 53 | s.push(1); 54 | s.push(2); 55 | s.push(3); 56 | s.push(0); 57 | 58 | stack s1 = reverse(s); 59 | 60 | stack s2; 61 | s2.push(1); 62 | s2.push(2); 63 | s2.push(3); 64 | 65 | if (check_stack_equal(s1, s2)) { 66 | cout << "Test 1 passed" << endl; 67 | cout << "reverse(1->2->3) = 3->2->1" << endl; 68 | } else { 69 | cout << "Test 1 failed" << endl; 70 | } 71 | } 72 | void test_2() { 73 | stack s; 74 | s.push(5); 75 | s.push(6); 76 | s.push(10); 77 | s.push(11); 78 | s.push(60); 79 | s.push(50); 80 | s.push(0); 81 | 82 | stack s1 = reverse(s); 83 | 84 | stack s2; 85 | s2.push(5); 86 | s2.push(6); 87 | s2.push(10); 88 | s2.push(11); 89 | s2.push(60); 90 | s2.push(50); 91 | 92 | if (check_stack_equal(s1, s2)) { 93 | cout << "Test 2 passed" << endl; 94 | cout << "reverse(5->6->10->11->60->50) = 50->60->11->10->6->5" << endl; 95 | } else { 96 | cout << "Test 2 failed" << endl; 97 | } 98 | } 99 | 100 | void test_3() { 101 | stack s; 102 | s.push(3); 103 | s.push(2); 104 | s.push(1); 105 | s.push(0); 106 | 107 | stack s1 = reverse(s); 108 | 109 | stack s2; 110 | s2.push(3); 111 | s2.push(2); 112 | s2.push(1); 113 | 114 | if (check_stack_equal(s1, s2)) { 115 | cout << "Test 3 passed" << endl; 116 | cout << "reverse(3->2->1) = 1->2->3" << endl; 117 | } else { 118 | cout << "Test 3 failed" << endl; 119 | } 120 | 121 | } 122 | 123 | int main() { 124 | test_1(); 125 | test_2(); 126 | test_3(); 127 | 128 | return 0; 129 | } 130 | -------------------------------------------------------------------------------- /python/SmallestChange.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Smallest change 3 | 4 | Given an input amount of change x, write a function to determine the 5 | minimum number of coins required to make that amount of change. 6 | 7 | Execution: python SmallestChange.py 8 | 9 | For more details, check out http://www.byte-by-byte.com/smallestchange/ 10 | """ 11 | import unittest 12 | 13 | 14 | def change(x: int, coins: list): 15 | if x == 0: 16 | return 0 17 | min_val = x 18 | for coin in coins: 19 | if x - coin >= 0: 20 | c = change(x-coin, coins) 21 | if min_val > c + 1: 22 | min_val = c + 1 23 | return min_val 24 | 25 | 26 | def change_dynamic(x: int, coins: list): 27 | cache = [0] * x 28 | for i in range(1, x): 29 | cache[i] = -1 30 | return change_dynamic_recur(x, coins, cache) 31 | 32 | 33 | def change_dynamic_recur(x: int, coins: list, cache: list): 34 | if x == 0: 35 | return 0 36 | min_val = x 37 | for coin in coins: 38 | if x - coin >= 0: 39 | if cache[x - coin] >= 0: 40 | c = cache[x - coin] 41 | else: 42 | c = change_dynamic_recur(x - coin, coins, cache) 43 | cache[x-coin] = c 44 | if min_val > c + 1: 45 | min_val = c + 1 46 | return min_val 47 | 48 | 49 | class TestChange(unittest.TestCase): 50 | 51 | # Tests for change function (no dynamic programming): 52 | def test_change_1(self): 53 | coins = [1, 5, 10, 25] 54 | self.assertEqual(change(1, coins), 1) 55 | print("Smallest from 1 is 1") 56 | 57 | def test_change_3(self): 58 | coins = [1, 5, 10, 25] 59 | self.assertEqual(change(3, coins), 3) 60 | print("Smallest from 3 is 3") 61 | 62 | def test_change_7(self): 63 | coins = [1, 5, 10, 25] 64 | self.assertEqual(change(7, coins), 3) 65 | print("Smallest from 7 is 3") 66 | 67 | def test_change_32(self): 68 | coins = [1, 5, 10, 25] 69 | self.assertEqual(change(32, coins), 4) 70 | print("Smallest from 32 is 4") 71 | 72 | # Tests for change_dynamic (dynamic programming): 73 | def test_change_dynamic_1(self): 74 | coins = [1, 5, 10, 25] 75 | self.assertEqual(change_dynamic(1, coins), 1) 76 | print("Smallest from 1 is 1") 77 | 78 | def test_change_dynamic_3(self): 79 | coins = [1, 5, 10, 25] 80 | self.assertEqual(change_dynamic(3, coins), 3) 81 | print("Smallest from 3 is 3") 82 | 83 | def test_change_dynamic_7(self): 84 | coins = [1, 5, 10, 25] 85 | self.assertEqual(change_dynamic(7, coins), 3) 86 | print("Smallest from 7 is 3") 87 | 88 | def test_change_dynamic_32(self): 89 | coins = [1, 5, 10, 25] 90 | self.assertEqual(change_dynamic(32, coins), 4) 91 | print("Smallest from 32 is 4") 92 | 93 | 94 | if __name__ == '__main__': 95 | unittest.main() 96 | -------------------------------------------------------------------------------- /java/MatrixProduct.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Matrix Product 3 | * Author: Sam Gavis-Hughson 4 | * Date: 8/28/2016 5 | * 6 | * Given a matrix, find the path from top left to bottom right with the greatest 7 | * product by moving only down and right. 8 | * 9 | * Execution: javac MatrixProduct.java && java MatrixProduct 10 | * 11 | * For more details, check out http://www.byte-by-byte.com/matrixproduct/ 12 | */ 13 | 14 | public class MatrixProduct { 15 | // Bottom up dynamic programming solution 16 | public static int matrixProduct(int[][] matrix) { 17 | if (matrix.length == 0 || matrix[0].length == 0) return 0; 18 | 19 | // Create cache of min and max product to a given cell 20 | int[][] maxCache = new int[matrix.length][matrix[0].length]; 21 | int[][] minCache = new int[matrix.length][matrix[0].length]; 22 | 23 | // Fill caches. We start at the top left and iteratively find the greatest 24 | // at smallest path to each subsequent cell by considering the greatest and 25 | // smallest path to the cells above and to the left of the current cell 26 | for (int i = 0; i < matrix.length; i++) { 27 | for (int j = 0; j < matrix[0].length; j++) { 28 | int maxVal = Integer.MIN_VALUE; 29 | int minVal = Integer.MAX_VALUE; 30 | 31 | // If you're in the top left corner, just copy to cache 32 | if (i == 0 && j == 0) { 33 | maxVal = matrix[i][j]; 34 | minVal = matrix[i][j]; 35 | } 36 | 37 | // If we're not at the top, consider the value above 38 | if (i > 0) { 39 | int tempMax = Math.max(matrix[i][j] * maxCache[i-1][j], matrix[i][j] * minCache[i-1][j]); 40 | maxVal = Math.max(tempMax, maxVal); 41 | int tempMin = Math.min(matrix[i][j] * maxCache[i-1][j], matrix[i][j] * minCache[i-1][j]); 42 | minVal = Math.min(tempMin, minVal); 43 | } 44 | 45 | // If we're not on the left, consider the value to the left 46 | if (j > 0) { 47 | int tempMax = Math.max(matrix[i][j] * maxCache[i][j-1], matrix[i][j] * minCache[i][j-1]); 48 | maxVal = Math.max(tempMax, maxVal); 49 | int tempMin = Math.min(matrix[i][j] * maxCache[i][j-1], matrix[i][j] * minCache[i][j-1]); 50 | minVal = Math.min(tempMin, minVal); 51 | } 52 | maxCache[i][j] = maxVal; 53 | minCache[i][j] = minVal; 54 | } 55 | } 56 | 57 | // Return the max value at the bottom right 58 | return maxCache[maxCache.length - 1][maxCache[0].length - 1]; 59 | } 60 | 61 | // Sample test cases 62 | public static void main(String[] args) { 63 | assert matrixProduct(new int[][]{{1,2,3}, {4, 5, 6}, {7, 8, 9}}) == 2016; 64 | assert matrixProduct(new int[][]{{-1,2,3}, {4, 5, 6}, {7, 8, 9}}) == -324; 65 | assert matrixProduct(new int[][]{{-1,2,3}, {4, 5, -6}, {7, 8, 9}}) == 1080; 66 | 67 | System.out.println("Passed all tests"); 68 | } 69 | } -------------------------------------------------------------------------------- /python/LinkedListCycle.py: -------------------------------------------------------------------------------- 1 | # /usr/bin/python2.7 2 | 3 | # Converting Sam's Java code to Python 4 | 5 | import unittest 6 | 7 | 8 | class Node (object): 9 | def __init__(self, value=0): 10 | self.value = value 11 | self.next = None 12 | 13 | 14 | # Algorithm using extra space. Mark visited nodes and check that you 15 | # only visit each node once. 16 | def hasCycle(node): 17 | visited = set() 18 | current = node 19 | 20 | while current is not None: 21 | if current in visited: 22 | return True 23 | else: 24 | visited.add(current) 25 | current = current.next 26 | 27 | return False 28 | 29 | 30 | # Floyd's algorithm. Increment one pointer by one and the other by two. 31 | # If they are ever pointing to the same node, there is a cycle. 32 | # Explanation is at: 33 | # https://www.quora.com/How-does-Floyds-cycle-finding-algorithm-work 34 | def hasCycleFloyd(node): 35 | 36 | if node is None: 37 | return False 38 | slow = node 39 | fast = node.next 40 | 41 | while fast is not None and fast.next is not None: 42 | if (fast == slow): 43 | return True 44 | 45 | fast = fast.next.next 46 | slow = slow.next 47 | 48 | return False 49 | 50 | 51 | class TestCycle(unittest.TestCase): 52 | 53 | def test_hasCycle(self): 54 | self.assertEqual(hasCycle(None), False) 55 | print "Marking visited: Null input" 56 | n = Node() 57 | self.assertEqual(hasCycle(n), False) 58 | print "Marking visited: Single node" 59 | n.next = n 60 | self.assertEqual(hasCycle(n), True) 61 | print "Marking visited: Single node cycle" 62 | n.next = Node() 63 | self.assertEqual(hasCycle(n), False) 64 | print "Marking visited: Multinode list" 65 | n.next.next = n 66 | self.assertEqual(hasCycle(n), True) 67 | print "Marking visited: Even length cycle" 68 | n.next.next = Node() 69 | n.next.next.next = Node() 70 | n.next.next.next.next = n.next 71 | self.assertEqual(hasCycle(n), True) 72 | print "Marking visited: Odd length cycle" 73 | 74 | def test_hasCycleFlyod(self): 75 | self.assertEqual(hasCycleFloyd(None), False) 76 | print "\nMarking visited: Null input" 77 | n = Node() 78 | self.assertEqual(hasCycleFloyd(n), False) 79 | print "Marking visited: Single node" 80 | n.next = n 81 | self.assertEqual(hasCycleFloyd(n), True) 82 | print "Marking visited: Single node cycle" 83 | n.next = Node() 84 | self.assertEqual(hasCycleFloyd(n), False) 85 | print "Marking visited: Multinode list" 86 | n.next.next = n 87 | self.assertEqual(hasCycleFloyd(n), True) 88 | print "Marking visited: Even length cycle" 89 | n.next.next = Node() 90 | n.next.next.next = Node() 91 | n.next.next.next.next = n.next 92 | self.assertEqual(hasCycleFloyd(n), True) 93 | print "Marking visited: Odd length cycle" 94 | 95 | print "Passed all test cases" 96 | 97 | 98 | if __name__ == '__main__': 99 | unittest.main() 100 | -------------------------------------------------------------------------------- /cpp/FindDuplicates.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Find Duplicates 3 | * Given an array of integers where each value 1 <= x <= len(array), write a 4 | * function that finds all the duplicates in the array. 5 | * 6 | * Execution: python FindDuplicates.py 7 | * Execution: g++ Findduplicates.cpp -o Findduplicates 8 | * 9 | * For more details, check out http://www.byte-by-byte.com/findduplicates/ 10 | * 11 | */ 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | vector findDuplicates(vector arr) { 19 | vector result_set; 20 | 21 | for(int i = 0; i < arr.size(); i++) { 22 | int idx = abs(arr[i]) - 1; 23 | 24 | if (arr[idx] < 0) { 25 | result_set.push_back(abs(arr[i])); 26 | } else { 27 | arr[idx] = -arr[idx]; 28 | } 29 | } 30 | for (int i = 0; i < arr.size(); i++) { 31 | arr[i] = abs(arr[i]); 32 | } 33 | sort( result_set.begin(), result_set.end() ); 34 | result_set.erase( unique( result_set.begin(), result_set.end() ), result_set.end() ); 35 | return result_set; 36 | } 37 | 38 | bool areVectorsEqual(vector vec_1, vector vec_2) { 39 | if (vec_1.size() != vec_2.size()) { 40 | return false; 41 | } 42 | std::sort(vec_1.begin(), vec_1.end()); 43 | std::sort(vec_2.begin(), vec_2.end()); 44 | 45 | for (int i = 0; i < vec_1.size(); i++) { 46 | if (vec_1[i] != vec_2[i]) { 47 | return false; 48 | } 49 | } 50 | return true; 51 | } 52 | 53 | void test_1() { 54 | cout << "Running Test 1 on [1,2,3,1]" << endl; 55 | vector test_1; 56 | test_1.push_back(1); 57 | test_1.push_back(2); 58 | test_1.push_back(3); 59 | test_1.push_back(1); 60 | 61 | vector dups_test_1 = findDuplicates(test_1); 62 | 63 | vector expected_test_1; 64 | expected_test_1.push_back(1); 65 | 66 | if (areVectorsEqual(dups_test_1, expected_test_1)) { 67 | cout << "Test 1 passed." << endl; 68 | } else { 69 | cout << "Test 1 failed." << endl; 70 | } 71 | } 72 | 73 | void test_2() { 74 | cout << "Running Test 2 on [1,1,1,1]" << endl; 75 | vector test_2; 76 | test_2.push_back(1); 77 | test_2.push_back(1); 78 | test_2.push_back(1); 79 | test_2.push_back(1); 80 | 81 | vector dups_test_2 = findDuplicates(test_2); 82 | 83 | vector expected_test_2; 84 | expected_test_2.push_back(1); 85 | 86 | if (areVectorsEqual(dups_test_2, expected_test_2)) { 87 | cout << "Test 2 passed." << endl; 88 | } else { 89 | cout << "Test 2 failed." << endl; 90 | } 91 | } 92 | 93 | void test_3() { 94 | cout << "Running Test 3 on [5,4,3,2]" << endl; 95 | vector test_3; 96 | test_3.push_back(5); 97 | test_3.push_back(4); 98 | test_3.push_back(3); 99 | test_3.push_back(2); 100 | 101 | vector dups_test_3 = findDuplicates(test_3); 102 | 103 | vector expected_test_3; 104 | 105 | if (areVectorsEqual(dups_test_3, expected_test_3)) { 106 | cout << "Test 3 passed." << endl; 107 | } else { 108 | cout << "Test 3 failed." << endl; 109 | } 110 | } 111 | int main() { 112 | 113 | test_1(); 114 | test_2(); 115 | test_3(); 116 | 117 | return 0; 118 | } 119 | -------------------------------------------------------------------------------- /java/LinkedListCycle.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Linked List Cycle 3 | * Author: Sam Gavis-Hughson 4 | * Date: 11/3/2016 5 | * 6 | * Given a linked list, determine whether it contains any cycles. 7 | * 8 | * Execution: javac LinkedListCycle.java && java LinkedListCycle 9 | * 10 | * For more details, check out http://www.byte-by-byte.com/listcycles/ 11 | */ 12 | 13 | import java.util.HashSet; 14 | 15 | public class LinkedListCycle { 16 | private static class Node{ 17 | int val; 18 | Node next; 19 | } 20 | 21 | // Algorithm using extra space. Mark visited nodes and check that you 22 | // only visit each node once. 23 | public static boolean hasCycle(Node n) { 24 | HashSet visited = new HashSet(); 25 | for (Node curr = n; curr != null; curr = curr.next) { 26 | if (visited.contains(curr)) return true; 27 | visited.add(curr); 28 | } 29 | 30 | return false; 31 | } 32 | 33 | // Floyd's algorithm. Increment one pointer by one and the other by two. 34 | // If they are ever pointing to the same node, there is a cycle. 35 | // Explanation: https://www.quora.com/How-does-Floyds-cycle-finding-algorithm-work 36 | public static boolean hasCycleFloyd(Node n) { 37 | if (n == null) return false; 38 | Node slow = n; 39 | Node fast = n.next; 40 | 41 | while (fast != null && fast.next != null) { 42 | if (fast == slow) return true; 43 | fast = fast.next.next; 44 | slow = slow.next; 45 | } 46 | 47 | return false; 48 | } 49 | 50 | // Sample test cases 51 | public static void main(String[] args) { 52 | // Test marking visited implementation 53 | assert hasCycle(null) == false: 54 | "Marking visited: Null input"; 55 | Node n = new Node(); 56 | assert hasCycle(n) == false: 57 | "Marking visited: Single node"; 58 | n.next = n; 59 | assert hasCycle(n) == true: 60 | "Marking visited: Single node cycle"; 61 | n.next = new Node(); 62 | assert hasCycle(n) == false: 63 | "Marking visited: Multinode list"; 64 | n.next.next = n; 65 | assert hasCycle(n) == true: 66 | "Marking visited: Even length cycle"; 67 | n.next.next = new Node(); 68 | n.next.next.next = new Node(); 69 | n.next.next.next.next = n.next; 70 | assert hasCycle(n) == true: 71 | "Marking visited: Odd length cycle"; 72 | 73 | // Test Floyd's algorithm implementation 74 | assert hasCycleFloyd(null) == false: 75 | "Floyd: Null input"; 76 | n = new Node(); 77 | assert hasCycleFloyd(n) == false: 78 | "Floyd: Single node"; 79 | n.next = n; 80 | assert hasCycleFloyd(n) == true: 81 | "Floyd: Single node cycle"; 82 | n.next = new Node(); 83 | assert hasCycleFloyd(n) == false: 84 | "Floyd: Multinode list"; 85 | n.next.next = n; 86 | assert hasCycleFloyd(n) == true: 87 | "Floyd: Even length cycle"; 88 | n.next.next = new Node(); 89 | n.next.next.next = new Node(); 90 | n.next.next.next.next = n.next; 91 | assert hasCycleFloyd(n) == true: 92 | "Floyd: Odd length cycle"; 93 | 94 | System.out.println("Passed all test cases"); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /java/FindDuplicates.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Find Duplicates 3 | * Author: Sam Gavis-Hughson 4 | * Date: 2/20/2017 5 | * 6 | * Given an array of integers where each value 1 <= x <= len(array), write a 7 | * function that finds all the duplicates in the array. 8 | * 9 | * Execution: javac FindDuplicates.java && java FindDuplicates 10 | * 11 | * For more details, check out http://www.byte-by-byte.com/findduplicates/ 12 | */ 13 | 14 | import java.util.ArrayList; 15 | import java.util.Arrays; 16 | import java.util.Collections; 17 | import java.util.HashSet; 18 | import java.util.List; 19 | import java.util.Set; 20 | 21 | public class FindDuplicates { 22 | 23 | // Return a list of duplicates in the array. To avoid using extra space, 24 | // we flag which elements we've seen before by negating the value at 25 | // indexed at that value in the array. 26 | public static List findDuplicates(int[] arr) { 27 | // Use a set for results to avoid duplicates 28 | Set resultSet = new HashSet(); 29 | 30 | for (int i = 0; i < arr.length; i++) { 31 | // Translate the value into an index (1 <= x <= len(arr)) 32 | int index = Math.abs(arr[i]) - 1; 33 | 34 | // If the value at that index is negative, then we've already seen 35 | // that value so it's a duplicate. Otherwise, negate the value at 36 | // that index so we know we've seen it 37 | if (arr[index] < 0) { 38 | resultSet.add(Math.abs(arr[i])); 39 | } else { 40 | arr[index] = -arr[index]; 41 | } 42 | } 43 | 44 | // Return the array to it's original state 45 | for (int i = 0; i < arr.length; i++) { 46 | arr[i] = Math.abs(arr[i]); 47 | } 48 | 49 | return new ArrayList(resultSet); 50 | } 51 | 52 | // Sample test cases 53 | public static void main(String[] args) { 54 | assert compareArrayAndListValues(findDuplicates(new int[]{1}), new int[]{}): 55 | "Length 1, no duplicates"; 56 | assert compareArrayAndListValues(findDuplicates(new int[]{1, 2}), new int[]{}): 57 | "Length 2, no duplicates"; 58 | assert compareArrayAndListValues(findDuplicates(new int[]{1, 1}), new int[]{1}): 59 | "Length 2, duplicates"; 60 | assert compareArrayAndListValues(findDuplicates(new int[]{1, 2, 3, 4}), new int[]{}): 61 | "Length 4, no duplicates"; 62 | assert compareArrayAndListValues(findDuplicates(new int[]{1, 1, 2, 3}), new int[]{1}): 63 | "Length 4, one duplicate"; 64 | assert compareArrayAndListValues(findDuplicates(new int[]{1, 1, 2, 2}), new int[]{1, 2}): 65 | "Length 4, two duplicates"; 66 | assert compareArrayAndListValues(findDuplicates(new int[]{1, 1, 1, 1}), new int[]{1}): 67 | "Length 4, repeated 4 times"; 68 | 69 | System.out.println("Passed all test cases"); 70 | } 71 | 72 | // Compare the values in an integer list with the values in an int array 73 | private static boolean compareArrayAndListValues(List l, int[] a) { 74 | Arrays.sort(a); 75 | Collections.sort(l); 76 | 77 | if (l.size() != a.length) return false; 78 | for (int i = 0; i < l.size(); i++) { 79 | if (l.get(i) != a[i]) return false; 80 | } 81 | 82 | return true; 83 | } 84 | } -------------------------------------------------------------------------------- /java/DedupLinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Remove duplicates of linked list 3 | * 4 | * Given an unsorted linked list, write a function to remove all the duplicates. 5 | * 6 | * Execution: javac DedupLinkedList.java && java DedupLinkedList 7 | * 8 | * For more details, check out http://www.byte-by-byte.com/deduplinkedlist 9 | */ 10 | import java.util.HashSet; 11 | import java.util.List; 12 | import java.util.ArrayList; 13 | import java.util.Arrays; 14 | import java.util.stream.Collectors; 15 | 16 | 17 | public class DedupLinkedList { 18 | // Private node class 19 | private static class Node { 20 | private int value; 21 | private Node next; 22 | 23 | private Node(int value) { 24 | this.value = value; 25 | } 26 | } 27 | 28 | public static List printList(Node n) { 29 | List list = new ArrayList<>(); 30 | while (n != null) { 31 | list.add(n.value); 32 | n = n.next; 33 | } 34 | return list; 35 | } 36 | 37 | public static void removeDups(Node n) { 38 | HashSet nodes = new HashSet(); 39 | Node prev = null; 40 | 41 | while (n != null) { 42 | if (nodes.contains(n.value)) { 43 | prev.next = n.next; 44 | } else { 45 | nodes.add(n.value); 46 | prev = n; 47 | } 48 | n = n.next; 49 | } 50 | prev.next = null; 51 | } 52 | 53 | // Sample test cases 54 | public static void main(String[] args) { 55 | 56 | // Test 1 duplicate: 57 | Node n = new Node(1); 58 | n.next = new Node(2); 59 | n.next.next = new Node(3); 60 | n.next.next.next = new Node(4); 61 | n.next.next.next.next = new Node(4); 62 | 63 | removeDups(n); 64 | List l1 = printList(n); 65 | int[] ints = {1,2,3,4}; 66 | List l2 = Arrays.stream(ints).boxed().collect(Collectors.toList()); 67 | 68 | if (l1.equals(l2)) 69 | System.out.println("Test with 1 duplicate passed."); 70 | else 71 | System.out.println("Test with 1 duplicate failed"); 72 | 73 | // Test 2 duplicates 74 | Node n2 = new Node(1); 75 | n2.next = new Node(1); 76 | n2.next.next = new Node(2); 77 | n2.next.next.next = new Node(2); 78 | n2.next.next.next.next = new Node(3); 79 | 80 | removeDups(n2); 81 | List l1_2 = printList(n2); 82 | int[] ints2 = {1,2,3}; 83 | List l2_2 = Arrays.stream(ints2).boxed().collect(Collectors.toList()); 84 | 85 | if (l1_2.equals(l2_2)) 86 | System.out.println("Test with 2 duplicates passed."); 87 | else 88 | System.out.println("Test with 2 duplicates failed."); 89 | 90 | // Test no duplicates 91 | Node n3 = new Node(1); 92 | n3.next = new Node(2); 93 | n3.next.next = new Node(3); 94 | n3.next.next.next = new Node(4); 95 | n3.next.next.next.next = new Node(5); 96 | 97 | removeDups(n3); 98 | List l1_3 = printList(n3); 99 | int[] ints3 = {1,2,3,4,5}; 100 | List l2_3 = Arrays.stream(ints3).boxed().collect(Collectors.toList()); 101 | 102 | if (l1_3.equals(l2_3)) 103 | System.out.println("Test with no duplicates passed."); 104 | else 105 | System.out.println("Test with no duplicates failed."); 106 | 107 | 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /python/NthToLast.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Nth-to-last Linked List Element 3 | 4 | Given a linked list, find the nth-to-last value in the list. 5 | 6 | Execution: python NthToLast.py 7 | 8 | For more details, check out http://www.byte-by-byte.com/nthtolastelement/ 9 | """ 10 | import unittest 11 | 12 | 13 | class Node: 14 | """ 15 | Node class for Linked List. 16 | """ 17 | def __init__(self, value=None): 18 | self.value = value 19 | self.next = None 20 | 21 | 22 | class LinkedList: 23 | def __init__(self): 24 | self.head = None 25 | 26 | def append(self, data): 27 | new_node = Node(data) 28 | 29 | if self.head is None: 30 | self.head = new_node 31 | return 32 | 33 | last_node = self.head 34 | while last_node.next: 35 | last_node = last_node.next 36 | last_node.next = new_node 37 | 38 | def nth_to_last(self, n): 39 | curr = self.head 40 | follower = self.head 41 | 42 | # Iterate curr forward by n. If you reach the end of the list then it is 43 | # shorter than n, so you can't possibly have an nth-to-last node. 44 | for i in range(n): 45 | if curr is None: 46 | return None 47 | curr = curr.next 48 | 49 | # If length is exactly n, the n-th-to-last node would be null. 50 | if curr is None: 51 | return None 52 | 53 | # Move both nodes forward in unison until curr is at the end of the list. 54 | while curr.next: 55 | curr = curr.next 56 | follower = follower.next 57 | 58 | return follower 59 | 60 | 61 | class TestNthToLast(unittest.TestCase): 62 | 63 | def test_0th_to_last(self): 64 | ll = LinkedList() 65 | ll.append(1) 66 | ll.append(2) 67 | ll.append(3) 68 | ll.append(4) 69 | ll.append(5) 70 | 71 | self.assertEqual(ll.nth_to_last(0).value, 5) 72 | print("0th to last for 1->2->3->4->5") 73 | 74 | def test_1st_to_last(self): 75 | ll = LinkedList() 76 | ll.append(1) 77 | ll.append(2) 78 | ll.append(3) 79 | ll.append(4) 80 | ll.append(5) 81 | 82 | self.assertEqual(ll.nth_to_last(1).value, 4) 83 | print("1st to last for 1->2->3->4->5") 84 | 85 | def test_2nd_to_last(self): 86 | ll = LinkedList() 87 | ll.append(1) 88 | ll.append(2) 89 | ll.append(3) 90 | ll.append(4) 91 | ll.append(5) 92 | 93 | self.assertEqual(ll.nth_to_last(2).value, 3) 94 | print("2nd to last for 1->2->3->4->5") 95 | 96 | def test_3rd_to_last(self): 97 | ll = LinkedList() 98 | ll.append(1) 99 | ll.append(2) 100 | ll.append(3) 101 | ll.append(4) 102 | ll.append(5) 103 | 104 | self.assertEqual(ll.nth_to_last(3).value, 2) 105 | print("2nd to last for 1->2->3->4->5") 106 | 107 | def test_4th_to_last(self): 108 | ll = LinkedList() 109 | ll.append(1) 110 | ll.append(2) 111 | ll.append(3) 112 | ll.append(4) 113 | ll.append(5) 114 | 115 | self.assertEqual(ll.nth_to_last(4).value, 1) 116 | print("4th to last for 1->2->3->4->5") 117 | 118 | def test_5th_to_last(self): 119 | ll = LinkedList() 120 | ll.append(1) 121 | ll.append(2) 122 | ll.append(3) 123 | ll.append(4) 124 | ll.append(5) 125 | 126 | self.assertEqual(ll.nth_to_last(5), None) 127 | print("5th to last for 1->2->3->4->5") 128 | 129 | 130 | if __name__ == '__main__': 131 | unittest.main() 132 | 133 | -------------------------------------------------------------------------------- /java/BuildOrder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Build Order 3 | * Author: Sam Gavis-Hughson 4 | * Date: 10/16/2016 5 | * 6 | * Given a list of packages and their dependencies, determine a valid build 7 | * order. 8 | * 9 | * Execution: javac BuildOrder.java && java BuildOrder 10 | * 11 | * For more details, check out http://www.byte-by-byte.com/buildorder/ 12 | */ 13 | 14 | import java.util.Arrays; 15 | import java.util.HashSet; 16 | import java.util.LinkedList; 17 | import java.util.List; 18 | import java.util.Set; 19 | 20 | public class BuildOrder { 21 | 22 | // Perform topological sort 23 | // Input is a list of dependencies where the index is the process number 24 | // and the value is the numbers the processes it depends on 25 | public static List buildOrder(int[][] processes) { 26 | Set temporaryMarks = new HashSet(); 27 | Set permanentMarks = new HashSet(); 28 | List result = new LinkedList(); 29 | 30 | // Recursively search from any unmarked node 31 | for (int i = 0; i < processes.length; i++) { 32 | if (!permanentMarks.contains(i)) { 33 | visit(i, processes, temporaryMarks, permanentMarks, result); 34 | } 35 | } 36 | 37 | return result; 38 | } 39 | 40 | // Search through all unmarked nodes accessible from process 41 | public static void visit(int process, 42 | int[][] processes, 43 | Set temporaryMarks, 44 | Set permanentMarks, 45 | List result) { 46 | // Throw an error if we find a cycle 47 | if (temporaryMarks.contains(process)) 48 | throw new RuntimeException("Graph is not acyclic"); 49 | 50 | // If we haven't visited the node, recursively search from there 51 | if (!permanentMarks.contains(process)) { 52 | temporaryMarks.add(process); 53 | 54 | // Perform recursive search from children 55 | for (int i : processes[process]) { 56 | visit(i, processes, temporaryMarks, permanentMarks, result); 57 | } 58 | 59 | // Add permanent mark, remove temporary mark, and add to results list 60 | permanentMarks.add(process); 61 | temporaryMarks.remove(process); 62 | result.add(process); 63 | } 64 | } 65 | 66 | // Sample test cases 67 | public static void main(String[] args) { 68 | assert compareResults(buildOrder(new int[][]{{}, {0}, {1}, {2}, {3}}), 69 | new int[]{0, 1, 2, 3, 4}): 70 | "Simple sorted order"; 71 | assert compareResults(buildOrder(new int[][]{{}, {0}, {0}, {1, 2}, {1, 2, 3}}), 72 | new int[]{0, 1, 2, 3, 4}): 73 | "Complex sorted order"; 74 | assert compareResults(buildOrder(new int[][]{{3}, {0}, {4}, {}, {1}}), 75 | new int[]{3, 0, 1, 4, 2}): 76 | "Simple unsorted order"; 77 | assert compareResults(buildOrder(new int[][]{{3}, {0, 3}, {0, 1, 3}, {}, {1, 2, 3}}), 78 | new int[]{3, 0, 1, 2, 4}): 79 | "Complex unsorted order"; 80 | try { 81 | buildOrder(new int[][]{{1}, {0}}); 82 | assert false: 83 | "Throw error on cycle"; 84 | } catch (Exception e) { 85 | } 86 | System.out.println("Passed all test cases"); 87 | } 88 | 89 | // Helper method for tests. Checks if lists have equal values 90 | private static boolean compareResults(List a, int[] b) { 91 | if (a.size() != b.length) return false; 92 | for (int i = 0; i < a.size(); i++) { 93 | if (a.get(i) != b[i]) return false; 94 | } 95 | 96 | return true; 97 | } 98 | } -------------------------------------------------------------------------------- /cpp/autocomplete.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class AutoComplete 7 | { 8 | private: 9 | 10 | struct node 11 | { 12 | int end; //marks the end of a word 13 | node* child[26]; 14 | 15 | node() : end(0) 16 | { 17 | for(int i=0;i<26;i++) 18 | child[i]=NULL; 19 | } 20 | }; 21 | 22 | node* root; 23 | 24 | public: 25 | AutoComplete() 26 | { 27 | root = new node(); 28 | } 29 | 30 | 31 | void addWord(string &A) //Adds strings to the dictionary 32 | { 33 | int n = A.size(); 34 | node* p = root; 35 | 36 | for(int i=0;ichild[A[i]-'a']==NULL) 39 | p->child[A[i]-'a'] = new node(); //create a node if it does not exist already 40 | 41 | p = p->child[A[i]-'a']; 42 | } 43 | 44 | p->end=1; //mark end of word 45 | } 46 | 47 | void getWords(string & A,vector & words) // stores prefixes of string A in vector "words" 48 | { 49 | int n = A.size(); 50 | node* p = root; 51 | for(int i=0;ichild[A[i]-'a']==NULL) 54 | return ; 55 | 56 | p = p->child[A[i]-'a']; 57 | } 58 | 59 | getPre(p,A,words); 60 | 61 | } 62 | 63 | void getPre(node* p , string &curr , vector & words) // recursive helper function called by getWords 64 | //returns all the prefixes rooted at node 'p' 65 | { 66 | if(p->end == 1) //if end of word ,append it to the answer vector 67 | { 68 | words.push_back(curr); 69 | } 70 | 71 | 72 | for(int i=0;i<26;i++) 73 | { 74 | if(p->child[i]) 75 | { 76 | curr+= 'a'+i; 77 | getPre(p->child[i],curr,words); 78 | curr.pop_back(); 79 | } 80 | } 81 | } 82 | 83 | void DisplaySuggestions(vector&pre) // Displays all the suggestions of the strings in vector "pre" 84 | { 85 | 86 | 87 | for(int i=0;ians; 91 | getWords(curr,ans); 92 | 93 | if(!ans.size()) 94 | cout<<"No matching strings starting with prefix \" "< "; 98 | for(int j=0;jdict,pre; 113 | 114 | dict.push_back("abc"); 115 | dict.push_back("abcd"); 116 | dict.push_back("abcdefg"); 117 | dict.push_back("bababc"); 118 | dict.push_back("dasabc"); 119 | dict.push_back("bbabc"); 120 | dict.push_back("bcdabc"); 121 | dict.push_back("xyzzabc"); 122 | dict.push_back("ddxyzzabc"); 123 | 124 | pre.push_back("a"); 125 | pre.push_back("abc"); 126 | pre.push_back("x"); 127 | pre.push_back("da"); 128 | pre.push_back("d"); 129 | pre.push_back("a"); 130 | pre.push_back("ab"); 131 | pre.push_back("p"); 132 | pre.push_back("bab"); 133 | 134 | AutoComplete *T = new AutoComplete(); 135 | 136 | cout<<"The words in the dictionary are :"<addWord(A); 141 | cout<DisplaySuggestions(pre); 147 | 148 | return 0; 149 | } 150 | -------------------------------------------------------------------------------- /cpp/LinkedListCycle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Linked List Cycle 3 | * Author: Arko Gupta 4 | * Date: 25/10/17 5 | * 6 | * Given a linked list, determine whether it contains any cycles. 7 | * 8 | * Execution: g++ LinkedListCycle.cpp && ./a.out 9 | * 10 | * For more details, check out http://www.byte-by-byte.com/listcycles/ 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | struct node 19 | { 20 | int val; 21 | node *next; 22 | 23 | node() 24 | { 25 | val = 0; 26 | next = NULL; 27 | } 28 | 29 | }; 30 | 31 | class LinkedListCycle 32 | { 33 | 34 | public: 35 | 36 | // Algorithm using extra space. Mark visited nodes and check that you 37 | // only visit each node once. 38 | bool hasCycle(node* head) 39 | { 40 | setvisited; 41 | node* curr = head; 42 | while(curr != NULL) 43 | { 44 | if(visited.find(curr) != visited.end()) 45 | return true; 46 | visited.insert(curr); 47 | curr = curr -> next; 48 | } 49 | return false; 50 | } 51 | 52 | // Floyd's algorithm. Increment one pointer by one and the other by two. 53 | // If they are ever pointing to the same node, there is a cycle. 54 | // Explanation: https://www.quora.com/How-does-Floyds-cycle-finding-algorithm-work 55 | bool hasCycleFloyd(node *head) 56 | { 57 | if(head == NULL) return false; 58 | 59 | node* slow = head; 60 | node* fast = head -> next; 61 | 62 | while(fast != NULL && fast -> next !=NULL) 63 | { 64 | if( slow == fast) return true; 65 | slow = slow -> next; 66 | fast = fast -> next -> next; 67 | } 68 | 69 | return false; 70 | } 71 | 72 | }; 73 | 74 | 75 | // Sample test cases 76 | int main() 77 | { 78 | LinkedListCycle checker; 79 | 80 | 81 | // Test marking visited implementation 82 | assert(checker.hasCycle(NULL) == false); 83 | cout << "Marking visited: Null input " << endl ; 84 | 85 | node* n = new node(); 86 | assert(checker.hasCycle(n) == false); 87 | cout << "Marking visited: Single node" << endl ; 88 | 89 | 90 | n -> next = n; 91 | assert(checker.hasCycle(n) == true); 92 | cout << "Marking visited: Single node cycle" << endl ; 93 | 94 | n -> next = new node(); 95 | assert(checker.hasCycle(n) == false); 96 | cout << "Marking visited: Multinode list" << endl ; 97 | 98 | n -> next -> next = n; 99 | assert(checker.hasCycle(n) == true); 100 | cout << "Marking visited: Even node cycle" << endl ; 101 | 102 | n -> next -> next = new node(); 103 | n -> next -> next -> next = new node(); 104 | n -> next -> next -> next -> next = n -> next; 105 | assert(checker.hasCycle(n) == true); 106 | cout << "Marking visited: Odd length cylce" << endl ; 107 | 108 | 109 | // Test Floyd's algorithm implementation 110 | assert(checker.hasCycleFloyd(NULL) == false); 111 | cout << "Floyd: Null input " << endl ; 112 | 113 | n = new node(); 114 | assert(checker.hasCycleFloyd(n) == false); 115 | cout << "Floyd: Single node" << endl ; 116 | 117 | 118 | n -> next = n; 119 | assert(checker.hasCycleFloyd(n) == true); 120 | cout << "Floyd: Single node cycle" << endl ; 121 | 122 | n -> next = new node(); 123 | assert(checker.hasCycleFloyd(n) == false); 124 | cout << "Floyd: Multinode list" << endl ; 125 | 126 | n -> next -> next = n; 127 | assert(checker.hasCycleFloyd(n) == true); 128 | cout << "Floyd: Even node cycle" << endl ; 129 | 130 | n -> next -> next = new node(); 131 | n -> next -> next -> next = new node(); 132 | n -> next -> next -> next -> next = n -> next; 133 | assert(checker.hasCycleFloyd(n) == true); 134 | cout << "Floyd: Odd length cylce" << endl ; 135 | 136 | cout << "All test cases passed !" ; 137 | 138 | return 0; 139 | } 140 | -------------------------------------------------------------------------------- /java/RandomTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Random Binary Tree 3 | * Author: Sam Gavis-Hughson 4 | * Date: 8/28/2016 5 | * 6 | * Create a binary tree object with a getRandomNode() method that returns a 7 | * random node from the binary tree. 8 | * 9 | * Execution: javac RandomTree.java && java RandomTree 10 | * 11 | * For more details, check out http://www.byte-by-byte.com/randombinarytree/ 12 | */ 13 | import java.util.Random; 14 | 15 | public class RandomTree { 16 | // Individual node of the tree 17 | private class Node { 18 | Node left; 19 | Node right; 20 | int val; 21 | int children; 22 | } 23 | 24 | // The root of the tree 25 | private Node root; 26 | private Random rand; 27 | 28 | public RandomTree() { 29 | rand = new Random(); 30 | } 31 | 32 | // This is for the tests 33 | public RandomTree(long seed) { 34 | rand = new Random(seed); 35 | } 36 | 37 | // Recursively traverse the tree to find the right place for the node in 38 | // order 39 | public void addNode(int val) { 40 | Node n = new Node(); 41 | n.val = val; 42 | if (root == null) { 43 | root = n; 44 | return; 45 | } 46 | 47 | // Recursive call 48 | addNode(root, n); 49 | } 50 | 51 | // Recursive method for adding a node 52 | private void addNode(Node curr, Node n) { 53 | // We are definitely adding the node to this subtree, so go ahead and 54 | // increment curr.children 55 | curr.children++; 56 | 57 | // Go left if its smaller and right if its greater than or equal 58 | if (n.val < curr.val) { 59 | if (curr.left == null) curr.left = n; 60 | else addNode(curr.left, n); 61 | } else { 62 | if (curr.right == null) curr.right = n; 63 | else addNode(curr.right, n); 64 | } 65 | } 66 | 67 | public void deleteNode(int val) { 68 | throw new UnsupportedOperationException("deleteNode() is not implemented"); 69 | } 70 | 71 | // Return each node with probability 1/N 72 | public int getRandomNode() { 73 | if (root == null) throw new NullPointerException(); 74 | 75 | // This is an index of a node in the tree. Indices go in sorted order. 76 | int count = rand.nextInt(root.children + 1); 77 | return getRandomNode(root, count); 78 | } 79 | 80 | // Recursive method. Binary search through tree to find the index. We use 81 | // the number of children to determine which direction to go 82 | private int getRandomNode(Node curr, int count) { 83 | if (count == children(curr.left)) return curr.val; 84 | if (count < children(curr.left)) return getRandomNode(curr.left, count); 85 | 86 | // The new index becomes the index of the same node but now within the 87 | // subtree rather than the whole tree 88 | return getRandomNode(curr.right, count - children(curr.left) - 1); 89 | } 90 | 91 | // Return the number of nodes in a given subtree 92 | private int children(Node n) { 93 | if (n == null) return 0; 94 | return n.children + 1; 95 | } 96 | 97 | // Sample test cases 98 | public static void main(String[] args) { 99 | // Generates the tree: 100 | // 4 101 | // / \ 102 | // 2 6 103 | // / \ / \ 104 | // 1 3 5 7 105 | 106 | RandomTree t = new RandomTree(0); 107 | t.addNode(4); 108 | t.addNode(2); 109 | t.addNode(6); 110 | t.addNode(1); 111 | t.addNode(3); 112 | t.addNode(5); 113 | t.addNode(7); 114 | assert t.getRandomNode() == 6; 115 | assert t.getRandomNode() == 3; 116 | assert t.getRandomNode() == 5; 117 | assert t.getRandomNode() == 3; 118 | assert t.getRandomNode() == 5; 119 | assert t.getRandomNode() == 1; 120 | System.out.println("Passed all tests"); 121 | } 122 | } 123 | 124 | -------------------------------------------------------------------------------- /java/PriorityQueue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Priority Queue 3 | * Author: Sam Gavis-Hughson 4 | * Date: 7/24/2017 5 | * 6 | * Implement a priority queue 7 | * 8 | * Execution: javac PriorityQueue.java && java PriorityQueue 9 | * 10 | * For more details, check out http://www.byte-by-byte.com/priorityqueue/ 11 | */ 12 | 13 | // Implements a priority queue using a max heap. The heap is of fixed size and 14 | // represented using an array. 15 | 16 | import java.util.Arrays; 17 | 18 | public class PriorityQueue { 19 | int[] heap; 20 | int size; 21 | 22 | // Constructor initializes instance variables 23 | public PriorityQueue(int maxSize) { 24 | heap = new int[maxSize]; 25 | size = 0; 26 | } 27 | 28 | // Push an element on to the queue 29 | public void push(int val) { 30 | // If the queue is full then throw an exception 31 | if (size == heap.length) throw new IllegalStateException(); 32 | 33 | // Put the value in the next available space in the queue 34 | int pos = size; 35 | heap[pos] = val; 36 | 37 | // While val is bigger than its parent, swap it with its parent 38 | while (pos > 0) { 39 | // Get the parent and compare the values 40 | int parent = (pos+1) / 2 - 1; 41 | if (heap[parent] >= heap[pos]) break; 42 | swapIndices(parent, pos); 43 | pos = parent; 44 | } 45 | 46 | // We added an element so increment the size 47 | size++; 48 | } 49 | 50 | // Pop the max element from the queue 51 | public int pop() { 52 | // If the queue is empty, throw an exception 53 | if (size == 0) throw new IllegalStateException (); 54 | 55 | // The top of the heap is the first item in the array, so save it off 56 | // to the side so we don't lose it 57 | int toReturn = heap[0]; 58 | 59 | // Move the bottom item in the heap to the first position. We don't need 60 | // to remove it from the array because we have the size variable 61 | heap[0] = heap[size - 1]; 62 | size--; 63 | 64 | // Bubble down the top element to the right spot 65 | int pos = 0; 66 | // We're going to be swapping with the children and any pos >= size / 2 67 | // doesn't have any children 68 | while (pos < size / 2) { 69 | int leftChild = pos * 2 + 1; 70 | int rightChild = leftChild + 1; 71 | // If the right child exists and is greater than the left child, 72 | // compare it to the current position 73 | if (rightChild < size && heap[leftChild] < heap[rightChild]) { 74 | // Only swap if the value is less than the child 75 | if (heap[pos] >= heap[rightChild]) break; 76 | swapIndices(pos, rightChild); 77 | pos = rightChild; 78 | } else { 79 | // Do the same comparison with the left child 80 | if (heap[pos] >= heap[leftChild]) break; 81 | swapIndices(pos, leftChild); 82 | pos = leftChild; 83 | } 84 | } 85 | 86 | return toReturn; 87 | } 88 | 89 | // Swap the values at the indices 90 | private void swapIndices(int i, int j) { 91 | int temp = heap[i]; 92 | heap[i] = heap[j]; 93 | heap[j] = temp; 94 | } 95 | 96 | public static void main(String[] args) { 97 | tester(new int[]{}, "Empty"); 98 | tester(new int[]{1, 2, 3, 4, 5, 6, 7, 8}, "Ascending order"); 99 | tester(new int[]{8, 7, 6, 5, 4, 3, 2, 1}, "Descending order"); 100 | tester(new int[]{1, 6, 3, 4, 5, 2, 8, 7}, "Mixed"); 101 | 102 | System.out.println("Passed all test cases"); 103 | } 104 | 105 | private static void tester(int[] input, String name) { 106 | PriorityQueue p = new PriorityQueue(input.length); 107 | for (int i : input) { 108 | p.push(i); 109 | } 110 | Arrays.sort(input); 111 | for (int i = input.length - 1; i >= 0; i--) { 112 | assert input[i] == p.pop(): 113 | name; 114 | } 115 | } 116 | } -------------------------------------------------------------------------------- /java/Autocomplete.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Autocomplete 3 | * Author: Sam Gavis-Hughson 4 | * Date: 11/13/2016 5 | * 6 | * Write an autocomplete class that returns all dictionary words with 7 | * a given prefix. 8 | * 9 | * Execution: javac Autocomplete.java && java Autocomplete 10 | * 11 | * For more details, check out http://www.byte-by-byte.com/autocomplete/ 12 | */ 13 | 14 | import java.util.Arrays; 15 | import java.util.HashMap; 16 | import java.util.List; 17 | import java.util.LinkedList; 18 | 19 | public class Autocomplete { 20 | 21 | // Trie node class 22 | private class Node { 23 | String prefix; 24 | HashMap children; 25 | 26 | // Does this node represent the last character in a word? 27 | boolean isWord; 28 | 29 | private Node(String prefix) { 30 | this.prefix = prefix; 31 | this.children = new HashMap(); 32 | } 33 | } 34 | 35 | // The trie 36 | private Node trie; 37 | 38 | // Construct the trie from the dictionary 39 | public Autocomplete(String[] dict) { 40 | trie = new Node(""); 41 | for (String s : dict) insertWord(s); 42 | } 43 | 44 | // Insert a word into the trie 45 | private void insertWord(String s) { 46 | // Iterate through each character in the string. If the character is not 47 | // already in the trie then add it 48 | Node curr = trie; 49 | for (int i = 0; i < s.length(); i++) { 50 | if (!curr.children.containsKey(s.charAt(i))) { 51 | curr.children.put(s.charAt(i), new Node(s.substring(0, i + 1))); 52 | } 53 | curr = curr.children.get(s.charAt(i)); 54 | if (i == s.length() - 1) curr.isWord = true; 55 | } 56 | } 57 | 58 | // Find all words in trie that start with prefix 59 | public List getWordsForPrefix(String pre) { 60 | List results = new LinkedList(); 61 | 62 | // Iterate to the end of the prefix 63 | Node curr = trie; 64 | for (char c : pre.toCharArray()) { 65 | if (curr.children.containsKey(c)) { 66 | curr = curr.children.get(c); 67 | } else { 68 | return results; 69 | } 70 | } 71 | 72 | // At the end of the prefix, find all child words 73 | findAllChildWords(curr, results); 74 | return results; 75 | } 76 | 77 | // Recursively find every child word 78 | private void findAllChildWords(Node n, List results) { 79 | if (n.isWord) results.add(n.prefix); 80 | for (Character c : n.children.keySet()) { 81 | findAllChildWords(n.children.get(c), results); 82 | } 83 | } 84 | 85 | // Sample test cases 86 | public static void main(String[] args) { 87 | Autocomplete a = new Autocomplete(new String[]{"abc", "acd", "bcd", "def", "a", "aba"}); 88 | 89 | assert compareArrays((String[])a.getWordsForPrefix("").toArray(new String[6]), 90 | new String[]{"abc", "acd", "bcd", "def", "a", "aba"}): 91 | "Empty string"; 92 | assert compareArrays((String[])a.getWordsForPrefix("a").toArray(new String[4]), 93 | new String[]{"abc", "acd", "a", "aba"}): 94 | "Single character prefix"; 95 | assert compareArrays((String[])a.getWordsForPrefix("def").toArray(new String[1]), 96 | new String[]{"def"}): 97 | "Prefix the length of the string"; 98 | assert compareArrays((String[])a.getWordsForPrefix("abcd").toArray(new String[0]), 99 | new String[]{}): 100 | "No results"; 101 | System.out.println("Passed all test cases"); 102 | } 103 | 104 | private static boolean compareArrays(String[] s1, String[] s2) { 105 | if (s1.length != s2.length) return false; 106 | 107 | Arrays.sort(s1); 108 | Arrays.sort(s2); 109 | 110 | for (int i = 0; i < s1.length; i++) { 111 | if (!s1[i].equals(s2[i])) return false; 112 | } 113 | 114 | return true; 115 | } 116 | } -------------------------------------------------------------------------------- /java/ShortestPath.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Shortest Path 3 | * Author: Sam Gavis-Hughson 4 | * Date: 10/17/2017 5 | * 6 | * Given a directed graph, find the shortest path between two nodes if one 7 | * exists. 8 | * 9 | * Execution: javac ShortestPath.java && java ShortestPath 10 | * 11 | * For more details, check out http://www.byte-by-byte.com/shortestpath/ 12 | */ 13 | 14 | import java.util.Arrays; 15 | import java.util.HashMap; 16 | import java.util.List; 17 | import java.util.LinkedList; 18 | import java.util.Queue; 19 | 20 | public class ShortestPath { 21 | 22 | // Graph node class 23 | public static class Node { 24 | int value; 25 | List children; 26 | 27 | // Basic constructor 28 | public Node(int value) { 29 | this.value = value; 30 | } 31 | 32 | // Lazily instantiate children list 33 | public void addChild(Node n) { 34 | if (this.children == null) this.children = new LinkedList(); 35 | this.children.add(n); 36 | } 37 | } 38 | 39 | // Find the shortest path between two nodes using BFS 40 | public static List shortestPath(Node a, Node b) { 41 | // Return null if either node is null or if they're the same node 42 | if (a == null || b == null) return null; 43 | if (a == b) return null; 44 | 45 | // Using a queue for our BFS 46 | Queue toVisit = new LinkedList(); 47 | 48 | // Track the parents so that we can reconstruct our path 49 | HashMap parents = new HashMap(); 50 | 51 | // Initialize the BFS 52 | toVisit.add(a); 53 | parents.put(a, null); 54 | 55 | // Keep going until we run out of nodes or reach our destination 56 | while (!toVisit.isEmpty()) { 57 | Node curr = toVisit.remove(); 58 | 59 | // If we find the node we're looking for then we're done 60 | if (curr == b) break; 61 | 62 | // If the current node doesn't have children, skip it 63 | if (curr.children == null) continue; 64 | 65 | // Add all the children to the queue 66 | for (Node n : curr.children) { 67 | if (!parents.containsKey(n)) { 68 | toVisit.add(n); 69 | parents.put(n, curr); 70 | } 71 | } 72 | } 73 | 74 | // If we couldn't find a path, the destination node won't have been 75 | // added to our parents set 76 | if (parents.get(b) == null) return null; 77 | 78 | // Create the output list and add the path to the list 79 | List out = new LinkedList(); 80 | Node n = b; 81 | while (n != null) { 82 | out.add(0, n); 83 | n = parents.get(n); 84 | } 85 | 86 | return out; 87 | } 88 | 89 | // Sample test cases 90 | public static void main(String[] args) { 91 | /* Construct sample graph 92 | * 0 ---> 1 93 | * ^ \ | 94 | * | v | 95 | * | 2 | 96 | * | ^ | 97 | * | / v 98 | * 3 <--- 4 99 | */ 100 | Node[] graph = new Node[5]; 101 | for (int i = 0; i < graph.length; i++) { 102 | graph[i] = new Node(i); 103 | } 104 | graph[0].addChild(graph[1]); 105 | graph[0].addChild(graph[2]); 106 | graph[1].addChild(graph[4]); 107 | graph[3].addChild(graph[0]); 108 | graph[3].addChild(graph[2]); 109 | graph[4].addChild(graph[3]); 110 | 111 | assert shortestPath(null, null) == null: 112 | "Null checks"; 113 | assert shortestPath(graph[0], graph[1]) 114 | .equals(Arrays.asList(new Node[]{graph[0], graph[1]})): 115 | "Path length 1"; 116 | assert shortestPath(graph[0], graph[0]) == null: 117 | "Link to itself"; 118 | assert shortestPath(graph[0], graph[3]) 119 | .equals(Arrays.asList(new Node[]{graph[0], graph[1], graph[4], graph[3]})): 120 | "Multiple node path"; 121 | 122 | System.out.println("Passed all test cases"); 123 | } 124 | } -------------------------------------------------------------------------------- /java/TwoMissingNumbers.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Two Missing Numbers 3 | * Author: Sam Gavis-Hughson 4 | * Date: 8/25/2016 5 | * 6 | * Given an unsorted array of numbers from 1 to N with two numbers missing 7 | * returns the two numbers that are missing. 8 | * 9 | * Execution: javac TwoMissingNumbers.java && java TwoMissingNumbers 10 | * 11 | * For more details, check out http://www.byte-by-byte.com/twomissingnumbers/ 12 | */ 13 | import java.util.Arrays; 14 | 15 | public class TwoMissingNumbers { 16 | 17 | // Determine the single number that is missing. 18 | // XOR the actual array and the expected array from 1 to N together. All 19 | // the repeated numbers cancel out, leaving us with the desired result. 20 | // (1 ^ 2 ^ ... ^ N-1 ^ N) ^ (1 ^ 2 ^ ... ^ N-1) = N 21 | public static int oneMissing(int[] arr) { 22 | int totalXor = 0; 23 | int arrXor = 0; 24 | 25 | // XOR the numbers from 1 to N, ie. the input if no numbers were missing 26 | for (int i = 1; i <= arr.length + 1; i++) totalXor ^= i; 27 | 28 | // XOR the input array 29 | for (int i : arr) arrXor ^= i; 30 | 31 | // XOR the two values together. x^x = 0 and x^0 = x. That means that any 32 | // repeated number cancels out, so we are left with the single 33 | // non-repeated number. 34 | // eg. (1 ^ 2 ^ ... ^ N-1 ^ N) ^ (1 ^ 2 ^ ... ^ N-1) = N 35 | return totalXor ^ arrXor; 36 | } 37 | 38 | // Determine the two numbers missing from an array. Returns an array of 39 | // length 2 40 | public static int[] twoMissing(int[] arr) { 41 | int size = arr.length + 2; 42 | 43 | // 1 + 2 + ... + N-1 + N = N * (N + 1) / 2 44 | long totalSum = size * (size + 1) / 2; 45 | 46 | // Sum up the input array 47 | long arrSum = 0; 48 | for (int i : arr) arrSum += i; 49 | 50 | // totalSum - arrSum = the sum of the two results. Therefore we know 51 | // that since our two results are not equal, one result is 52 | // > (sum of two results) / 2 and the other is 53 | // < (sum of two results) / 2 54 | int pivot = (int) ((totalSum - arrSum) / 2); 55 | 56 | // Use the same technique as oneMissing() on each half of the array. 57 | int totalLeftXor = 0; 58 | int arrLeftXor = 0; 59 | int totalRightXor = 0; 60 | int arrRightXor = 0; 61 | 62 | for (int i = 1; i <= pivot; i++) totalLeftXor ^= i; 63 | for (int i = pivot + 1; i <= size; i++) totalRightXor ^= i; 64 | for (int i : arr) { 65 | if (i <= pivot) arrLeftXor ^= i; 66 | else arrRightXor ^= i; 67 | } 68 | 69 | return new int[]{totalLeftXor ^ arrLeftXor, 70 | totalRightXor ^ arrRightXor}; 71 | } 72 | 73 | // Sample test cases 74 | public static void main(String[] args) { 75 | // oneMissing tests 76 | assert oneMissing(new int[]{1, 2, 4, 5}) == 3 : 77 | "oneMissing: Normal case"; 78 | assert oneMissing(new int[]{3, 2, 5, 4}) == 1 : 79 | "oneMissing: Missing first element"; 80 | assert oneMissing(new int[]{4, 3, 2, 1}) == 5 : 81 | "oneMissing: Missing last element"; 82 | 83 | // twoMissing tests 84 | assert compareArrayValues(twoMissing(new int[]{1, 3, 5}), 85 | new int[]{2, 4}) : 86 | "twoMissing: Normal case"; 87 | assert compareArrayValues(twoMissing(new int[]{2, 4, 5}), 88 | new int[]{1, 3}): 89 | "twoMissing: Missing first element"; 90 | assert compareArrayValues(twoMissing(new int[]{3, 1, 2}), 91 | new int[]{4, 5}): 92 | "twoMissing: Missing last two elements"; 93 | 94 | System.out.println("Passed all test cases"); 95 | } 96 | 97 | // Helper method for tests. Checks if arrays contain the same values 98 | private static boolean compareArrayValues(int[] a1, int[] a2) { 99 | if (a1.length != a2.length) return false; 100 | Arrays.sort(a1); 101 | Arrays.sort(a2); 102 | for (int i = 0; i < a1.length; i++) { 103 | if (a1[i] != a2[i]) return false; 104 | } 105 | return true; 106 | } 107 | } -------------------------------------------------------------------------------- /cpp/AutocompleteModern.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: AutocompleteModern 3 | * Author: Mohamed Amine Mzoughi 4 | * Date: 04/01/2018 5 | * 6 | * Write an autocomplete class that returns all dictionary words with 7 | * a given prefix. 8 | * 9 | * Execution: g++ AutocompleteModern.cpp -o AutocompleteModern && ./AutocompleteModern 10 | * 11 | * For more details, check out http://www.byte-by-byte.com/autocomplete/ 12 | */ 13 | 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | class Autocomplete 23 | { 24 | // Trie node class 25 | struct Node 26 | { 27 | std::string m_prefix; 28 | std::unordered_map> m_children; 29 | 30 | // Does this node represent the last character in a word? 31 | bool m_isWord; 32 | 33 | Node(const std::string& prefix) : 34 | m_prefix(prefix), 35 | m_isWord(false) 36 | { 37 | } 38 | }; 39 | 40 | // The trie 41 | Node m_trie; 42 | 43 | // Insert a word into the trie 44 | void insertWord(const std::string& s) 45 | { 46 | // Iterate through each character in the string. If the character is not 47 | // already in the trie then add it 48 | Node* curr = &m_trie; 49 | for (size_t charIndex = 0; charIndex < s.size(); ++charIndex) 50 | { 51 | if (curr->m_children.find(s[charIndex]) == curr->m_children.end()) 52 | { 53 | curr->m_children.emplace(s[charIndex], new Node(s.substr(0, charIndex + 1))); 54 | } 55 | curr = curr->m_children[s[charIndex]].get(); 56 | 57 | if (charIndex == s.size() - 1) 58 | { 59 | curr->m_isWord = true; 60 | } 61 | } 62 | } 63 | 64 | // Recursively find every child word 65 | void findAllChildWords(Node& n, std::vector& results) const 66 | { 67 | if (n.m_isWord) 68 | { 69 | results.push_back(n.m_prefix); 70 | } 71 | 72 | for (const auto& child : n.m_children) { 73 | findAllChildWords(*child.second, results); 74 | } 75 | } 76 | 77 | public: 78 | // Construct the trie from the dictionary 79 | Autocomplete(const std::vector& dict) : 80 | m_trie("") 81 | { 82 | for (const auto& s : dict) 83 | { 84 | insertWord(s); 85 | } 86 | } 87 | 88 | // Find all words in trie that start with prefix 89 | std::vector getWordsForPrefix(const std::string& pre) 90 | { 91 | std::vector results; 92 | 93 | // Iterate to the end of the prefix 94 | Node* curr = &m_trie; 95 | for (const auto c : pre) 96 | { 97 | if (curr->m_children.find(c) != curr->m_children.end()) 98 | { 99 | curr = curr->m_children[c].get(); 100 | } 101 | else 102 | { 103 | return results; 104 | } 105 | } 106 | 107 | // At the end of the prefix, find all child words 108 | findAllChildWords(*curr, results); 109 | return results; 110 | } 111 | }; 112 | 113 | static bool compareArrays(std::vector&& s1, 114 | std::vector&& s2) 115 | { 116 | if (s1.size() != s2.size()) 117 | { 118 | return false; 119 | } 120 | 121 | std::sort(s1.begin(), s1.end()); 122 | std::sort(s2.begin(), s2.end()); 123 | 124 | return std::equal(s1.begin(), s1.end(), s2.begin()); 125 | } 126 | 127 | int main(int argc, char* argv[]) 128 | { 129 | (void) argc; 130 | (void) argv; 131 | 132 | Autocomplete a({"abc", "acd", "bcd", "def", "a", "aba"}); 133 | 134 | assert("Empty string" && compareArrays(a.getWordsForPrefix(""), 135 | {"abc", "acd", "bcd", "def", "a", "aba"})); 136 | 137 | assert("Single character prefix" && compareArrays(a.getWordsForPrefix("a"), 138 | {"abc", "acd", "a", "aba"})); 139 | 140 | assert("Prefix the length of the string" && compareArrays(a.getWordsForPrefix("def"), {"def"})); 141 | 142 | assert("No results" && compareArrays(a.getWordsForPrefix("abcd"), {})); 143 | 144 | std::cout << "Passed all test cases\n"; 145 | } 146 | -------------------------------------------------------------------------------- /python/SquareSubmatrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: Square submatrix 3 | 4 | Given a 2D boolean array, find the largest square subarray of true values. 5 | The return value should be the side length of the largest square subarray 6 | subarray. 7 | 8 | Execution: python SquareSubmatrix.py 9 | 10 | For more details, check out http://www.byte-by-byte.com/squaresubmatrix/ 11 | """ 12 | 13 | import unittest 14 | 15 | 16 | def naive_square_matrix(mat: list): 17 | """ 18 | Brute force solution. From each cell see what is the biggest square 19 | submatrix for which it is the upper left-hand corner. 20 | """ 21 | max_val = 0 22 | # Compute recursively for each cell what it is the upper left corner of. 23 | for i in range(len(mat)): 24 | for j in range(len(mat[0])): 25 | if mat[i][j]: 26 | max_val = max(max_val, naive_square_matrix_recur(mat, i, j)) 27 | return max_val 28 | 29 | 30 | def naive_square_matrix_recur(mat: list, i: int, j: int): 31 | """ 32 | Recursive helper function. 33 | """ 34 | # If we get to the bottom or right of the matrix, we can't go any 35 | # further. 36 | if i == len(mat) or j == len(mat[0]): 37 | return 0 38 | 39 | # If the cell is False then it is not part of a valid submatrix. 40 | if not(mat[i][j]): 41 | return 0 42 | 43 | # Find the size of the right, bottom, and bottom right submatrices and 44 | # add 1 to the minimum of those 3 to get the result. 45 | return 1 + min(min(naive_square_matrix_recur(mat, i+1, j), 46 | naive_square_matrix_recur(mat, i, j+1)), 47 | naive_square_matrix_recur(mat, i+1, j+1)) 48 | 49 | 50 | def top_down_square_matrix(mat: list): 51 | """ 52 | Top down dynamic programming solution. Cache the values as we compute 53 | them to avoid repeating computations. 54 | """ 55 | cache = [[False] * len(mat[0])] * len(mat) 56 | max_val = 0 57 | for i in range(len(mat)): 58 | for j in range(len(mat[0])): 59 | if mat[i][j]: 60 | max_val = max(max_val, top_down_square_matrix_recur(mat, i, j, cache)) 61 | return max_val 62 | 63 | 64 | def top_down_square_matrix_recur(mat: list, i: int, j: int, cache: list): 65 | if i == len(mat) or j == len(mat[0]): 66 | return 0 67 | if not mat[i][j]: 68 | return 0 69 | 70 | # If the value is set in the cache, return it. Otherwise, compute and 71 | # save to cache. 72 | if cache[i][j] > 0: 73 | return cache[i][j] 74 | cache[i][j] = 1 + min(min(top_down_square_matrix_recur(mat, i+1, j, cache), 75 | top_down_square_matrix_recur(mat, i, j+1, cache)), 76 | top_down_square_matrix_recur(mat, i+1, j+1, cache)) 77 | return cache[i][j] 78 | 79 | 80 | def bottom_up_square_submatrix(mat): 81 | """ 82 | Bottom up solution. Start from the upper left-hand corner and compute 83 | progressively larger submatrices. 84 | """ 85 | max_val = 0 86 | # Initialize cache 87 | cache = [[False] * len(mat[0])] * len(mat) 88 | # Iterate over the matrix to compute all values 89 | for i in range(len(cache)): 90 | for j in range(len(cache[0])): 91 | # If we are in the first row or column then the value is just 92 | # 1 if that cell is true and 0 otherwise. In other rows and 93 | # columns, need to look up and to the left. 94 | if i == 0 or j == 0: 95 | cache[i][j] = 1 if mat[i][j] else 0 96 | elif mat[i][j]: 97 | cache[i][j] = 1 + min(min(cache[i][j-1], cache[i-1][j]), cache[i-1][j-1]) 98 | if cache[i][j] > max_val: 99 | max_val = cache[i][j] 100 | return max_val 101 | 102 | 103 | class TestSquareSubmatrix(unittest.TestCase): 104 | 105 | def test_naive_square_matrix(self): 106 | mat = [[True]] 107 | self.assertEqual(naive_square_matrix(mat), 1) 108 | 109 | mat = [[False]] 110 | self.assertEqual(naive_square_matrix(mat), 0) 111 | 112 | mat = [[True, True, True, False], [False, True, True, True], [True, True, True, True, True]] 113 | self.assertEqual(naive_square_matrix(mat), 2) 114 | 115 | mat = [[True, True, True, True], [False, True, True, True], [True, True, True, True]] 116 | self.assertEqual(naive_square_matrix(mat), 3) 117 | 118 | def test_bottom_up_square_matrix(self): 119 | mat = [[True]] 120 | self.assertEqual(bottom_up_square_submatrix(mat), 1) 121 | 122 | mat = [[False]] 123 | self.assertEqual(bottom_up_square_submatrix(mat), 0) 124 | 125 | mat = [[True, True, True, False], [False, True, True, True], [True, True, True, True, True]] 126 | self.assertEqual(bottom_up_square_submatrix(mat), 2) 127 | 128 | mat = [[True, True, True, True], [False, True, True, True], [True, True, True, True]] 129 | self.assertEqual(bottom_up_square_submatrix(mat), 3) 130 | 131 | 132 | if __name__ == '__main__': 133 | unittest.main() 134 | 135 | -------------------------------------------------------------------------------- /java/Knapsack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: 0-1 Knapsack 3 | * Author: Sam Gavis-Hughson 4 | * Date: 6/16/2017 5 | * 6 | * Given a list of items with values and weights, as well as a max weight, find 7 | * the maximum value you can generate from items where the sum of the weights is 8 | * less than the max. 9 | * 10 | * Execution: javac Knapsack.java && java Knapsack 11 | * 12 | * For more details, check out http://www.byte-by-byte.com/01knapsack/ 13 | */ 14 | 15 | import java.util.HashMap; 16 | import java.util.Map; 17 | 18 | public class Knapsack { 19 | // Item class 20 | public static class Item { 21 | int weight; 22 | int value; 23 | 24 | public Item(int weight, int value) { 25 | this.weight = weight; 26 | this.value = value; 27 | } 28 | } 29 | 30 | // Recursively check every combination of items by traversing list of items 31 | // and either including or excluding each item 32 | public static int naiveKnapsack(Item[] items, int W) { 33 | return naiveKnapsack(items, W, 0); 34 | } 35 | 36 | // Overloaded recursive function for naiveKnapsack 37 | private static int naiveKnapsack(Item[] items, int W, int i) { 38 | // Return when we reach the end of the list 39 | if (i == items.length) return 0; 40 | 41 | // If item is heavier than remaining weight, skip item 42 | if (W - items[i].weight < 0) return naiveKnapsack(items, W, i+1); 43 | 44 | // Try both including and excluding the current item 45 | return Math.max(naiveKnapsack(items, W - items[i].weight, i+1) + items[i].value, 46 | naiveKnapsack(items, W, i+1)); 47 | } 48 | 49 | // Recursive solution that uses a cache to improve performance 50 | public static int topDownKnapsack(Item[] items, int W) { 51 | // Map: i -> W -> value 52 | // Use a map instead of array because the data could be very sparse 53 | Map> cache = new HashMap>(); 54 | return topDownKnapsack(items, W, 0, cache); 55 | } 56 | 57 | // Overloaded recursive function for topDownKnapsack 58 | private static int topDownKnapsack(Item[] items, int W, int i, Map> cache) { 59 | // Return when we reach the end of the list 60 | if (i == items.length) return 0; 61 | 62 | // Check the cache and return value if we get a hit 63 | if (!cache.containsKey(i)) cache.put(i, new HashMap()); 64 | Integer cached = cache.get(i).get(W); 65 | if (cached != null) return cached; 66 | 67 | // If item is heavier than remaining weight, skip item 68 | if (W - items[i].weight < 0) return topDownKnapsack(items, W, i+1, cache); 69 | 70 | // Try both including and excluding the current item 71 | int toReturn = Math.max(topDownKnapsack(items, W - items[i].weight, i+1, cache) + items[i].value, 72 | topDownKnapsack(items, W, i+1, cache)); 73 | cache.get(i).put(W, toReturn); 74 | return toReturn; 75 | } 76 | 77 | // Iterative dynamic programming solution 78 | public static int bottomUpKnapsack(Item[] items, int W) { 79 | // cache[i][j] = max value for the first i items with a max weight of j 80 | int[][] cache = new int[items.length + 1][W + 1]; 81 | for (int i = 1; i <= items.length; i++) { 82 | for (int j = 0; j <= W; j++) { 83 | // If including item[i-1] would exceed max weight j, don't 84 | // include the item. Otherwise take the max value of including 85 | // or excluding the item 86 | if (items[i-1].weight > j) cache[i][j] = cache[i-1][j]; 87 | else cache[i][j] = Math.max(cache[i-1][j], cache[i-1][j-items[i-1].weight] + items[i-1].value); 88 | } 89 | } 90 | 91 | return cache[items.length][W]; 92 | } 93 | 94 | // Sample test cases 95 | public static void main(String[] args) { 96 | Item[] items = new Item[]{new Item(1,1), 97 | new Item(2,1), 98 | new Item(3,2), 99 | new Item(4,3), 100 | new Item(5,5), 101 | new Item(6,8), 102 | new Item(7,13), 103 | new Item(8,21), 104 | new Item(9,34), 105 | new Item(10,55)}; 106 | int W = 20; 107 | 108 | assert naiveKnapsack(new Item[]{}, 10) == 0: 109 | "Naive, empty list"; 110 | assert topDownKnapsack(new Item[]{}, 10) == 0: 111 | "Top Down, empty list"; 112 | assert bottomUpKnapsack(new Item[]{}, 10) == 0: 113 | "Bottom Up, empty list"; 114 | assert naiveKnapsack(items, 20) == 90: 115 | "Naive, fibonacci"; 116 | assert topDownKnapsack(items, 20) == 90: 117 | "Top Down, fibonacci"; 118 | assert bottomUpKnapsack(items, 20) == 90: 119 | "Bottom Up, fibonacci"; 120 | 121 | System.out.println("Passed all test cases"); 122 | } 123 | } -------------------------------------------------------------------------------- /cpp/TwoMissing.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Two missing 3 | * 4 | Given an array containing all the numbers from 1 to n except two, 5 | find the two missing numbers. 6 | * 7 | * Execution: g++ TwoMissing.cpp -o TwoMissing 8 | * 9 | * For more details, check out http://www.byte-by-byte.com/twomissing 10 | * 11 | */ 12 | #include 13 | #include 14 | #include 15 | 16 | using namespace std; 17 | 18 | int oneMissing(vector v) { 19 | int total_xor = 0; 20 | int arr_xor = 0; 21 | 22 | for (int i = 1; i < v.size()+2; i++) { 23 | total_xor = total_xor ^ i; 24 | } 25 | 26 | for (int i = 0; i < v.size(); i++) { 27 | arr_xor = arr_xor ^ v[i]; 28 | } 29 | 30 | return total_xor ^ arr_xor; 31 | } 32 | 33 | // def twoMissing(arr): 34 | // size = len(arr) + 2 35 | // totalSum = size * (size + 1)//2 # we want only the integer portion 36 | // arrSum = 0 37 | // 38 | // for i in range(len(arr)): 39 | // arrSum += arr[i] 40 | // 41 | // pivot = (totalSum - arrSum) // 2 # we want only the integer portion 42 | // 43 | // totalLeftXor = 0 44 | // arrLeftXor = 0 45 | // totalRightXor = 0 46 | // arrRightXor = 0 47 | // 48 | // for i in range(1, pivot+1): 49 | // totalLeftXor ^= i 50 | // 51 | // for i in range(pivot+1, size+1): 52 | // totalRightXor ^= i 53 | // 54 | // for i in range(len(arr)): 55 | // if (arr[i] <= pivot): 56 | // arrLeftXor ^= arr[i] 57 | // else: 58 | // arrRightXor ^= arr[i] 59 | // 60 | // return (totalLeftXor ^ arrLeftXor, totalRightXor ^ arrRightXor) 61 | 62 | vector twoMissing(vector v) { 63 | int size = v.size() + 2; 64 | int total_sum = int(size * (size + 1) / 2); 65 | int arr_sum = 0; 66 | 67 | for(int i = 0; i < v.size(); i++) { 68 | arr_sum += v[i]; 69 | } 70 | int pivot = int((total_sum - arr_sum) / 2); 71 | 72 | int total_left_xor = 0; 73 | int arr_left_xor = 0; 74 | int total_right_xor = 0; 75 | int arr_right_xor = 0; 76 | 77 | for (int i = 1; i < pivot+1; i++) { 78 | total_left_xor ^= i; 79 | } 80 | for (int i = pivot+1; i < size+1; i++) { 81 | total_right_xor ^= i; 82 | } 83 | for (int i = 0; i < v.size(); i++) { 84 | if (v[i] <= pivot) { 85 | arr_left_xor ^= v[i]; 86 | } else { 87 | arr_right_xor ^= v[i]; 88 | } 89 | } 90 | 91 | vector return_vec; 92 | return_vec.push_back(total_left_xor ^ arr_left_xor); 93 | return_vec.push_back(total_right_xor ^ arr_right_xor); 94 | return return_vec; 95 | } 96 | 97 | void testOneMissing_1() { 98 | vector v; 99 | v.push_back(1); 100 | v.push_back(2); 101 | v.push_back(4); 102 | v.push_back(5); 103 | 104 | if (oneMissing(v) == 3) { 105 | cout << "Test One Missing 1 passed" << endl; 106 | } else { 107 | cout << "Test One Missing 1 failed" << endl; 108 | } 109 | } 110 | 111 | void testOneMissing_2() { 112 | vector v; 113 | v.push_back(3); 114 | v.push_back(2); 115 | v.push_back(5); 116 | v.push_back(4); 117 | 118 | if (oneMissing(v) == 1) { 119 | cout << "Test One Missing 2 passed" << endl; 120 | } else { 121 | cout << "Test One Missing 2 failed" << endl; 122 | } 123 | } 124 | 125 | void testOneMissing_3() { 126 | vector v; 127 | v.push_back(4); 128 | v.push_back(3); 129 | v.push_back(2); 130 | v.push_back(1); 131 | 132 | if (oneMissing(v) == 5) { 133 | cout << "Test One Missing 3 passed" << endl; 134 | } else { 135 | cout << "Test One Missing 3 failed" << endl; 136 | } 137 | } 138 | 139 | void testTwoMissing_1() { 140 | vector v; 141 | v.push_back(1); 142 | v.push_back(3); 143 | v.push_back(5); 144 | 145 | vector result = twoMissing(v); 146 | 147 | if (result[0] == 2 && result[1] == 4) { 148 | cout << "Test Two Missing 1 passed" << endl; 149 | } else { 150 | cout << "Test Two Missing 1 failed" << endl; 151 | } 152 | } 153 | 154 | void testTwoMissing_2() { 155 | vector v; 156 | v.push_back(2); 157 | v.push_back(4); 158 | v.push_back(5); 159 | 160 | vector result = twoMissing(v); 161 | 162 | if (result[0] == 1 && result[1] == 3) { 163 | cout << "Test Two Missing 2 passed" << endl; 164 | } else { 165 | cout << "Test Two Missing 2 failed" << endl; 166 | } 167 | } 168 | 169 | void testTwoMissing_3() { 170 | vector v; 171 | v.push_back(3); 172 | v.push_back(1); 173 | v.push_back(2); 174 | 175 | vector result = twoMissing(v); 176 | 177 | if (result[0] == 4 && result[1] == 5) { 178 | cout << "Test Two Missing 3 passed" << endl; 179 | } else { 180 | cout << "Test Two Missing 3 failed" << endl; 181 | } 182 | } 183 | 184 | void testOneMissing() { 185 | testOneMissing_1(); 186 | testOneMissing_2(); 187 | testOneMissing_3(); 188 | } 189 | 190 | void testTwoMissing() { 191 | testTwoMissing_1(); 192 | testTwoMissing_2(); 193 | testTwoMissing_3(); 194 | } 195 | 196 | int main() { 197 | 198 | testOneMissing(); 199 | testTwoMissing(); 200 | 201 | return 0; 202 | } 203 | 204 | -------------------------------------------------------------------------------- /java/ZeroMatrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Zero Matrix 3 | * Author: Sam Gavis-Hughson 4 | * Date: 9/5/2016 5 | * 6 | * Given a boolean matrix, update it so that if any cell is true, all the rows 7 | * in that cell are true. 8 | * 9 | * eg. 10 | * [true, false, false] [true, true, true ] 11 | * [false, false, false] -> [true, false, false] 12 | * [false, false, false] [true, false, false] 13 | * 14 | * Execution: javac ZeroMatrix.java && java ZeroMatrix 15 | * 16 | * For more details, check out http://www.byte-by-byte.com/zeromatrix/ 17 | */ 18 | import java.util.Arrays; 19 | 20 | public class ZeroMatrix { 21 | public static void zeroMatrix(boolean[][] matrix) { 22 | 23 | // Verify the input array is nonzero 24 | if (matrix.length == 0 || matrix[0].length == 0) return; 25 | 26 | // Determine whether the first row or first column is true 27 | boolean rowZero = false, colZero = false; 28 | for (boolean i : matrix[0]) { 29 | rowZero |= i; 30 | } 31 | for (boolean[] i : matrix) { 32 | colZero |= i[0]; 33 | } 34 | 35 | // For each cell not in the first row/column, if it is true, set the 36 | // cell in the first row/same column and first column/same row to be 37 | // true 38 | for (int i = 1; i < matrix.length; i++) { 39 | for (int j = 1; j < matrix[0].length; j++) { 40 | if (matrix[i][j]) { 41 | matrix[i][0] = true; 42 | matrix[0][j] = true; 43 | } 44 | } 45 | } 46 | 47 | // Go through the first column and set each row to true where cell in 48 | // the first column is true 49 | for (int i = 1; i < matrix.length; i++) { 50 | if (matrix[i][0]) { 51 | for (int j = 1; j < matrix[i].length; j++) { 52 | matrix[i][j] = true; 53 | } 54 | } 55 | } 56 | 57 | // Repeat for the rows 58 | for (int j = 1; j < matrix[0].length; j++) { 59 | if (matrix[0][j]) { 60 | for (int i = 1; i < matrix.length; i++) { 61 | matrix[i][j] = true; 62 | } 63 | } 64 | } 65 | 66 | // Set first row/column to true if necessary 67 | if (rowZero) { 68 | for (int i = 0; i < matrix[0].length; i++) { 69 | matrix[0][i] = true; 70 | } 71 | } 72 | 73 | if (colZero) { 74 | for (int i = 0; i < matrix.length; i++) { 75 | matrix[i][0] = true; 76 | } 77 | } 78 | } 79 | 80 | // Sample test cases 81 | public static void main(String[] args) { 82 | boolean[][] a = new boolean[][]{ 83 | {true, false, false}, 84 | {false, false, false}, 85 | {false, false, false} 86 | }; 87 | zeroMatrix(a); 88 | assert compare2dArrays(a, new boolean[][]{ 89 | {true, true, true}, 90 | {true, false, false}, 91 | {true, false, false} 92 | }) : "First row and first column"; 93 | 94 | a = new boolean[][]{ 95 | {false, false, false}, 96 | {false, false, false}, 97 | {false, false, false} 98 | }; 99 | zeroMatrix(a); 100 | assert compare2dArrays(a, new boolean[][]{ 101 | {false, false, false}, 102 | {false, false, false}, 103 | {false, false, false} 104 | }) : "All false"; 105 | 106 | a = new boolean[][]{ 107 | {true, true, true}, 108 | {true, true, true}, 109 | {true, true, true}, 110 | }; 111 | zeroMatrix(a); 112 | assert compare2dArrays(a, new boolean[][]{ 113 | {true, true, true}, 114 | {true, true, true}, 115 | {true, true, true}, 116 | }) : "All true"; 117 | 118 | a = new boolean[][]{ 119 | {false, true, false}, 120 | }; 121 | zeroMatrix(a); 122 | assert compare2dArrays(a, new boolean[][]{ 123 | {true, true, true} 124 | }) : "1 x 3 array"; 125 | 126 | a = new boolean[][]{ 127 | {false}, 128 | {true}, 129 | {false} 130 | }; 131 | zeroMatrix(a); 132 | assert compare2dArrays(a, new boolean[][]{ 133 | {true}, 134 | {true}, 135 | {true} 136 | }) : "3 x 1 array"; 137 | 138 | a = new boolean[][]{ 139 | {true, false, false}, 140 | {false, false, false}, 141 | {false, false, true} 142 | }; 143 | zeroMatrix(a); 144 | assert compare2dArrays(a, new boolean[][]{ 145 | {true, true, true}, 146 | {true, false, true}, 147 | {true, true, true} 148 | }) : "Multiple true"; 149 | 150 | System.out.println("Passed all test cases"); 151 | } 152 | 153 | private static boolean compare2dArrays(boolean[][] a, boolean[][] b) { 154 | if (a.length != b.length) return false; 155 | if (a[0].length != b[0].length) return false; 156 | 157 | for (int i = 0; i < a.length; i++) { 158 | for (int j = 0; j < a[0].length; j++) { 159 | if (a[i][j] != b[i][j]) return false; 160 | } 161 | } 162 | 163 | return true; 164 | } 165 | } -------------------------------------------------------------------------------- /java/RandomLinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Random Linked List 3 | * 4 | * Given a linked list where each node contains a pointer to the next node and 5 | * a pointer to a random node in the list, write a function to create a copy of 6 | * the linked list. 7 | * 8 | * Execution: javac RandomLinkedList.java && java RandomLinkedList 9 | * 10 | * For more details, check out http://www.byte-by-byte.com/randomlinkedlist/ 11 | */ 12 | 13 | import java.util.HashMap; 14 | import java.util.Random; 15 | 16 | public class RandomLinkedList { 17 | 18 | // Private node class 19 | private static class Node { 20 | int value; 21 | Node next; 22 | Node random; 23 | } 24 | 25 | // Copy list using extra space. Store mapping of old nodes to new nodes 26 | public static Node cloneExtraSpace(Node n) { 27 | if (n == null) return n; 28 | 29 | // Map nodes in old list to equivalent nodes in new list 30 | HashMap mapping = new HashMap(); 31 | 32 | // Create new linked list, minus the random node pointers. Save mapping 33 | // of equivalent old node to new node 34 | Node copy = new Node(); 35 | Node nCurr = n, copyCurr = copy; 36 | mapping.put(nCurr, copyCurr); 37 | 38 | while (nCurr.next != null) { 39 | copyCurr.next = new Node(); 40 | nCurr = nCurr.next; 41 | copyCurr = copyCurr.next; 42 | mapping.put(nCurr, copyCurr); 43 | } 44 | 45 | // Copy the random pointers. Find the random pointer in the original 46 | // list and look up the equivalent using the map 47 | nCurr = n; 48 | copyCurr = copy; 49 | while (nCurr != null) { 50 | copyCurr.random = mapping.get(nCurr.random); 51 | nCurr = nCurr.next; 52 | copyCurr = copyCurr.next; 53 | } 54 | 55 | return copy; 56 | } 57 | 58 | // Copy list without using extra space. Interleave the nodes from the new 59 | // with the nodes from the original list. Then separate the new list from 60 | // the old 61 | public static Node cloneNoExtraSpace(Node n) { 62 | if (n == null) return n; 63 | 64 | // Create new nodes in between the original nodes 65 | Node nCurr = n; 66 | while (nCurr != null) { 67 | Node temp = new Node(); 68 | temp.value = nCurr.value; 69 | temp.next = nCurr.next; 70 | nCurr.next = temp; 71 | nCurr = nCurr.next.next; 72 | } 73 | 74 | // Copy random pointers 75 | nCurr = n; 76 | while (nCurr != null) { 77 | nCurr.next.random = nCurr.random.next; 78 | nCurr = nCurr.next.next; 79 | } 80 | 81 | // Separate new nodes from old nodes 82 | Node copy = n.next; 83 | nCurr = n; 84 | while (nCurr.next != null) { 85 | Node tmp = nCurr.next; 86 | nCurr.next = nCurr.next.next; 87 | nCurr = tmp; 88 | } 89 | 90 | return copy; 91 | } 92 | 93 | // Sample test cases 94 | public static void main(String[] args) { 95 | assert cloneExtraSpace(null) == null: 96 | "Empty list - extra space"; 97 | assert cloneNoExtraSpace(null) == null: 98 | "Empty list - no extra space"; 99 | 100 | Node n = new Node(); 101 | n.random = n; 102 | assert compareLinkedList(cloneExtraSpace(n), n): 103 | "Length one linked list, none-null random - extra space"; 104 | 105 | assert compareLinkedList(cloneNoExtraSpace(n), n): 106 | "Length one linked list, none-null random - no extra space"; 107 | 108 | // Randomly generate random linked lists 109 | Random rand = new Random(0); 110 | for (int i = 0; i < 10; i++) { 111 | // Create the nodes 112 | Node[] nodes = new Node[rand.nextInt(100)]; 113 | for (int j = 0; j < nodes.length; j++) { 114 | nodes[j] = new Node(); 115 | } 116 | 117 | // Create the links between the nodes 118 | for (int j = 0; j < nodes.length; j++) { 119 | if (j < nodes.length - 1) nodes[j].next = nodes[j+1]; 120 | // Some null and some pointers to other nodes 121 | if (rand.nextInt(100) > 10) { 122 | nodes[j].random = nodes[rand.nextInt(nodes.length)]; 123 | } 124 | } 125 | 126 | assert compareLinkedList(cloneExtraSpace(n), n): 127 | "Length " + nodes.length + " linked list, randomly generated - extra space"; 128 | assert compareLinkedList(cloneNoExtraSpace(n), n): 129 | "Length " + nodes.length + " linked list, randomly generated - no extra space"; 130 | } 131 | 132 | System.out.println("Passed all test cases"); 133 | } 134 | 135 | private static boolean compareLinkedList(Node a, Node b) { 136 | Node currA = a, currB = b; 137 | while (currA != null && currB != null) { 138 | if (currA.value != currB.value) return false; 139 | if (currA.random != null && currB.random != null) { 140 | if (currA.random.value != currB.random.value) return false; 141 | } else if (currA.random != null || currB.random != null) { 142 | return false; 143 | } 144 | currA = currA.next; 145 | currB = currB.next; 146 | } 147 | 148 | return currA == null && currB == null; 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /python/Knapsack.py: -------------------------------------------------------------------------------- 1 | """ 2 | Title: 0-1 Knapsack 3 | 4 | Given a list of items with values and weights, as well as a max weight, find 5 | the maximum value you can generate from items where the sum of the weights is 6 | less than the max. 7 | 8 | Execution: python Knapsack.py 9 | 10 | For more details, check out http://www.byte-by-byte.com/01knapsack/ 11 | """ 12 | import unittest 13 | 14 | 15 | class Item: 16 | """ 17 | Item class for Knapsack. 18 | """ 19 | def __init__(self, weight: int, value: int): 20 | self.weight = weight 21 | self.value = value 22 | 23 | 24 | def naive_knapsack(items: list, W: int): 25 | """ 26 | Recursively check every combination of items by traversing list of items 27 | and either including or excluding each item. 28 | """ 29 | return naive_knapsack_recur(items, W, 0) 30 | 31 | 32 | def naive_knapsack_recur(items: list, W: int, i: 0): 33 | """ 34 | Recursive helper function for naive_knapsack. 35 | """ 36 | 37 | # Return when we reach the end of the list. 38 | if i == len(items): 39 | return 0 40 | 41 | # If item is heavier than remaining weight, skip item. 42 | if W - items[i].weight < 0: 43 | return naive_knapsack_recur(items, W, i+1) 44 | 45 | # Try both including and excluding the current item. 46 | return max(naive_knapsack_recur(items, W - items[i].weight, i+1) + items[i].value, 47 | naive_knapsack_recur(items, W, i+1)) 48 | 49 | 50 | def top_down_knapsack(items: list, W: int): 51 | """ 52 | Recursive solution that uses a cache to improve performance. 53 | """ 54 | 55 | # Map: i -> W -> value 56 | # Use a map instead of array because the data could be very sparse. 57 | cache = dict() 58 | return top_down_knapsack_recur(items, W, 0, cache) 59 | 60 | 61 | def top_down_knapsack_recur(items: list, W: int, i: int, cache: dict): 62 | """ 63 | Overloaded recursive function for top_down_knapsack. 64 | """ 65 | 66 | # Return when we reach the end of the list. 67 | if i == len(items): 68 | return 0 69 | 70 | # Check the cache and return value if we get a hit. 71 | if i not in cache.keys(): 72 | cache[i] = dict() 73 | cached = None 74 | try: 75 | cached = cache[i][W] 76 | except: 77 | pass 78 | 79 | if cached: 80 | return cached 81 | 82 | # If item is heavier than remaining weight, skip item 83 | if W - items[i].weight < 0: 84 | return top_down_knapsack_recur(items, W, i+1, cache) 85 | 86 | to_return = max(top_down_knapsack_recur(items, W - items[i].weight, i + 1, cache) + items[i].value, 87 | top_down_knapsack_recur(items, W, i + 1, cache)) 88 | 89 | cache[i] = {W: to_return} 90 | return to_return 91 | 92 | 93 | def bottom_up_knapsack(items: list, W: int): 94 | """ 95 | Iterative dynamic programming solution. 96 | """ 97 | 98 | # cache[i][j] = max value for the first i items with a max weight of j 99 | cache = [[0 for x in range(W + 1)] for y in range(len(items) + 1)] 100 | for i in range(1, len(items)+1): 101 | for j in range(W+1): 102 | # If including item[i-1] would exceed max weight j, dont 103 | # include the item. Otherwise take the max value of including 104 | # or excluding the item. 105 | if items[i-1].weight > j: 106 | cache[i][j] = cache[i-1][j] 107 | else: 108 | cache[i][j] = max(cache[i-1][j], cache[i-1][j-items[i-1].weight] + items[i-1].value) 109 | return cache[len(items)][W] 110 | 111 | 112 | class TestKnapsack(unittest.TestCase): 113 | def test_naive_empty_list(self): 114 | self.assertEqual(naive_knapsack(items=[], W=10), 0) 115 | print("Naive, empty list") 116 | 117 | def test_top_down_empty_list(self): 118 | self.assertEqual(top_down_knapsack(items=[], W=10), 0) 119 | print("Top-down, empty list") 120 | 121 | def test_bottom_up_empty_list(self): 122 | self.assertEqual(bottom_up_knapsack(items=[], W=10), 0) 123 | print("Bottom-up, empty list") 124 | 125 | def test_naive_fibonacci(self): 126 | items = [] 127 | items.append(Item(1,1)) 128 | items.append(Item(2,1)) 129 | items.append(Item(3,2)) 130 | items.append(Item(4,3)) 131 | items.append(Item(5,5)) 132 | items.append(Item(6,8)) 133 | items.append(Item(7,13)) 134 | items.append(Item(8,21)) 135 | items.append(Item(9,34)) 136 | items.append(Item(10,55)) 137 | 138 | self.assertEqual(naive_knapsack(items, W=20), 90) 139 | 140 | def test_top_down_fibonacci(self): 141 | items = [] 142 | items.append(Item(1,1)) 143 | items.append(Item(2,1)) 144 | items.append(Item(3,2)) 145 | items.append(Item(4,3)) 146 | items.append(Item(5,5)) 147 | items.append(Item(6,8)) 148 | items.append(Item(7,13)) 149 | items.append(Item(8,21)) 150 | items.append(Item(9,34)) 151 | items.append(Item(10,55)) 152 | 153 | self.assertEqual(top_down_knapsack(items, W=20), 90) 154 | 155 | def test_bottom_up_fibonacci(self): 156 | items = [] 157 | items.append(Item(1,1)) 158 | items.append(Item(2,1)) 159 | items.append(Item(3,2)) 160 | items.append(Item(4,3)) 161 | items.append(Item(5,5)) 162 | items.append(Item(6,8)) 163 | items.append(Item(7,13)) 164 | items.append(Item(8,21)) 165 | items.append(Item(9,34)) 166 | items.append(Item(10,55)) 167 | 168 | self.assertEqual(bottom_up_knapsack(items, W=20), 90) 169 | 170 | 171 | if __name__ == '__main__': 172 | unittest.main() 173 | 174 | -------------------------------------------------------------------------------- /java/SquareSubmatrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Title: Square submatrix 3 | * Author: Sam Gavis-Hughson 4 | * Date: 10/17/2017 5 | * 6 | * Given a 2D boolean array, find the largest square subarray of true values. 7 | * The return value should be the side length of the largest square subarray 8 | * subarray. 9 | * 10 | * Execution: javac SquareSubmatrix.java && java SquareSubmatrix 11 | * 12 | * For more details, check out http://www.byte-by-byte.com/squaresubmatrix/ 13 | */ 14 | 15 | import java.util.Arrays; 16 | 17 | public class SquareSubmatrix { 18 | // Brute force solution. From each cell see what is the biggest square 19 | // submatrix for which it is the upper left-hand corner 20 | public static int naiveSquareSubmatrix(boolean[][] arr) { 21 | int max = 0; 22 | // Compute recursively for each cell what it is the upper left corner of 23 | for (int i = 0; i < arr.length; i++) { 24 | for (int j = 0; j < arr[0].length; j++) { 25 | if (arr[i][j]) max = Math.max(max, naiveSquareSubmatrix(arr, i, j)); 26 | } 27 | } 28 | 29 | return max; 30 | } 31 | 32 | // Overloaded recursive function 33 | private static int naiveSquareSubmatrix(boolean[][] arr, int i, int j) { 34 | // If we get to the bottom or right of the matrix, we can't go any 35 | // further 36 | if (i == arr.length || j == arr[0].length) return 0; 37 | 38 | // If the cell is False then it is not part of a valid submatrix 39 | if (!arr[i][j]) return 0; 40 | 41 | // Find the size of the right, bottom, and bottom right submatrices and 42 | // add 1 to the minimum of those 3 to get the result 43 | return 1 + Math.min(Math.min(naiveSquareSubmatrix(arr, i+1, j), 44 | naiveSquareSubmatrix(arr, i, j+1)), 45 | naiveSquareSubmatrix(arr, i+1, j+1)); 46 | } 47 | 48 | // Top down dynamic programming solution. Cache the values as we compute 49 | // them to avoid repeating computations 50 | public static int topDownSquareSubmatrix(boolean[][] arr) { 51 | // Initialize cache. Don't need to initialize to -1 because the only 52 | // cells that will be 0 are ones that are False and we want to skip 53 | // those ones anyway 54 | int[][] cache = new int[arr.length][arr[0].length]; 55 | int max = 0; 56 | for (int i = 0; i < arr.length; i++) { 57 | for (int j = 0; j < arr[0].length; j++) { 58 | if (arr[i][j]) max = Math.max(max, topDownSquareSubmatrix(arr, i, j, cache)); 59 | } 60 | } 61 | 62 | return max; 63 | } 64 | 65 | // Overloaded recursive function 66 | private static int topDownSquareSubmatrix(boolean[][] arr, int i, int j, int[][] cache) { 67 | if (i == arr.length || j == arr[0].length) return 0; 68 | if (!arr[i][j]) return 0; 69 | 70 | // If the value is set in the cache return it. Otherwise compute and 71 | // save to cache 72 | if (cache[i][j] > 0) return cache[i][j]; 73 | cache[i][j] = 1 + Math.min(Math.min(topDownSquareSubmatrix(arr, i+1, j, cache), 74 | topDownSquareSubmatrix(arr, i, j+1, cache)), 75 | topDownSquareSubmatrix(arr, i+1, j+1, cache)); 76 | return cache[i][j]; 77 | } 78 | 79 | // Bottom up solution. Start from the upper left-hand corner and compute 80 | // progressively larger submatrices 81 | public static int bottomUpSquareSubmatrix(boolean[][] arr) { 82 | int max = 0; 83 | // Initialize cache 84 | int[][] cache = new int[arr.length][arr[0].length]; 85 | // Iterate over the matrix to compute all values 86 | for (int i = 0; i < cache.length; i++) { 87 | for (int j = 0; j < cache[0].length; j++) { 88 | // If we are in the first row or column then the value is just 89 | // 1 if that cell is true and 0 otherwise. In other rows and 90 | // columns, need to look up and to the left 91 | if (i == 0 || j == 0) { 92 | cache[i][j] = arr[i][j] ? 1 : 0; 93 | } else if (arr[i][j]) { 94 | cache[i][j] = Math.min(Math.min(cache[i][j-1], 95 | cache[i-1][j]), 96 | cache[i-1][j-1]) + 1; 97 | } 98 | if (cache[i][j] > max) max = cache[i][j]; 99 | } 100 | } 101 | 102 | return max; 103 | } 104 | 105 | // Sample testcases 106 | public static void main(String[] args) { 107 | (new TestCase(new boolean[][]{new boolean[]{true}}, 1)).run(); 108 | (new TestCase(new boolean[][]{new boolean[]{false}}, 0)).run(); 109 | (new TestCase(new boolean[][]{ 110 | new boolean[]{true, true, true, false}, 111 | new boolean[]{false, true, true, true}, 112 | new boolean[]{true, true, true, true}}, 2)).run(); 113 | (new TestCase(new boolean[][]{ 114 | new boolean[]{true, true, true, true}, 115 | new boolean[]{false, true, true, true}, 116 | new boolean[]{true, true, true, true}}, 3)).run(); 117 | System.out.println("Passed all test cases"); 118 | } 119 | 120 | // Class for defining and running test cases 121 | private static class TestCase { 122 | private boolean[][] input; 123 | private int output; 124 | 125 | private TestCase(boolean[][] input, int output) { 126 | this.input = input; 127 | this.output = output; 128 | } 129 | 130 | private void run() { 131 | assert naiveSquareSubmatrix(input) == output: 132 | "naiveSquareSubmatrix failed for input = " + inputString(); 133 | assert topDownSquareSubmatrix(input) == output: 134 | "topDownSquareSubmatrix failed for input = " + inputString(); 135 | assert bottomUpSquareSubmatrix(input) == output: 136 | "bottomUpSquareSubmatrix failed for input = " + inputString(); 137 | } 138 | 139 | private String inputString() { 140 | StringBuilder sb = new StringBuilder(); 141 | for (int i = 0; i < input.length; i++) { 142 | sb.append(Arrays.toString(input[i])); 143 | if (i != input.length - 1) sb.append('\n'); 144 | } 145 | return sb.toString(); 146 | } 147 | } 148 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Byte by Byte Solutions 2 | [Byte by Byte](http://www.byte-by-byte.com) is a coding interview prep website that provides many practice interview questions as well as detailed explanations. This repo contains working, tested code for the solutions on Byte by Byte. 3 | 4 | ### Contributing 5 | I would love to compile solutions to all of the problems here, as well as offer solutions in different languages. Currently we only have Java solutions but Python, C, or any other languages would be most welcome. Just create a pull request with your changes. And make sure your code includes at least a few tests! 6 | 7 | ### Index of Questions 8 | * [Median of Arrays](http://www.byte-by-byte.com/median/) 9 | Find the median of two sorted arrays. 10 | 11 | * [Priority Queue](http://www.byte-by-byte.com/priorityqueue/) 12 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/PriorityQueue.java)) 13 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/PriorityQueue.py))
14 | Implement a Priority Queue. 15 | 16 | * [0-1 Knapsack](http://www.byte-by-byte.com/01knapsack/) 17 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/Knapsack.java)) 18 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/Knapsack.py))
19 | Given a list of items with values and weights, as well as a max weight, find the maximum value you can generate from items where the sum of the weights is less than the max. 20 | 21 | * [Matrix Product](http://www.byte-by-byte.com/matrixproduct/) 22 | ([Github](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/MatrixProduct.java))
23 | Given a matrix, find the path from top left to bottom right with the greatest product by moving only down and right. 24 | 25 | * [Find Duplicates](http://www.byte-by-byte.com/findduplicates/) 26 | ([C++](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/cpp/FindDuplicates.cpp)) 27 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/FindDuplicates.java)) 28 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/FindDuplicates.py))
29 | Given an array of integers where each value `1 <= x <= len(array)`, write a function that finds all the duplicates in the array. 30 | 31 | * [Integer to Roman Numeral](http://www.byte-by-byte.com/inttoroman/) 32 | ([C++](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/cpp/IntToRoman.cpp)) 33 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/IntToRoman.java)) 34 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/pythopython/IntToRoman.py))
35 | ([Php](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/php/IntToRoman.php))
36 | Given an integer, write a function to return its roman numeral representation. 37 | 38 | * [Autocomplete](http://www.byte-by-byte.com/autocomplete/) ([Github](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/Autocomplete.java)) 39 | Write an autocomplete class that returns all dictionary words with a given prefix. 40 | 41 | * [Linked List Cycle](http://www.byte-by-byte.com/listcycles/) 42 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/LinkedListCycle.java)) 43 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/LinkedListCycle.py))
44 | Given a linked list, determine whether it contains a cycle. 45 | 46 | * [Build Order](http://www.byte-by-byte.com/buildorder/) 47 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/BuildOrder.java)) 48 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/BuildOrder.py))
49 | Given a list of packages that need to be built and the dependencies for each package, determine a valid order in which to build the packages. 50 | 51 | * [Consecutive Array](http://www.byte-by-byte.com/consecutivearray/) 52 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/ConsecutiveArray.java)) 53 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/ConsecutiveArray.py))
54 | Given an unsorted array, find the length of the longest sequence of consecutive numbers in the array. 55 | 56 | * [Zero Matrix](http://www.byte-by-byte.com/zeromatrix/) ([Github](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/ZeroMatrix.java)) 57 | Given a boolean matrix, update it so that if any cell is true, all the cells in that row and column are true. 58 | 59 | * [Random Binary Tree](http://www.byte-by-byte.com/randombinarytree/) ([Github](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/RandomTree.java)) 60 | Implement a binary tree with a method getRandomNode() that returns a random node. 61 | 62 | * [Two Missing Numbers](http://www.byte-by-byte.com/twomissingnumbers/) 63 | ([C++](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/cpp/TwoMissingNumbers.cpp)) 64 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/TwoMissingNumbers.java)) 65 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/TwoMissingNumbers.py))
66 | Given an array containing all the numbers from 1 to n except two, find the two missing numbers. 67 | 68 | * [Shortest Path](http://www.byte-by-byte.com/shortestpath/) ([Github](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/ShortestPath.java)) 69 | Given a directed graph, find the shortest path between two nodes if one exists. 70 | 71 | * [Square Submatrix](http://www.byte-by-byte.com/squaresubmatrix/) 72 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/SquareSubmatrix.java)) 73 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/SquareSubmatrix.py))
74 | Given a 2D array of 1s and 0s, find the largest square subarray of all 1s. 75 | 76 | * [Random Linked List](http://www.byte-by-byte.com/randomlinkedlist/) 77 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/RandomLinkedList.java))
78 | Given a linked list where each node has two pointers, one to the next node and one to a random node in the list, clone the linked list. 79 | 80 | * [Big Int Mod](http://www.byte-by-byte.com/bigintmod/) 81 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/BigIntMod.java)) 82 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/BigIntMod.py))
83 | Given a list of bytes `a`, each representing one byte of a larger integer (ie. `{0x12, 0x34, 0x56, 0x78}` represents the integer `0x12345678`), and an integer `b`, find `a % b`. 84 | 85 | * [Merge K Arrays](http://www.byte-by-byte.com/mergekarrays/) 86 | Given k sorted arrays, merge them into a single sorted array. 87 | 88 | * [Dedup Linked List](http://www.byte-by-byte.com/deduplinkedlist/) 89 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/DedupLinkedList.java)) 90 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/DedupLinkedList.py))
91 | Given an unsorted linked list, write a function to remove all the duplicates. 92 | 93 | * [Lowest Common Ancestor](http://www.byte-by-byte.com/lowestcommonancestor/) 94 | Given two nodes in a binary tree, write a function to find the lowest common ancestor. 95 | 96 | * [String Deletion](http://www.byte-by-byte.com/stringdeletion/) 97 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/StringDeletion.java)) 98 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/StringDeletion.py))
99 | Given a string and a dictionary HashSet, write a function to determine the minimum number of characters to delete to make a word. 100 | 101 | * [Sum](http://www.byte-by-byte.com/sum/) 102 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/Sum.java)) 103 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/Sum.py))
104 | Given two integers, write a function to sum the numbers without using any arithmetic operators. 105 | 106 | * [Reverse Stack](http://www.byte-by-byte.com/reversestack/) 107 | ([C++](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/cpp/ReverseStack.cpp)) 108 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/ReverseStack.java)) 109 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/ReverseStack.py))
110 | Given a stack, reverse the items without creating any additional data structures. 111 | 112 | * [Swap Variables](http://www.byte-by-byte.com/swapvariables/) 113 | ([C++](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/cpp/SwapVariables.cpp)) 114 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/SwapVariables.java)) 115 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/SwapVariables.py))
116 | Given two integers, write a function that swaps them without using any temporary variables. 117 | 118 | * [Matrix Search](http://www.byte-by-byte.com/matrixsearch/) 119 | Given an `n x m` array where all rows and columns are in sorted order, write a function to determine whether the array contains an element `x`. 120 | 121 | * [Clock Angle](http://www.byte-by-byte.com/clockangle/) 122 | ([C++](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/cpp/ClockAngle.cpp)) 123 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/ClockAngle.java)) 124 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/ClockAngle.py))
125 | Given two integers, an hour and a minute, write a function to calculate the angle between the two hands on a clock representing that time. 126 | 127 | * [Fibonacci](http://www.byte-by-byte.com/fibonacci/) 128 | ([C++](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/cpp/Fibonacci.cpp)) 129 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/Fibonacci.java)) 130 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/Fibonacci.py))
131 | Given an integer n, write a function to compute the nth Fibonacci number. 132 | 133 | * [Tree to Doubly Linked List](http://www.byte-by-byte.com/treetolist/) 134 | Given a tree, write a function to convert it into a circular doubly linked list from left to right by only modifying the existing pointers. 135 | 136 | * [Line Intersection](http://www.byte-by-byte.com/lineintersection/) 137 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/LineIntersection.java)) 138 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/LineIntersection.py))
139 | Given two lines on a Cartesian plane, write a function to determine whether or not the lines intersect. 140 | 141 | * [Longest Consecutive Branch](http://www.byte-by-byte.com/longestbranch/) 142 | Given a tree, write a function to find the length of the longest branch of nodes in increasing consecutive order. 143 | 144 | * [Sort Stacks](http://www.byte-by-byte.com/sortstacks/) 145 | Given a stack, sort the elements in the stack using one additional stack. 146 | 147 | * [Print Reversed List](http://www.byte-by-byte.com/printreversedlist/) 148 | ([C++](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/cpp/PrintReversedList.cpp)) 149 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/PrintReversedList.java)) 150 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/PrintReversedList.py))
151 | Given a linked list, write a function that prints the nodes of the list in reverse order. 152 | 153 | * [Longest Common Substring](http://www.byte-by-byte.com/longestsubstring/) 154 | Given two strings, write a function that returns the longest common substring. 155 | 156 | * [Stack from Queues](http://www.byte-by-byte.com/stackfromqueues/) 157 | Implement a LIFO stack with basic functionality (push and pop) using FIFO queues to store the data. 158 | 159 | * [Balanced Binary Tree](http://www.byte-by-byte.com/balancedtree/) 160 | Given a binary tree, write a function to determine whether the tree is balanced. 161 | 162 | * [Gray Code](http://www.byte-by-byte.com/graycode/) 163 | ([C++](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/cpp/GrayCode.cpp)) 164 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/GrayCode.java)) 165 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/GrayCode.py))
166 | Given two integers, write a function to determine whether or not their binary representations differ by a single bit. 167 | 168 | * [Merge Arrays](http://www.byte-by-byte.com/mergearrays/) 169 | Given 2 sorted arrays, A and B, where A is long enough to hold the contents of A and B, write a function to copy the contents of B into A without using any buffer or additional memory. 170 | 171 | * [Zero Sum Subarray](http://www.byte-by-byte.com/zerosum/) 172 | Given an array, write a function to find any subarray that sums to zero, if one exists. 173 | 174 | * [Three Sum](http://www.byte-by-byte.com/threesum/) 175 | Given a list of integers, write a function that returns all sets of 3 numbers in the list, `a`, `b`, and `c`, so that `a + b + c == 0`. 176 | 177 | * [Rotate Bits](http://www.byte-by-byte.com/rotatebits/) 178 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/RotateBits.java)) 179 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/RotateBits.py))
180 | Given a number, write a function to rotate the bits (ie circular shift). 181 | 182 | * [Palindromes](http://www.byte-by-byte.com/palindromes/) 183 | Given a linked list, write a function to determine whether the list is a palindrome. 184 | 185 | * [Permutations](http://www.byte-by-byte.com/permutations/) 186 | Write a function that returns all permutations of a given list. 187 | 188 | * [N Stacks](http://www.byte-by-byte.com/nstacks/) 189 | Implement N > 0 stacks using a single array to store all stack data (you may use auxiliary arrays in your stack object, but all of the objects in all of the stacks must be in the same array). No stack should be full unless the entire array is full. 190 | 191 | * [Tree Level Order](http://www.byte-by-byte.com/treelevelorder/) 192 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/TreeLevelOrder.java)) 193 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/TreeLevelOrder.py))
194 | Given a tree, write a function that prints out the nodes of the tree in level order. 195 | 196 | * [Split Linked List](http://www.byte-by-byte.com/splitlinkedlist/) 197 | Given a linked list, write a function to split the list into two equal halves. 198 | 199 | * [Kth Most Frequest String](http://www.byte-by-byte.com/kthmostfrequentstring/) 200 | Given a list of strings, write a function to get the kth most frequently occurring string. 201 | 202 | * [String Compression](http://www.byte-by-byte.com/stringcompression/) 203 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/StringCompression.java)) 204 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/StringCompression.py))
205 | Given a string, write a function to compress it by shortening every sequence of the same character to that character followed by the number of repetitions. If the compressed string is longer than the original, you should return the original string. 206 | 207 | * [Anagrams](http://www.byte-by-byte.com/anagrams/) 208 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/Anagrams.java)) 209 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/Anagrams.py))
210 | Given two strings, write a function to determine whether they are anagrams. 211 | 212 | * [Binary Search Tree Verification](http://www.byte-by-byte.com/binarysearchtree/) 213 | Given a binary tree, write a function to test if the tree is a binary search tree. 214 | 215 | * [Max Stack](http://www.byte-by-byte.com/maxstack/) 216 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/MaxStack.java)) 217 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/MaxStack.py))
218 | Implement a LIFO stack that has a `push()`, `pop()`, and `max()` function, where `max()` returns the maximum value in the stack. All of these functions should run in `O(1)` time. 219 | 220 | * [Number of Ones in Binary](http://www.byte-by-byte.com/onesinbinary/) 221 | ([C++](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/cpp/OnesInBinary.cpp)) 222 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/OnesInBinary.java)) 223 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/OnesInBinary.py))
224 | Given an integer, write a function to compute the number of ones in the binary representation of the number. 225 | 226 | * [Smallest Change](http://www.byte-by-byte.com/smallestchange/) 227 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/SmallestChange.java)) 228 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/SmallestChange.py))
229 | Given an input amount of change `x`, write a function to determine the minimum number of coins required to make that amount of change. 230 | 231 | * [Nth-to-last Element](http://www.byte-by-byte.com/nthtolastelement) 232 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/NthToLast.java)) 233 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/NthToLast.py))
234 | Given a linked list, and an input n, write a function that returns the nth-to-last element of the linked list. 235 | 236 | * [FizzBuzz](http://www.byte-by-byte.com/fizzbuzz/) 237 | ([C++](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/cpp/FizzBuzz.cpp)) 238 | ([Java](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/java/FizzBuzz.java)) 239 | ([Python](https://github.com/samgh/Byte-by-Byte-Solutions/blob/master/python/FizzBuzz.py))
240 | Output numbers from `1` to `x`. If the number is divisible by `3`, replace it with `“Fizz”`. If it is divisible by `5`, replace it with `“Buzz”`. If it is divisible by `3` and `5` replace it with `“FizzBuzz”`. 241 | 242 | --------------------------------------------------------------------------------