├── 7-Databases
├── SQL
│ ├── README.md~
│ ├── README.md
│ ├── joins
│ │ └── triple.sql
│ └── leetcodeSQL
│ │ └── 175-Combine-Two-Tables
│ │ └── solution.sql
└── README.md
├── _config.yml
├── 1-Sorting-Algorithms
├── Tim_Sort
│ └── Solution.java
├── Bucket_Sort
│ └── Solution.java
├── Intro_Sort
│ └── Solution.java
├── Mergesort
│ └── Solution.java
├── Quicksort
│ └── Solution.java
├── Shell_Sort
│ └── Solution.java
├── Topo_Sort
│ └── Solution.java
├── Insertion_Sort
│ └── Solution.java
├── Selection_Sort
│ └── Solution.java
└── Bubble_Sort
│ └── Solution.java
├── 99-answerKey
├── general
│ ├── dec
│ │ ├── wordLadder.java
│ │ ├── lcs.class
│ │ ├── properGrammer.class
│ │ ├── randomNumbersBlacklisitng.class
│ │ ├── randomNumbersBlacklisting.java
│ │ └── properGrammer.java
│ └── dec-week2
│ │ └── compression.java
├── companies
│ ├── lendingHome
│ │ └── questions.txt
│ ├── twit
│ │ ├── Krak
│ │ │ └── Solution.java
│ │ └── IP
│ │ │ └── Solution.java
│ ├── airbnb
│ │ ├── README.md
│ │ ├── palindromePairs
│ │ │ └── README.md
│ │ ├── Text-Justification
│ │ │ ├── README.md
│ │ │ └── caller.java
│ │ └── meals
│ │ │ └── Solution.java
│ ├── KA
│ │ ├── Set
│ │ │ └── README.md
│ │ └── childNewParent
│ │ │ └── Solution.java
│ ├── pin
│ │ ├── isSubSeq
│ │ │ ├── README.md
│ │ │ └── Solution.java
│ │ └── reachZero
│ │ │ └── Solution.java
│ ├── hackerrank
│ │ └── ladderPrint.java
│ ├── gusto
│ │ ├── IncreasingSub.java
│ │ ├── Holes.java
│ │ ├── questions.txt
│ │ └── payments.java
│ ├── snap
│ │ └── gamelife
│ │ │ └── failed.java
│ ├── yelp
│ │ └── 1-stringcompression
│ │ │ └── stringcompression.java
│ └── thumbtack
│ │ ├── StreamOfInts
│ │ └── Solution.java
│ │ └── meds
│ │ └── RevPolish.java
├── hackerrank
│ ├── cavity-map
│ │ ├── Solution.java~
│ │ └── Solution.java
│ └── Arrays
│ │ └── ArraysDS
│ │ ├── Solution.class
│ │ └── Solution.java
├── utils
│ └── MapSolutions.java
├── algorithms
│ ├── graphSearch
│ │ ├── Edge.class
│ │ ├── Graph.class
│ │ ├── Dijkstra.class
│ │ ├── Dijkstra$VertexDistancePair.class
│ │ ├── Edge.java
│ │ ├── README.md
│ │ ├── Graph.java
│ │ ├── testing.java
│ │ └── Dijkstra.java
│ ├── sorting
│ │ └── comparison-based
│ │ │ ├── Selection-Sort
│ │ │ ├── callSort.java
│ │ │ └── SelectionSort.java
│ │ │ ├── Bubble-Sort
│ │ │ └── BubbleSort.java
│ │ │ ├── Insertion-Sort
│ │ │ └── InsertionSort.java
│ │ │ ├── README.md
│ │ │ ├── Heap-Sort
│ │ │ └── Solution.java
│ │ │ └── quicksort
│ │ │ └── quicksort.java
│ ├── recursion-dynamic
│ │ ├── factorial
│ │ │ └── Solution.java
│ │ └── fibonacci
│ │ │ └── Solution.java
│ ├── allPermutations
│ │ └── Solution.java
│ └── search
│ │ └── binary-search
│ │ └── BinarySearch.java
├── data-structures
│ ├── Linked-List
│ │ ├── CircularLinked
│ │ │ ├── CircularTasks.java
│ │ │ ├── Node.java
│ │ │ └── CircularLinkedList.java
│ │ ├── SinglyLinkedList
│ │ │ ├── Node.java
│ │ │ ├── tinkeringSinglyLinkedList.java
│ │ │ └── TestSinglyLinkedList.java
│ │ ├── DoublyLinkedList
│ │ │ ├── Node.java
│ │ │ └── DoublyTasks.java
│ │ ├── README.md
│ │ └── LinkedList
│ │ │ ├── AbstractDoublyLinkedList.java
│ │ │ └── AbstractLinkedList.java
│ ├── trees
│ │ └── BST
│ │ │ └── BinarySearchTree.java
│ ├── Stack
│ │ ├── StackTest.java
│ │ ├── README.md
│ │ └── Stack.java
│ ├── Queue
│ │ ├── README.md
│ │ └── QueueTest.java
│ └── Graphs
│ │ └── Graph
│ │ ├── Graph.java
│ │ ├── Edge.java
│ │ ├── README.md
│ │ └── testing.java
├── leetcode
│ ├── 291|Word-Pattern-II
│ │ └── Solution.java
│ ├── 266-Palindrome-Permutation
│ │ ├── Solution.class
│ │ └── Solution.java
│ ├── 231-Power-of-Two
│ │ └── Solution.java
│ ├── 9|Palindrome-Number
│ │ └── Solution.java
│ ├── 191|#of-1-Bits
│ │ └── Solution.java
│ ├── 362-Design-HitCounter
│ │ ├── Solution.java
│ │ └── HitCounter.java
│ ├── 206|rev-ll
│ │ └── Solution.java
│ ├── 125|Valid-Palindrome
│ │ └── Solution.java
│ ├── 151|Reverse-Wrd
│ │ └── Solution.java
│ ├── 171|excelsheet-col#
│ │ └── Solution.java
│ ├── 226-Invert-Binary-Tree
│ │ └── Solution.java
│ ├── 104|Max-Depth-BT
│ │ └── Solution.java
│ ├── 121|Best-Time-Buy-Sell
│ │ └── Solution.java
│ ├── 283-Move-Zeroes
│ │ ├── Solution.java
│ │ └── README.md
│ ├── 388-LongestAbsPath
│ │ └── Solution.java
│ ├── 64|MinPathSum
│ │ └── Solution.java
│ ├── 1|Two-Sum
│ │ └── Solutions.java
│ ├── 219-Contains-Duplicate-II
│ │ └── Solution.java
│ ├── 6|ZigZag-Conversion
│ │ └── Solution.java
│ ├── 36|Valid-Sudoku
│ │ └── README.md
│ ├── 49|Group-Anagrams
│ │ └── Solution.java
│ ├── 392-Is-Subsequence
│ │ └── Solution.java
│ ├── 67|Add-Binary
│ │ ├── README.md
│ │ └── Solution.java
│ ├── 290|Word-Pattern-I
│ │ └── Solution.java
│ ├── 2|Add-Two-Numbers
│ │ └── practice
│ │ │ └── addTwoNumbers.java
│ ├── 439-ternary-exprsn-parser
│ │ └── Solution.java
│ ├── 234-Palindrome-LL
│ │ └── Solution.java
│ ├── 438|SubstringAnagrams
│ │ └── Solution.java
│ ├── 38|countNsay
│ │ └── Solution.java
│ └── 68|Text-Justification
│ │ └── caller.java
├── eccentric-hacks
│ └── print-no-main
│ │ └── noMainMethod.java
├── CTCI
│ ├── Ch3-Stacks-Queues
│ │ ├── 4-Queue-via-Stack
│ │ │ ├── Solution.java
│ │ │ ├── Stack.java
│ │ │ └── Node.java
│ │ ├── 2-Stack-Min
│ │ │ └── TestMinStack.java
│ │ └── 3-generic-Stack
│ │ │ └── Stack.java
│ ├── ATM
│ │ └── README.md
│ ├── Ch4-Trees&Graphs
│ │ ├── 3-ListofDepths
│ │ │ └── Solution.java
│ │ ├── 2-MinimalTree
│ │ │ └── TestBST.java
│ │ └── 1-RouteBetweenNodes
│ │ │ ├── TestPath.java
│ │ │ └── Graph.java
│ └── Ch1-Arrays-Strings
│ │ ├── 1-unqiueString
│ │ └── unqiueString.java
│ │ ├── 7-setzeroMatrix
│ │ └── setzeroMatrix.java
│ │ ├── 6-matrixtranspose
│ │ └── matrixtranspose.java
│ │ ├── B4-dromePerm
│ │ └── dromePerm.java
│ │ ├── 2-reverseString
│ │ └── reverseString.java
│ │ └── 3-permutation-Of-Other
│ │ └── permutationOfOther.java
├── concepts
│ └── anonymousmethods
│ │ ├── Car.java
│ │ ├── CarShop.java
│ │ ├── README.md
│ │ ├── Ford.java
│ │ └── test.java
├── genericFrequent
│ ├── invert-BST
│ │ ├── TreeNode.java
│ │ ├── makeBST.java
│ │ └── BST.java
│ ├── wordLadder
│ │ ├── TestWordLadder.java
│ │ └── WordLadder.java
│ ├── printLadder
│ │ └── ladderVPrint.java
│ ├── reading-usr-input
│ │ └── readusrinput.java
│ ├── LongestCommonPrefix
│ │ └── LCPrefix.java
│ ├── Binary-Search
│ │ └── BinarySearch.java
│ ├── getSum
│ │ └── sumints.java
│ ├── repeatingWords
│ │ └── repeatingWords.java
│ └── groupAnagrams
│ │ └── Solution.java
├── codility
│ └── 4-Lesson-Counting-Elements
│ │ └── FrogRiverOne
│ │ └── Solution.java
├── project-Euler
│ ├── 8-prime-1001
│ │ └── thprime.java
│ ├── 9-min-Multiple-20
│ │ └── minMultiple20.java
│ ├── 1-Largest-Prime-Factor
│ │ └── largestPrimeFactor.java
│ └── 2-largest-Product-drome
│ │ └── largestProductdrome.java
├── unicorns
│ └── dynamic
│ │ └── numofwaysCoins
│ │ └── Solution.java
└── interviewcake
│ └── appleStocks
│ └── appleStocks.java
├── 101-General-Concepts
└── Backtracking
│ └── isBipartite
│ └── Solution.java
├── 0-Refresher
├── implement
│ └── graphs_trees
│ │ └── graphs
│ │ ├── unweighted
│ │ ├── Vertex.java
│ │ ├── MDirectedGraph.java
│ │ ├── MUnidirectedGraph.java
│ │ └── Solutions.java
│ │ └── weighted
│ │ └── MDirectedGraph.java
└── CTCI
│ ├── ch1-arrays-and-strings
│ ├── 7-rotation
│ │ ├── Solution.java
│ │ └── Question.java
│ ├── 9-string_rotation
│ │ └── Solution.java
│ ├── 1-is_unique
│ │ └── Solution.java
│ ├── 3-urlify
│ │ └── Solution.java
│ ├── 6-string_compression
│ │ └── Solution.java
│ └── 5-one_away
│ │ └── Solution.java
│ ├── ch3-Stacks_n_Queues
│ ├── 4-QueueAs2Stacks
│ │ ├── Solution.java
│ │ └── MyQueue.java
│ ├── 3-StackOfPlates
│ │ └── Solution.java
│ ├── 1-Array3Stacks
│ │ └── Solution.java
│ ├── 6-DogCatShelter
│ │ └── Solution.java
│ ├── Notes.java
│ └── 5-SortedStack
│ │ ├── ActualSolution.java
│ │ └── Solution.java
│ └── ch2-Linked_list
│ ├── 4-partition
│ ├── Understanding.java
│ └── Solution.java
│ ├── 2-kth_last
│ └── UseRunner.java
│ ├── 3-deleteMiddleNode
│ └── Solution.java
│ ├── 1-remove_dups
│ ├── SolutionNoBuffer.java
│ └── Solution.java
│ ├── implementations
│ ├── Demo.java
│ └── DoublyLinkedList.java
│ ├── 6-IsPalindrome
│ └── StackMid.java
│ └── 8-LoopDetection
│ └── Solution.java
├── 2-Data-Structures
├── LinkedLists
│ ├── CircularLinked
│ │ ├── CircularTasks.java
│ │ ├── Node.java
│ │ └── CircularLinkedList.java
│ ├── SinglyLinkedList
│ │ ├── Node.java
│ │ ├── tinkeringSinglyLinkedList.java
│ │ └── TestSinglyLinkedList.java
│ ├── DoublyLinkedList
│ │ ├── Node.java
│ │ └── DoublyTasks.java
│ ├── README.md
│ └── LinkedList
│ │ ├── AbstractDoublyLinkedList.java
│ │ └── AbstractLinkedList.java
├── Trees
│ ├── Test-tree
│ │ ├── TreeNode.java
│ │ ├── makeBST.java
│ │ └── invertBST.java
│ └── BST.java
├── trie
│ ├── caller.java
│ ├── TrieNode.java
│ └── Trie.java
├── array-vs-linkedlist
│ └── README.md
└── wordladder
│ ├── callpathAttempt.java
│ └── pathAttempt.java
├── 12-EPI
├── README.md
├── ch4
│ ├── maxingOutBits.java
│ ├── pySimple.py
│ ├── sqrRange.js
│ ├── permutable.java
│ └── squaresWithinRange.java
└── ch6-arrays
│ ├── jumpToEndMinSteps
│ └── Solution.java
│ ├── evenOdd
│ └── Solution.java
│ ├── buySellStocks
│ └── Solution.java
│ ├── jumpToTheEnd
│ └── Solution.java
│ ├── deletingDuplicates
│ └── Solution.java
│ └── carryOverAdd
│ └── Solution.java
├── .gitignore
├── 10-Java-DataStructs
└── src
│ ├── Trees
│ ├── BT.java
│ └── TesterTree.java
│ └── Graph
│ └── NonDir
│ └── GraphTesting.java
├── 6-OS
└── README.md
├── 8-Architecture
└── README.md
└── 11-Infrastructure
└── README.md
/7-Databases/SQL/README.md~:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-minimal
--------------------------------------------------------------------------------
/1-Sorting-Algorithms/Tim_Sort/Solution.java:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/99-answerKey/general/dec/wordLadder.java:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1-Sorting-Algorithms/Bucket_Sort/Solution.java:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1-Sorting-Algorithms/Intro_Sort/Solution.java:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1-Sorting-Algorithms/Mergesort/Solution.java:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1-Sorting-Algorithms/Quicksort/Solution.java:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1-Sorting-Algorithms/Shell_Sort/Solution.java:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1-Sorting-Algorithms/Topo_Sort/Solution.java:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/99-answerKey/companies/lendingHome/questions.txt:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/99-answerKey/companies/twit/Krak/Solution.java:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1-Sorting-Algorithms/Insertion_Sort/Solution.java:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1-Sorting-Algorithms/Selection_Sort/Solution.java:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/99-answerKey/hackerrank/cavity-map/Solution.java~:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/101-General-Concepts/Backtracking/isBipartite/Solution.java:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0-Refresher/implement/graphs_trees/graphs/unweighted/Vertex.java:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0-Refresher/implement/graphs_trees/graphs/unweighted/MDirectedGraph.java:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/0-Refresher/implement/graphs_trees/graphs/unweighted/MUnidirectedGraph.java:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/0-Refresher/implement/graphs_trees/graphs/weighted/MDirectedGraph.java:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/99-answerKey/companies/airbnb/README.md:
--------------------------------------------------------------------------------
1 | #Common Airbnb Questions
2 | These are still Leetcode problems
3 |
--------------------------------------------------------------------------------
/0-Refresher/implement/graphs_trees/graphs/unweighted/Solutions.java:
--------------------------------------------------------------------------------
1 | /*
2 | Topological Sort
3 | BFS
4 | DFS
5 | */
--------------------------------------------------------------------------------
/99-answerKey/general/dec/lcs.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ChristianCSE/Interview-Study-Guide/HEAD/99-answerKey/general/dec/lcs.class
--------------------------------------------------------------------------------
/2-Data-Structures/LinkedLists/CircularLinked/CircularTasks.java:
--------------------------------------------------------------------------------
1 | package CircularLinkedList;
2 |
3 | public class CircularTasks
4 | {
5 |
6 | }
7 |
--------------------------------------------------------------------------------
/7-Databases/SQL/README.md:
--------------------------------------------------------------------------------
1 | ### SQL Basics
2 | Doing joins, aggreagate functions, etc.
3 | I will specify when it's specific to MySQL or PostgreSQL
4 |
--------------------------------------------------------------------------------
/99-answerKey/general/dec/properGrammer.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ChristianCSE/Interview-Study-Guide/HEAD/99-answerKey/general/dec/properGrammer.class
--------------------------------------------------------------------------------
/99-answerKey/utils/MapSolutions.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | class MapSolutions {
3 |
4 |
5 |
6 | public static void main(String[] args){
7 |
8 | }
9 | }
--------------------------------------------------------------------------------
/99-answerKey/algorithms/graphSearch/Edge.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ChristianCSE/Interview-Study-Guide/HEAD/99-answerKey/algorithms/graphSearch/Edge.class
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Linked-List/CircularLinked/CircularTasks.java:
--------------------------------------------------------------------------------
1 | package CircularLinkedList;
2 |
3 | public class CircularTasks
4 | {
5 |
6 | }
7 |
--------------------------------------------------------------------------------
/99-answerKey/algorithms/graphSearch/Graph.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ChristianCSE/Interview-Study-Guide/HEAD/99-answerKey/algorithms/graphSearch/Graph.class
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch1-arrays-and-strings/7-rotation/Solution.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Solution {
4 |
5 |
6 | public static void main(String[] args) {
7 |
8 | }
9 | }
--------------------------------------------------------------------------------
/99-answerKey/algorithms/graphSearch/Dijkstra.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ChristianCSE/Interview-Study-Guide/HEAD/99-answerKey/algorithms/graphSearch/Dijkstra.class
--------------------------------------------------------------------------------
/99-answerKey/companies/airbnb/palindromePairs/README.md:
--------------------------------------------------------------------------------
1 | ##Does not pass all the test cases
2 | The array setFail does go through, but the time complexity is too long.
3 |
--------------------------------------------------------------------------------
/99-answerKey/hackerrank/Arrays/ArraysDS/Solution.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ChristianCSE/Interview-Study-Guide/HEAD/99-answerKey/hackerrank/Arrays/ArraysDS/Solution.class
--------------------------------------------------------------------------------
/99-answerKey/leetcode/291|Word-Pattern-II/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution{
2 |
3 |
4 |
5 |
6 |
7 |
8 | public static void main(String[] args){
9 |
10 | }
11 | }
--------------------------------------------------------------------------------
/99-answerKey/general/dec/randomNumbersBlacklisitng.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ChristianCSE/Interview-Study-Guide/HEAD/99-answerKey/general/dec/randomNumbersBlacklisitng.class
--------------------------------------------------------------------------------
/99-answerKey/eccentric-hacks/print-no-main/noMainMethod.java:
--------------------------------------------------------------------------------
1 | class noMainMethod{
2 | static{
3 | System.out.println("no main method");
4 | System.exit(0);
5 | }
6 | }
7 |
8 |
9 |
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch3-Stacks-Queues/4-Queue-via-Stack/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution{
2 |
3 |
4 |
5 |
6 |
7 |
8 | public static void main(String[] args) {
9 |
10 | }
11 | }
--------------------------------------------------------------------------------
/99-answerKey/CTCI/ATM/README.md:
--------------------------------------------------------------------------------
1 | # What is this?
2 | Questions that I came across that categorizing would've taken too long.
3 |
4 | ### I do have plans of eventually organizing them :100: [TBA]
--------------------------------------------------------------------------------
/99-answerKey/data-structures/trees/BST/BinarySearchTree.java:
--------------------------------------------------------------------------------
1 | public class BinarySearchTree{
2 |
3 |
4 |
5 | public BinarySearchTree()
6 | {
7 |
8 | }
9 |
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/266-Palindrome-Permutation/Solution.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ChristianCSE/Interview-Study-Guide/HEAD/99-answerKey/leetcode/266-Palindrome-Permutation/Solution.class
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch3-Stacks-Queues/4-Queue-via-Stack/Stack.java:
--------------------------------------------------------------------------------
1 | class Stack {
2 |
3 | private Node head;
4 | private int size;
5 |
6 | public Stack(){
7 |
8 | }
9 |
10 |
11 |
12 | }
--------------------------------------------------------------------------------
/99-answerKey/algorithms/graphSearch/Dijkstra$VertexDistancePair.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ChristianCSE/Interview-Study-Guide/HEAD/99-answerKey/algorithms/graphSearch/Dijkstra$VertexDistancePair.class
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch3-Stacks-Queues/4-Queue-via-Stack/Node.java:
--------------------------------------------------------------------------------
1 | class Node {
2 |
3 | Node next;
4 | int data;
5 | public Node(int data, Node next) {
6 | this.data = data;
7 | this.next = next;
8 | }
9 | }
--------------------------------------------------------------------------------
/99-answerKey/concepts/anonymousmethods/Car.java:
--------------------------------------------------------------------------------
1 |
2 | public interface Car
3 | {
4 | int getMileage();
5 | String getColor();
6 | int getYearModel();
7 | int daysInShop();
8 | void emptySet(int i);
9 | }
10 |
--------------------------------------------------------------------------------
/2-Data-Structures/LinkedLists/SinglyLinkedList/Node.java:
--------------------------------------------------------------------------------
1 | public class Node{
2 |
3 | int data;
4 | Node next = null;
5 |
6 | //constructor
7 | public Node(int data)
8 | {
9 | this.data = data;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Linked-List/SinglyLinkedList/Node.java:
--------------------------------------------------------------------------------
1 | public class Node{
2 |
3 | int data;
4 | Node next = null;
5 |
6 | //constructor
7 | public Node(int data)
8 | {
9 | this.data = data;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch4-Trees&Graphs/3-ListofDepths/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution{
2 |
3 |
4 |
5 | public static void main(String[] args) {
6 | //Given BST, create a LL of all nodes at each depth.
7 | //Depth D => D LL
8 |
9 | }
10 | }
--------------------------------------------------------------------------------
/2-Data-Structures/LinkedLists/DoublyLinkedList/Node.java:
--------------------------------------------------------------------------------
1 | public class Node{
2 |
3 | int data;
4 | Node next;
5 | Node prev;
6 |
7 | public Node(int data)
8 | {
9 | this.data = data;
10 | next= null;
11 | prev = null;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/99-answerKey/concepts/anonymousmethods/CarShop.java:
--------------------------------------------------------------------------------
1 | public class CarShop
2 | {
3 | int daysInshop;
4 |
5 | public CarShop(){
6 | daysInshop = daysInShop();
7 | }
8 |
9 | public int daysInShop()
10 | {
11 | return 10;
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/99-answerKey/companies/KA/Set/README.md:
--------------------------------------------------------------------------------
1 | #Plain Questions
2 |
3 |
4 | ###Q:Do Sets allow for duplicates? If Set's do not allow for duplicates
5 | explain what occurs when a duplicate does appear.
6 |
7 | A: No, Sets do not allow for duplicate
8 |
9 |
--------------------------------------------------------------------------------
/2-Data-Structures/Trees/Test-tree/TreeNode.java:
--------------------------------------------------------------------------------
1 | public class TreeNode
2 | {
3 | protected int data;
4 | protected TreeNode right;
5 | protected TreeNode left;
6 |
7 | public TreeNode(int data)
8 | {
9 | this.data = data;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Linked-List/DoublyLinkedList/Node.java:
--------------------------------------------------------------------------------
1 | public class Node{
2 |
3 | int data;
4 | Node next;
5 | Node prev;
6 |
7 | public Node(int data)
8 | {
9 | this.data = data;
10 | next= null;
11 | prev = null;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/99-answerKey/genericFrequent/invert-BST/TreeNode.java:
--------------------------------------------------------------------------------
1 | public class TreeNode
2 | {
3 | protected int data;
4 | protected TreeNode right;
5 | protected TreeNode left;
6 |
7 | public TreeNode(int data)
8 | {
9 | this.data = data;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/2-Data-Structures/LinkedLists/CircularLinked/Node.java:
--------------------------------------------------------------------------------
1 | package CircularLinkedList;
2 |
3 | public class Node
4 | {
5 | int data;
6 | Node next;
7 | Node prev;
8 |
9 | public Node(int data)
10 | {
11 | data = 0;
12 | next = null;
13 | prev = null;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Linked-List/CircularLinked/Node.java:
--------------------------------------------------------------------------------
1 | package CircularLinkedList;
2 |
3 | public class Node
4 | {
5 | int data;
6 | Node next;
7 | Node prev;
8 |
9 | public Node(int data)
10 | {
11 | data = 0;
12 | next = null;
13 | prev = null;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/99-answerKey/companies/KA/childNewParent/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 |
3 |
4 |
5 |
6 | public static void main(String[] args) {
7 | //given a tree: move one node and all it's children into another parent
8 | }
9 | }
10 |
11 |
12 | class Tree{
13 | Node root;
14 | int data;
15 |
16 | }
--------------------------------------------------------------------------------
/12-EPI/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # Problem Solving Patterns
4 |
5 | - Sorting
6 | - Recursion
7 | - Divide and conquer
8 | - dynamic programming
9 | - greedy method
10 | - incremental improvement
11 | - elimination
12 | - parallelism
13 | - caching
14 | - randomization
15 | - approximation
16 | - state
17 |
18 |
19 |
--------------------------------------------------------------------------------
/7-Databases/SQL/joins/triple.sql:
--------------------------------------------------------------------------------
1 | --Task: List everyone in a group in a single row
2 | select e.name, array_agg(person.fName), array_agg(person.lName), array_agg(person.pid)
3 | from group e
4 | inner join atLoc on atLoc.locId = e.locId
5 | inner join person on (atLoc.pid = person.pid and person.region = e.region)
6 | group by e.name
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | #OSX
2 | .DS_Store
3 |
4 | #npm
5 | node_modules
6 |
7 | #New Relic
8 | dump.rdb
9 |
10 | #javaC
11 | *.class
12 | *.iml
13 | *.gradle
14 | */local.properties
15 | */.idea/workspace.xml
16 | */.idea/libraries
17 | *.DS_Store
18 | */build
19 | */captures
20 | *bin/
21 | *gen/
22 | .idea/vcs.xml
23 | idea/
24 | idea
25 | .idea
26 | *.idea
--------------------------------------------------------------------------------
/99-answerKey/leetcode/231-Power-of-Two/Solution.java:
--------------------------------------------------------------------------------
1 | // 231. Power of Two
2 | public class Solution {
3 | public boolean isPowerOfTwo(int n)
4 | {
5 | if(n>0)
6 | {
7 | if( (n&n-1) == 0)
8 | {
9 | return true;
10 | }
11 | else
12 | return false;
13 | }
14 | else
15 | return false;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/99-answerKey/hackerrank/Arrays/ArraysDS/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 |
3 | static public void reversit(int[] arr){
4 | int len = arr.length-1;
5 | for(int i = len; i >= 0; i--) {
6 | System.out.print(arr[i] + " ");
7 | }
8 | System.out.println("");
9 | }
10 |
11 | public static void main(String[] args) {
12 | reversit(new int[]{1, 2, 3, 4});
13 | }
14 | }
--------------------------------------------------------------------------------
/99-answerKey/algorithms/sorting/comparison-based/Selection-Sort/callSort.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 | public class callSort{
3 |
4 |
5 | public static void main(String[] args)
6 | {
7 | int[] arr = {3, 44, 1, 90, 43, 89, 22};
8 | SelectionSort sort = new SelectionSort();
9 | System.out.println("Selection Sort O(n^2): " + Arrays.toString(sort.sort(arr)));
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/12-EPI/ch4/maxingOutBits.java:
--------------------------------------------------------------------------------
1 |
2 | public class maxingOutBits {
3 |
4 | static public void decompose(double numb) {
5 | System.out.println("in here=> " + numb);
6 | }
7 |
8 | public static void main(String[] args) {
9 | int[] bitmask = new int[8];
10 | //each index = 8 bit position
11 |
12 | // long container = 9223372036854775807;
13 | // decompose(container);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/12-EPI/ch4/pySimple.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | def isPerfect(numb):
4 | return (math.pow(numb, 0.5)%1 == 0)
5 |
6 |
7 | def printPerfects(arr):
8 | if (len(arr) < 2):
9 | return 0;
10 | start = arr[0];
11 | end = arr[1];
12 | container = [];
13 | for x in range(start,end):
14 | if(isPerfect(x)):
15 | container.append(x)
16 | return container
17 |
18 | print( len(printPerfects([1, 500])) )
--------------------------------------------------------------------------------
/99-answerKey/companies/airbnb/Text-Justification/README.md:
--------------------------------------------------------------------------------
1 | #Failed Case
2 | ###This still does not work
3 |
4 | Currently fails:
5 | ["Here","is","an","example","of","text","justification."] 15
6 |
7 |
8 | My Output: ["Here is an","example of text","justification. "]
9 |
10 |
11 | Expected: ["Here is an","example of text","justification. "]
12 |
13 |
14 |
15 | "Here is an": This is length 19 when it should be 15
16 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/9|Palindrome-Number/Solution.java:
--------------------------------------------------------------------------------
1 | //is the given integer a palindrome
2 |
3 | public class Solution {
4 | public boolean isPalindrome(int x) {
5 | String s = x + "";
6 | s = s.replace(" ", "");
7 | char[] c = s.toCharArray();
8 | int len = c.length;
9 | for(x = 0; x < len/2; x++)
10 | {
11 | if(c[x] != c[len-x-1])
12 | {
13 | return false;
14 | }
15 | }
16 | return true;
17 |
18 | }
19 | }
--------------------------------------------------------------------------------
/10-Java-DataStructs/src/Trees/BT.java:
--------------------------------------------------------------------------------
1 | package Trees;
2 |
3 | /**
4 | * Created by Christian on 12/10/16.
5 | */
6 | public class BT {
7 | Node root;
8 | class Node {
9 | int data;
10 | Node right;
11 | Node left;
12 | public Node(int data){
13 | this.data = data;
14 | }
15 | }
16 |
17 | public BT(int data){
18 | root = new Node(data);
19 | }
20 |
21 | public Node getTree(){
22 | return root;
23 | }
24 |
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/191|#of-1-Bits/Solution.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | // you need to treat n as an unsigned value
3 | public int hammingWeight(int n)
4 | {
5 | int mask = 1, i;
6 | int counted1s = 0;
7 | for(i = 0; i < 32; i++)
8 | {
9 | if( (n&mask) != 0)
10 | {
11 | counted1s++;
12 | }
13 | mask = mask << 1;
14 | }
15 | return counted1s;
16 | }
17 | }
--------------------------------------------------------------------------------
/99-answerKey/leetcode/362-Design-HitCounter/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 |
3 |
4 |
5 |
6 | public static void main(String[] args){
7 | HitCounter obj = new HitCounter();
8 | obj.hit(1);
9 | obj.hit(2);
10 | obj.hit(3);
11 | System.out.println("=>" +obj.getHits(4));
12 | obj.hit(300);
13 | System.out.println("=>" + obj.getHits(300));
14 | System.out.println("=>" + obj.getHits(301));
15 |
16 | }
17 | }
--------------------------------------------------------------------------------
/10-Java-DataStructs/src/Trees/TesterTree.java:
--------------------------------------------------------------------------------
1 | package Trees;
2 |
3 | /**
4 | * Created by Christian on 12/9/16.
5 | */
6 | public class TesterTree {
7 |
8 |
9 | public static void main(String[] args) {
10 | System.out.println("hello");
11 | BST tree = new BST(1);
12 | tree.insert(6);
13 | tree.insert(15);
14 | tree.insert(3);
15 | tree.insert(3);
16 | tree.insert(5);
17 | tree.insert(4);
18 | tree.inOrderTraversal(tree.getTree());
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/99-answerKey/concepts/anonymousmethods/README.md:
--------------------------------------------------------------------------------
1 | # Anonymous Method
2 |
3 | What are they?
4 |
5 | They are:
6 |
7 | What do they look like?
8 |
9 | method( new ImplementsInterface()
10 | ({
11 | public void interfaceMethod (param)
12 | {//...
13 | }
14 | });
15 |
16 | Why do they matter?
17 |
18 | Right now I don't know
19 |
20 | |
21 |
--------------------------------------------------------------------------------
/10-Java-DataStructs/src/Graph/NonDir/GraphTesting.java:
--------------------------------------------------------------------------------
1 | package Graph.NonDir;
2 |
3 | /**
4 | * Created by Christian on 12/11/16.
5 | */
6 | public class GraphTesting {
7 |
8 | public static void main(String[] args) {
9 | Graph graph = new Graph(6);
10 | graph.insertEdge("a", "b", 0);
11 | graph.insertEdge("b", "c", 0);
12 | graph.insertEdge("c", "a", 0);
13 | graph.insertEdge("z", "b", 0);
14 | graph.insertEdge("c", "g", 0);
15 | graph.BFS("a", "g");
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/2-Data-Structures/trie/caller.java:
--------------------------------------------------------------------------------
1 | public class caller{
2 |
3 |
4 | public static void main(String[] args)
5 | {
6 | String[] arr = new String[]{"cat", "catnip", "cats", "cool", "want", "wanter"};
7 | Trie myTrie = new Trie();
8 | myTrie.putarr(arr);
9 | String[] prefixes = new String[]{"cat", "catsp", "lol", "catn", "nono", "wan", "ca", "wantered"};
10 | for(String see: prefixes)
11 | System.out.println(myTrie.containsPrefix(see) + " " + see + " in my Trie");
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/2-Data-Structures/LinkedLists/SinglyLinkedList/tinkeringSinglyLinkedList.java:
--------------------------------------------------------------------------------
1 | public class tinkeringSinglyLinkedList{
2 | public static void main(String[] args)
3 | {
4 | SinglyLinkedList list = new SinglyLinkedList();
5 | int[] nodes = {0, 1, 2, 3, 4, 5, 6, 7};
6 | list.putMultiNodes(nodes);
7 | list.listToString();
8 |
9 | SinglyLinkedList alist = new SinglyLinkedList();
10 | int[] anodes = {10, 11, 12, 13, 14, 15, 16, 27};
11 | alist.putMultiNodes(anodes);
12 | alist.listToString();
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/206|rev-ll/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 |
3 |
4 | //changing after the fact doesn't change the context
5 | //of a previous change
6 | public static ListNode reverseList(ListNode head){
7 | ListNode prev = null;
8 | ListNode curr = head;
9 | ListNode ahead = null;
10 | }
11 |
12 | public static void main(String[] args) {
13 |
14 |
15 | }
16 | }
17 |
18 | public class ListNode {
19 | int val;
20 | ListNode next;
21 | public ListNode(int val){
22 | this.val = val;
23 | }
24 | }
--------------------------------------------------------------------------------
/12-EPI/ch4/sqrRange.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const isPerf = number => (!( Math.pow(number, 0.5)%1));
4 |
5 | const isPerfect = numbs => {
6 | if(numbs.length < 2) {
7 | return 0;
8 | }
9 | let starting = numbs[0];
10 | let ending = numbs[1];
11 | var totalCount= 0;
12 | for(let i = starting+1; i < ending; i++){
13 | if (isPerf(i)) {
14 | totalCount++;
15 | }
16 | }
17 | console.log('this many perfects: ', totalCount);
18 | return totalCount;
19 | }
20 |
21 |
22 |
23 | isPerfect([1, 10])
24 |
--------------------------------------------------------------------------------
/2-Data-Structures/trie/TrieNode.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class TrieNode{
4 | Map children;
5 |
6 | public TrieNode()
7 | {
8 | children = new HashMap<>();
9 | }
10 |
11 |
12 | public TrieNode addChild(char key)
13 | {
14 | TrieNode child = children.get(key);
15 | //if null; then child DNE in Trie
16 | if(child == null)
17 | {
18 | child = new TrieNode();
19 | children.put(key, child);
20 | }
21 | return child;
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/99-answerKey/algorithms/sorting/comparison-based/Bubble-Sort/BubbleSort.java:
--------------------------------------------------------------------------------
1 | public class BubbleSort{
2 |
3 | public int[] sort(int[] arr){
4 | int k = arr.length -1, i, temp;
5 | boolean wire = false;
6 | while(!wire){
7 | wire = true;
8 | for( i = 0; i < k; i++)
9 | {
10 | if (arr[i] > arr[i+1])
11 | {
12 | temp = arr[i];
13 | arr[i] = arr[i+1];
14 | arr[i+1] = temp;
15 | wire = false;
16 | }
17 | }//for()
18 | k--;
19 | }//while()
20 | return arr;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch3-Stacks_n_Queues/4-QueueAs2Stacks/Solution.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Solution {
4 |
5 |
6 |
7 | public static void main(String[] args) {
8 | MyQueue queue = new MyQueue();
9 | queue.add(10);
10 | queue.add(20);
11 | queue.add(30);
12 | queue.add(40);
13 | //returns in reverse order
14 |
15 | System.out.println(queue.poll());
16 |
17 | System.out.println(queue.poll());
18 |
19 | queue.add(50);
20 |
21 | System.out.println(queue.poll());
22 |
23 |
24 | }
25 | }
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Linked-List/SinglyLinkedList/tinkeringSinglyLinkedList.java:
--------------------------------------------------------------------------------
1 | public class tinkeringSinglyLinkedList{
2 | public static void main(String[] args)
3 | {
4 | SinglyLinkedList list = new SinglyLinkedList();
5 | int[] nodes = {0, 1, 2, 3, 4, 5, 6, 7};
6 | list.putMultiNodes(nodes);
7 | list.listToString();
8 |
9 | SinglyLinkedList alist = new SinglyLinkedList();
10 | int[] anodes = {10, 11, 12, 13, 14, 15, 16, 27};
11 | alist.putMultiNodes(anodes);
12 | alist.listToString();
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/2-Data-Structures/LinkedLists/SinglyLinkedList/TestSinglyLinkedList.java:
--------------------------------------------------------------------------------
1 | import static org.junit.Assert.assertEquals;
2 | import static org.junit.Assert.assertFalse;
3 | import static org.junit.Assert.assertTrue;
4 | import org.junit.Ignore;
5 | import org.junit.Test;
6 |
7 | public class TestLinkedList{
8 | @Test
9 | public void testSinglyLinkedList()
10 | {
11 | SinglyLinkedList list = new SinglyLinkedList();
12 | int[] nodes = {0, 1, 2, 3, 4, 5, 6, 7};
13 | list.setAutoLinkedList(nodes);
14 | list.getPrintedList();
15 | }
16 |
--------------------------------------------------------------------------------
/2-Data-Structures/array-vs-linkedlist/README.md:
--------------------------------------------------------------------------------
1 | # Array vs Linked List vs Others
2 |
3 |
4 |
5 |
6 | | Methods |
7 | Linked List Runtimes |
8 | Array Runtimes |
9 | Dynamic Array (ArrayList) Runtimes |
10 | BST |
11 | Random Access List |
12 |
13 |
14 |
15 |
16 | | Indexing |
17 | 1 |
18 | 2 |
19 | 3 |
20 | 4 |
21 | 5 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Linked-List/SinglyLinkedList/TestSinglyLinkedList.java:
--------------------------------------------------------------------------------
1 | import static org.junit.Assert.assertEquals;
2 | import static org.junit.Assert.assertFalse;
3 | import static org.junit.Assert.assertTrue;
4 | import org.junit.Ignore;
5 | import org.junit.Test;
6 |
7 | public class TestLinkedList{
8 | @Test
9 | public void testSinglyLinkedList()
10 | {
11 | SinglyLinkedList list = new SinglyLinkedList();
12 | int[] nodes = {0, 1, 2, 3, 4, 5, 6, 7};
13 | list.setAutoLinkedList(nodes);
14 | list.getPrintedList();
15 | }
16 |
--------------------------------------------------------------------------------
/2-Data-Structures/wordladder/callpathAttempt.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class callpathAttempt{
4 |
5 | public static void main(String[] args)
6 | {
7 | String[] myWords = new String[]{"hot","dot","dog","lot","log"};
8 | Set wordList = new HashSet<>(Arrays.asList(myWords));
9 | String beginWord = "hit";
10 | String endWord = "cog";
11 | //non-static methods; hence need instance of path (Implied constructor)
12 | PathSolution caller = new PathSolution();
13 | System.out.println(caller.pathLength(beginWord, endWord, wordList));
14 | }
15 |
--------------------------------------------------------------------------------
/99-answerKey/companies/airbnb/Text-Justification/caller.java:
--------------------------------------------------------------------------------
1 |
2 | public class caller{
3 |
4 | public static void main(String[] args)
5 | {
6 | Solution call = new Solution();
7 | String[] candidate = new String[]{"This", "is", "an", "example", "of", "text", "justification."};
8 | String[] blanks = new String[]{""};
9 | String[] letters = new String[]{"a","b","c","d","e"};
10 | String[] moreStrings = new String[]{"Listen","to","many,","speak","to","a","few."};
11 |
12 |
13 | System.out.println(call.fullJustify(moreStrings, 6));
14 |
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/99-answerKey/companies/pin/isSubSeq/README.md:
--------------------------------------------------------------------------------
1 | # Success!
2 | NOTE: It is asking for the existence of a subsequence; hence, we don't
3 | care about length. In other words, we just care if the subsequence
4 | exists wrt order.
5 |
6 |
7 |
8 | # Fails DP :shit:
9 | Passes 12/12 cases but there is a memory limit exceeded fault.
10 | I don't post the fail case due to it containing an extremely long string which takes forever to load.
11 | I can post the s string:
12 |
13 | String s = ""gggsgguggggbsggggggggggggggggggggegggggggggggqgugggegggggggggggggggngggggggcggggggggggggeggggggggggg""
--------------------------------------------------------------------------------
/99-answerKey/concepts/anonymousmethods/Ford.java:
--------------------------------------------------------------------------------
1 | public class Ford extends CarShop implements Car
2 | {
3 |
4 | int miles;
5 | String color;
6 | int year;
7 |
8 | public Ford(int miles, String color, int year)
9 | {
10 | this.miles = miles;
11 | this.color = color;
12 | this.year = year;
13 | }
14 |
15 | public int getMileage()
16 | {
17 | return miles;
18 | }
19 |
20 | public String getColor(){
21 | return color;
22 | }
23 |
24 | public int getYearModel()
25 | {
26 | return year;
27 | }
28 |
29 | public void emptySet(int i)
30 | {
31 |
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch3-Stacks-Queues/2-Stack-Min/TestMinStack.java:
--------------------------------------------------------------------------------
1 | import static org.junit.Assert.*;
2 | import org.junit.Test;
3 | public class TestMinStack
4 | {
5 |
6 | @Test
7 | public void testStack() {
8 | MinStack stack = new MinStack<>();
9 | String aBet = "bcdefghijklmnopqrstuvwxyza";
10 | String[] input = aBet.split("");
11 | for(String letter: input){
12 | stack.push(letter);
13 | }
14 | assertEquals("a", stack.getMin());
15 | assertEquals("a", stack.pop());
16 | assertEquals("z", stack.pop());
17 | assertEquals("b", stack.getMin());
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/99-answerKey/genericFrequent/wordLadder/TestWordLadder.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by christian on 5/22/16.
3 | */
4 | package wordLadder;
5 | import java.util.*;
6 | public class TestWordLadder {
7 | String[] arrayWord = new String[]{"hot","dot","dog","lot","log"};
8 | Set fakeTree = new HashSet<>(Arrays.asList(arrayWord));
9 | String startWord = "hit";
10 | String endWord = "cog";
11 | WordLadder result = DFSWordLadder.getPathNow(startWord, endWord, fakeTree);
12 | System.out.println(result.getPathLength());
13 | // result.getPath();
14 |
15 |
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/99-answerKey/concepts/anonymousmethods/test.java:
--------------------------------------------------------------------------------
1 | public class test{
2 |
3 |
4 | public static void emptySet(Car aCar)
5 | {
6 | for(int i = 0; i < 10; i++)
7 | {
8 | aCar.emptySet(i);
9 | }
10 | }
11 | public static void main(String[] args)
12 | {
13 | Car emptyCar = new Ford(0, "blue", 2016);
14 | emptySet(emptyCar);
15 |
16 | emptySet(new Ford(900, "red", 1999) {
17 | @Override
18 | public void emptySet(int i)
19 | {
20 | System.out.println(i);
21 | }
22 | });
23 |
24 | Car myCar = new Ford(90, "blue", 2010);
25 | emptySet(myCar);
26 |
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/125|Valid-Palindrome/Solution.java:
--------------------------------------------------------------------------------
1 | //give an alphanumeric phrase determine if it is a palindrome
2 | //ignore punctutation, nonalpha, etc. Still consider the phrase
3 | //as long as alphanumeric chars match.
4 | public class Solution {
5 | public boolean isPalindrome(String s)
6 | {
7 | s = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
8 | char[] letter = s.toCharArray();
9 | int len = letter.length;
10 | for(int i = 0; i < len/2; i++)
11 | {
12 | if(letter[i] != letter[len-i-1])
13 | {
14 | return false;
15 | }
16 | }
17 | return true;
18 | }
19 | }
--------------------------------------------------------------------------------
/99-answerKey/algorithms/sorting/comparison-based/Selection-Sort/SelectionSort.java:
--------------------------------------------------------------------------------
1 | public class SelectionSort{
2 |
3 | //implicit constructor
4 |
5 | public int[] sort(int[] arr)
6 | {
7 | int temp;
8 | int min_index;
9 | for(int i = 0; i < arr.length; i++)
10 | {
11 | //assume min index
12 | min_index = i;
13 | for(int j = i + 1; j < arr.length; j++)
14 | {
15 | if(arr[min_index] > arr[j])
16 | {
17 | min_index = j;
18 | }
19 | }
20 | //update
21 | temp = arr[i];
22 | arr[i] = arr[min_index];
23 | arr[min_index] = temp;
24 | }
25 | return arr;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/151|Reverse-Wrd/Solution.java:
--------------------------------------------------------------------------------
1 |
2 | public class Solution {
3 | public String reverseWords(String s) {
4 |
5 | String[] chopS = s.split("\\s+");
6 | String back2Front = ""; //will be expensive
7 | int length = chopS.length;
8 |
9 | for(int i = length-1; i >= length/2; i--)
10 | {
11 | back2Front = back2Front + chopS[i] + " ";
12 | }
13 |
14 | for(int i = (length/2 - 1); i > -1; i--)
15 | {
16 | back2Front = back2Front + chopS[i] + " ";
17 | }
18 | return back2Front.trim();
19 | }
20 | }
--------------------------------------------------------------------------------
/99-answerKey/companies/hackerrank/ladderPrint.java:
--------------------------------------------------------------------------------
1 | class ladderVPrint{
2 |
3 |
4 | public static void printStairs(int n)
5 | {
6 | int j = 0, i;
7 | for(i = n; i > 1; i--)
8 | {
9 | for(j = 0; j < i; j++)
10 | {
11 | System.out.print('*');
12 | }
13 | System.out.println();
14 | }
15 | for (i = 1; i <= n; i++)
16 | {
17 | for (j = 0; j < i; j++)
18 | {
19 | System.out.print('*');
20 | }
21 | System.out.println();
22 | }
23 |
24 | }
25 |
26 | public static void main(String[] args)
27 | {
28 | printStairs(5);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/99-answerKey/algorithms/sorting/comparison-based/Insertion-Sort/InsertionSort.java:
--------------------------------------------------------------------------------
1 | public class InsertionSort{
2 | public static void sort(int[] arr)
3 | {
4 | int len = arr.length, i, j;
5 | for(i = 1; i < len; i++)
6 | for(j = i; j > 0 && arr[j] < arr[j-1]; j--)
7 | {
8 | swap(arr, j, j-1);
9 | }
10 | System.out.println(java.util.Arrays.toString(arr));
11 | }
12 | public static void swap(int[] arr, int a, int b)
13 | {
14 | int temp = arr[a];
15 | arr[a] = arr[b];
16 | arr[b] = temp;
17 | }
18 |
19 | public static void main(String[] args)
20 | {
21 | sort(new int[]{8, 2, 1, 4});
22 | }
23 | }
24 |
25 |
--------------------------------------------------------------------------------
/99-answerKey/genericFrequent/printLadder/ladderVPrint.java:
--------------------------------------------------------------------------------
1 | class ladderVPrint{
2 |
3 |
4 | public static void printStairs(int n)
5 | {
6 | int j = 0, i;
7 | for(i = n; i > 1; i--)
8 | {
9 | for(j = 0; j < i; j++)
10 | {
11 | System.out.print('*');
12 | }
13 | System.out.println();
14 | }
15 | for (i = 1; i <= n; i++)
16 | {
17 | for (j = 0; j < i; j++)
18 | {
19 | System.out.print('*');
20 | }
21 | System.out.println();
22 | }
23 |
24 | }
25 |
26 | public static void main(String[] args)
27 | {
28 | printStairs(5);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/99-answerKey/genericFrequent/reading-usr-input/readusrinput.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | /*
3 | reads user input and stores in an array; prints the array
4 | filed with String objects
5 | **/
6 | class readusrinput{
7 |
8 | public static void main(String[] args)
9 | {
10 | Scanner input = new Scanner(System.in);
11 | String usr;
12 | String[] store = new String[10];
13 | int len = store.length;
14 | int i = 0;
15 | while( ( ( usr = input.nextLine() ) != null) && i < len )
16 | {
17 | store[i] = usr;
18 | i++;
19 | }
20 | System.out.println( Arrays.deepToString(store) );
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch3-Stacks_n_Queues/3-StackOfPlates/Solution.java:
--------------------------------------------------------------------------------
1 |
2 | import java.util.*;
3 |
4 | class Solution {
5 |
6 |
7 |
8 |
9 | public static void main(String[] args) {
10 | List> stacks = new ArrayList<>();
11 | stacks.add(new ArrayDeque<>());
12 | stacks.get(0).push(10);
13 | // System.out.println(stacks.get(stacks.size()-1));
14 | stacks.add(new ArrayDeque<>());
15 | stacks.get(1).push(11);
16 | System.out.println("List => " + stacks);
17 | stacks.remove(0); //removes the list entirely!
18 | //shifts everything to the left for you
19 | System.out.println("List => " + stacks);
20 | }
21 | }
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Stack/StackTest.java:
--------------------------------------------------------------------------------
1 | package datastructures.stack;
2 | import static org.junit.Assert.*;
3 | import java.util.Map.Entry;
4 | import org.junit.Test;
5 | public class StackTest
6 | {
7 | @Test
8 | public void testStack() {
9 | Stack stack = new Stack<>();
10 | String aBet = "abcdefghijklmnopqrstuvwxyz";
11 | String[] input = aBet.split("");
12 | for(String letter: input){
13 | stack.push(letter);
14 | }
15 | assertEquals("z", stack.pop());
16 | assertEquals("y", stack.pop());
17 | assertEquals("x", stack.pop());
18 | assertEquals("w", stack.pop());
19 | assertEquals("v", stack.pop());
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/171|excelsheet-col#/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 |
3 | public static int titleToNumber(String s){
4 | char[] c = s.toCharArray();
5 | int len = c.length;
6 | int excel = 0;
7 | for(int i = 0; i < len ; i++){
8 | int helper = (c[i]-64)*(int)(Math.pow(26, (len-1-i)));
9 | excel = excel + helper;
10 | }
11 | return excel;
12 | }
13 |
14 |
15 |
16 | public static void main(String[] args){
17 | System.out.println(titleToNumber("AB")); // 28
18 | System.out.println(titleToNumber("BA"));
19 | System.out.println(titleToNumber("AA"));//27
20 | System.out.println(titleToNumber("A"));
21 |
22 |
23 | }
24 | }
--------------------------------------------------------------------------------
/12-EPI/ch6-arrays/jumpToEndMinSteps/Solution.java:
--------------------------------------------------------------------------------
1 | // import java.util.*;
2 |
3 | // class Solution {
4 |
5 |
6 | // public static int minStepsToEnd(List list) {
7 | // int newJump = 0;
8 | // int reachableRange = 0;
9 | // int ending = list.size() - 1;
10 | // List fromStep = new ArrayList<>();
11 | // for(int i = 0; i <= reachableRange && reachableRange < ending; i++) {
12 | // int determinedMax = Math.max(i + list.get(i), reachableRange);
13 |
14 | // newJump += (determinedMax != reachableRange) ? 1 : 0;
15 |
16 | // }
17 | // return 0;
18 | // }
19 |
20 |
21 | // public static void main(String[] args) {
22 |
23 | // }
24 | // }
--------------------------------------------------------------------------------
/2-Data-Structures/Trees/Test-tree/makeBST.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | public class makeBST{
3 |
4 | public static void main(String[] args)
5 | {
6 | invertBST invertCaller = new invertBST();
7 | TreeNode one = new TreeNode(1);
8 | TreeNode two = new TreeNode(2);
9 | TreeNode three = new TreeNode(3);
10 | TreeNode four = new TreeNode(4);
11 | TreeNode five = new TreeNode(5);
12 | TreeNode six = new TreeNode(6);
13 | TreeNode seven = new TreeNode(7);
14 | one.left = two;
15 | one.right = three;
16 | two.left = four;
17 | two.right = five;
18 | three.left = six;
19 | three.right = seven;
20 | invertCaller.invertTree(one);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/99-answerKey/genericFrequent/invert-BST/makeBST.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | public class makeBST{
3 |
4 | public static void main(String[] args)
5 | {
6 | invertBST invertCaller = new invertBST();
7 | TreeNode one = new TreeNode(1);
8 | TreeNode two = new TreeNode(2);
9 | TreeNode three = new TreeNode(3);
10 | TreeNode four = new TreeNode(4);
11 | TreeNode five = new TreeNode(5);
12 | TreeNode six = new TreeNode(6);
13 | TreeNode seven = new TreeNode(7);
14 | one.left = two;
15 | one.right = three;
16 | two.left = four;
17 | two.right = five;
18 | three.left = six;
19 | three.right = seven;
20 | invertCaller.invertTree(one);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch2-Linked_list/4-partition/Understanding.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Understanding {
4 |
5 |
6 | public static Node partition(Node node, int x) {
7 |
8 | return null;
9 | }
10 |
11 | public static void main(String[] args) {
12 |
13 | //3, 1, 5, 7, 8, 2, 9, 1
14 | //x = 5
15 | //3, 1, 2, 1, 5, 7, 8, 9
16 | Node head = new Node(3);
17 | Node ptr = head;
18 | for(int i: new int[]{}){
19 | ptr.next = new Node(i);
20 | ptr = ptr.next;
21 | }
22 | ptr = head;
23 | partition(ptr, 5);
24 | }
25 | }
26 |
27 |
28 | class Node {
29 |
30 | int data;
31 | Node next;
32 |
33 | public Node(int data) {
34 | this.data = data;
35 | }
36 | }
--------------------------------------------------------------------------------
/99-answerKey/codility/4-Lesson-Counting-Elements/FrogRiverOne/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | static public int solution(int X, int[] A) {
3 | int req_leaves = X;
4 | boolean[] pond = new boolean[X+1];
5 | for(int i = 0; i < A.length; i++) {
6 | int spot = A[i];
7 | if(!pond[spot]) {
8 | pond[spot] = true;
9 | req_leaves--;
10 | if(req_leaves == 0) {return i;}
11 | }
12 | }
13 | return -1;
14 | }
15 |
16 | public static void main(String[] args) {
17 | int[] pond = new int[]{1, 3, 1, 4, 2, 3, 5, 4};
18 | int land = 5;
19 | System.out.println(solution(land, pond));
20 | }
21 | }
22 |
23 |
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch4-Trees&Graphs/2-MinimalTree/TestBST.java:
--------------------------------------------------------------------------------
1 | class TestBST{
2 |
3 | public static void inOrder(BST.Node node, String dir, int stem){
4 | if(node!=null){
5 | if(node.data != stem) System.out.println(dir+ stem + " -> "+node.data);
6 | else System.out.println(dir+ " : " + node.data);
7 | inOrder(node.left, "left of ", node.data);
8 | inOrder(node.right, "right of ", node.data);
9 | }
10 | else{
11 | System.out.println(" /stop/");
12 | }
13 | }
14 | public static void main(String[] args) {
15 | BST tree = new BST(0);
16 | int[] incr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
17 | BST.Node root = tree.getMinHeightBST(incr, 0, incr.length-1);
18 | inOrder(root, "root", root.data);
19 | }
20 | }
--------------------------------------------------------------------------------
/99-answerKey/leetcode/226-Invert-Binary-Tree/Solution.java:
--------------------------------------------------------------------------------
1 | // 226. Invert Binary Tree
2 |
3 | /**
4 | * Definition for a binary tree node.
5 | * public class TreeNode {
6 | * int val;
7 | * TreeNode left;
8 | * TreeNode right;
9 | * TreeNode(int x) { val = x; }
10 | * }
11 | */
12 | //given the root
13 | public class Solution {
14 | public TreeNode invertTree(TreeNode root) {
15 | if(root == null) {return null;}
16 | TreeNode temp = root.left;
17 | root.left = root.right;
18 |
19 | root.right = temp;
20 |
21 | if(root.left != null){invertTree(root.left); }
22 | if(root.right != null){ invertTree(root.right); }
23 | return root;
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch3-Stacks_n_Queues/1-Array3Stacks/Solution.java:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | class Solution {
5 |
6 |
7 | public static void main(String[] args) throws Exception{
8 | ArrayStacks myStacks = new ArrayStacks(2);
9 | myStacks.add(1, 10);
10 | myStacks.add(1, 100);
11 | myStacks.add(0, 100);
12 | myStacks.add(0, 100);
13 | myStacks.printStacks();
14 | System.out.println("\nPOPPED HEAD=> " + myStacks.pop(0));
15 | myStacks.printStacks();
16 | myStacks.add(0, 300);
17 | myStacks.printStacks();
18 | System.out.println("\nPOPPED HEAD=> " + myStacks.pop(0));
19 | myStacks.printStacks();
20 | System.out.println("\nPOPPED HEAD=> " + myStacks.pop(0));
21 | myStacks.printStacks();
22 | myStacks.peek(0);
23 | }
24 | }
--------------------------------------------------------------------------------
/2-Data-Structures/LinkedLists/README.md:
--------------------------------------------------------------------------------
1 | #Linked Lists
2 | Types:
3 |
4 | - Singly Linked List
5 | - Doubly Linked List
6 | - Circular Linked List
7 | - Linked List
8 |
9 | - This is an abstract class that defines the general skeleton for linked lists. In other words, these are conventional methods required in Linked Lists: Circular, Linear, and Doubly.
10 | - I need to make this just a single abstract class in order for it to work universally, hence any methods that are distinct to a Linked List Type will not be included.
11 | - All the ___Task.java classes have some similar required functionality; hence I might make an Abstract Class for this as well.
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/7-Databases/SQL/leetcodeSQL/175-Combine-Two-Tables/solution.sql:
--------------------------------------------------------------------------------
1 | --Person
2 | -- +-------------+---------+
3 | -- | Column Name | Type |
4 | -- +-------------+---------+
5 | -- | PersonId | int |
6 | -- | FirstName | varchar |
7 | -- | LastName | varchar |
8 | -- +-------------+---------+
9 | --
10 |
11 | --Address
12 | -- +-------------+---------+
13 | -- | Column Name | Type |
14 | -- +-------------+---------+
15 | -- | AddressId | int |
16 | -- | PersonId | int |
17 | -- | City | varchar |
18 | -- | State | varchar |
19 | -- +-------------+---------+
20 |
21 |
22 |
23 |
24 | -- Write your MySQL query statement below
25 | select p.FirstName, p.LastName, a.City, a.State
26 | from Person p
27 | left join Address a on a.PersonId = p.PersonId
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Linked-List/README.md:
--------------------------------------------------------------------------------
1 | #Linked Lists
2 | Types:
3 |
4 | - Singly Linked List
5 | - Doubly Linked List
6 | - Circular Linked List
7 | - Linked List
8 |
9 | - This is an abstract class that defines the general skeleton for linked lists. In other words, these are conventional methods required in Linked Lists: Circular, Linear, and Doubly.
10 | - I need to make this just a single abstract class in order for it to work universally, hence any methods that are distinct to a Linked List Type will not be included.
11 | - All the ___Task.java classes have some similar required functionality; hence I might make an Abstract Class for this as well.
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/99-answerKey/algorithms/recursion-dynamic/factorial/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | public class Solution {
3 | //factorial Dynamic
4 | public static int dynamicFactorial(int n) {
5 | if (n == 0)
6 | return 1;
7 | int fact = 1;
8 | for (int i = 1; i <= n; i++) {
9 | fact *= i;
10 | }
11 | return fact;
12 | }
13 |
14 | public static int recursiveFactorial(int n) {
15 | if (n == 0 || n == 1) {
16 | return 1;
17 | }
18 | return n * recursiveFactorial(n-1);
19 | }
20 |
21 | public static void main(String[] args)
22 | {
23 | Scanner input = new Scanner(System.in);
24 | int r;
25 | System.out.println("What factorial do you want to know?");
26 | r = input.nextInt();
27 | System.out.println(r+"! = " + recursiveFactorial(r));
28 |
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/104|Max-Depth-BT/Solution.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Solution {
4 |
5 | public static int maxDepth(TreeNode root){
6 | TreeNode node = root;
7 | return recursMax(node, 0);
8 | }
9 |
10 | public static int recursMax(TreeNode node, int depth){
11 | if(node == null){
12 | return depth;
13 | }
14 | depth = depth+1;
15 | int left = recursMax(node.left, depth);
16 | int right = recursMax(node.right, depth);
17 | return left>right ? left : right;
18 | }
19 |
20 |
21 |
22 | public static void main(String[] args){
23 |
24 |
25 | }
26 | }
27 |
28 |
29 | class TreeNode {
30 |
31 | int val;
32 | TreeNode left;
33 | TreeNode right;
34 | public TreeNode(int val){
35 | this.val = val;
36 | left = null;
37 | right = null;
38 | }
39 | }
--------------------------------------------------------------------------------
/99-answerKey/genericFrequent/wordLadder/WordLadder.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by christian on 5/22/16.
3 | */
4 | package wordLadder;
5 | import java.util.*;
6 | class WordLadder {
7 | private List path;
8 | private String currentWord;
9 | private int pathLength;
10 |
11 | public WordLadder(List path, String currentWord, int pathLength)
12 | {
13 | this.path = path;
14 | this.currentWord = currentWord;
15 | this.pathLength = pathLength;
16 | }
17 |
18 | public List getPath()
19 | {
20 | return path;
21 | }
22 |
23 | public String getCurrentWord()
24 | {
25 | return currentWord;
26 | }
27 |
28 | public int getPathLength()
29 | {
30 | return pathLength;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch1-arrays-and-strings/9-string_rotation/Solution.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Solution {
4 |
5 | /*tbh how would you notice this??*/
6 | public static boolean isRotation(String str1, String str2) {
7 |
8 | if(str1.length() != str2.length()) return false;
9 |
10 | String trick = str1 + str1;
11 | return (trick.indexOf(str2) > 0) ? true : false;
12 | }
13 |
14 | public static void main(String[] args) {
15 | String str1 = "waterbottle";
16 | String str2 = "ttlewaterbo";
17 | System.out.println(isRotation(str1, str2));
18 | str1 = "waterbottle";
19 | str2 = "erbottlewat";
20 | System.out.println(isRotation(str1, str2));
21 | str1 = "waterbottle";
22 | str2 = "waterelottb";
23 | System.out.println(isRotation(str1, str2));
24 | }
25 | }
--------------------------------------------------------------------------------
/99-answerKey/leetcode/121|Best-Time-Buy-Sell/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 |
3 | public static int maxProfit(int[] prices){
4 | int len = prices.length;
5 | if(len < 1 ){return 0;}//can't buy/sell 1 stock
6 | int maxProfit = 0;
7 | int min = prices[0];
8 | for(int i= 1; i < len; i++){
9 | int curr = prices[i];
10 | int profit = curr - min; //min came before, curr => after
11 | maxProfit = (maxProfit>profit)? maxProfit:profit;
12 | min = (min= 0; i--){
12 | if(nums[i]==0){
13 | for(int ptr = i; ptr < len-1; ptr++)
14 | {
15 | int temp = nums[ptr];
16 | nums[ptr] = nums[ptr+1];
17 | nums[ptr+1] = temp;
18 | }//for()
19 | }//if()
20 | }//for()
21 | }
22 |
23 | public static void testerArr(int[] arr)
24 | {
25 | moveZeroes(arr);
26 | System.out.println(java.util.Arrays.toString(arr));
27 | }
28 |
29 | public static void main(String[] args)
30 | {
31 | testerArr(new int[]{0, 1, 0, 3, 12});
32 | testerArr(new int[]{0, 0, 1});
33 | }
34 | }
35 |
36 |
37 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/388-LongestAbsPath/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | /*
4 | dir
5 | subdir1
6 | subdir2
7 | file.ext
8 | ==>
9 | "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
10 | */
11 |
12 | /*
13 | Time complexity required: O(n) where n is the size of the input string.
14 | Notice that a/aa/aaa/file1.txt is not the longest file path,
15 | if there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png
16 | */
17 |
18 | class Solution {
19 |
20 |
21 |
22 |
23 | public static int lengthLongestPath(String input) {
24 |
25 | String parent = "";
26 | int curr=0;
27 | while(input.charAt(curr)!= '/'){
28 | parent += input.charAt(curr);
29 | }
30 | curr = curr + 3;
31 | Syste
32 |
33 | return 0;
34 | }
35 |
36 | public static void main(String[] args){
37 |
38 | }
39 | }
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Queue/README.md:
--------------------------------------------------------------------------------
1 |
2 | #Queue API:
3 |
4 | [Java SDK](http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/c228a234a3f3/src/share/classes/java/util/Queue.java)
5 |
[Sedgewick](http://algs4.cs.princeton.edu/13stacks/Queue.java.html)
6 |
7 | ###Queue API defined by CTIC & Sedgewick
8 | add(item)
9 | remove()
10 | peek()
11 | isEmpty()
12 | int size () [sedgewidge]
13 |
14 | ###Queue in Java JDK
15 | public interface Queue extends Collection
16 | boolean add(E e)
17 | boolean offer(E e)
18 | E remove() ( throws exception if empty )
19 | throw new NoSuchElementException()
20 | E poll() (null if head is empty)
21 | E element()
22 | E peek()
23 | void clear()
24 | public boolean addAll(Collection extends E> c)
25 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch1-arrays-and-strings/1-is_unique/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class Solution {
4 |
5 |
6 | public static boolean isUnique(String candidate) {
7 | Set set = new HashSet<>();
8 |
9 | for(char c: candidate.toCharArray()) {
10 | if(set.contains(c)) {
11 | return false;
12 | } else {
13 | set.add(c);
14 | }
15 | }
16 | return true;
17 | }
18 |
19 | public static boolean isUniqueNoDS(String candidate) {
20 |
21 | return true;
22 | }
23 |
24 | public static void main(String[] args) {
25 | String candidate = "helloperson";
26 | System.out.println( candidate + " all unique chars: " + isUnique(candidate));
27 | candidate = "abcd";
28 | System.out.println( candidate + " all unique chars: " + isUnique(candidate));
29 | }
30 | }
--------------------------------------------------------------------------------
/12-EPI/ch6-arrays/evenOdd/Solution.java:
--------------------------------------------------------------------------------
1 | /*
2 | All evens in the front, all odds in the back
3 | No Auxillary Array!
4 | */
5 |
6 | class Solution {
7 | static public int[] evenThenOdd(int[] A) {
8 | int evenCandidate = 0, oddCandidate = A.length -1;
9 | //two pointer
10 | while(evenCandidate < oddCandidate) {
11 | if(A[evenCandidate]%2==0) {
12 | evenCandidate++; //keep it here
13 | } else {
14 | int temp = A[oddCandidate]; //let's see if even
15 | A[oddCandidate] = A[evenCandidate]; //even gets position of odd now
16 | A[evenCandidate] = temp;
17 | oddCandidate--;
18 | }
19 | }
20 | return A;
21 | }
22 |
23 | public static void main(String[] args) {
24 | System.out.println(java.util.Arrays.toString(evenThenOdd(new int[]{1, 3, 4, 6, 8, 2, 3})));
25 | }
26 | }
--------------------------------------------------------------------------------
/99-answerKey/project-Euler/8-prime-1001/thprime.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | //get the 1001th prime
3 | public class thprime {
4 |
5 | private static boolean isitprime(long tester) {
6 | for(long i = 3; i < tester; i = i + 2){
7 | if(tester%i == 0)
8 | {
9 | return false;
10 | }
11 | }
12 | return true;
13 | }
14 |
15 | public static void get1001th()
16 | {
17 | long th = 1; //2 = 1st prime
18 | long tester = 3; //start at the 2nd valid prime
19 | while(true)
20 | {
21 | if(isitprime(tester))
22 | {
23 | th++;
24 | if(th == 10001)
25 | {
26 | break;
27 | }
28 | }
29 | tester = tester + 2; //skip evens
30 | }
31 | System.out.println(tester + "is the " + th + "th prime");
32 | }
33 |
34 | public static void main (String args[])
35 | {
36 | get1001th();
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/99-answerKey/companies/gusto/IncreasingSub.java:
--------------------------------------------------------------------------------
1 | class IncreasingSub {
2 |
3 |
4 | public static String incrSequence(String word){
5 |
6 | if(word==null){return "";}
7 | int maxCount = 1;
8 | String currMax = ""+word.charAt(0);
9 |
10 | String cache = currMax;
11 | int len = word.length();
12 |
13 | for(int i = 1; i < len; i++){
14 | char curr = word.charAt(i);
15 | int diff = curr - word.charAt(i-1);
16 | if(diff > 0){
17 | cache = cache + curr;
18 | if(cache.length() > currMax.length()){
19 | currMax = cache;
20 | }
21 | } else {
22 | cache = ""+curr;
23 | }
24 | }
25 |
26 | System.out.println("incr subsequence: " + currMax);
27 | return currMax;
28 | }
29 |
30 |
31 | public static void main(String[] args){
32 | incrSequence("pandora");
33 | incrSequence("helloabcdpluswhatisthis");
34 | }
35 | }
--------------------------------------------------------------------------------
/99-answerKey/algorithms/allPermutations/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 |
3 |
4 | public static void permute(int[] arr){
5 | int len = arr.length;
6 | permute(arr, len);
7 | }
8 |
9 | public static void permute(int[] arr, int len){
10 | if(len == 1){
11 | System.out.println("permutation: " + java.util.Arrays.toString(arr));
12 | }
13 | else{
14 | for(int i = 0; i < len; i++){
15 | permute(arr, len-1);
16 | if(i%2==1){
17 | //if odd indexing
18 | swap(arr, 0, len-1);
19 | } else {
20 | //even indexing
21 | swap(arr, i, len-1);
22 | }
23 | }
24 | }
25 |
26 | }
27 |
28 | public static void swap(int[] arr, int a, int b){
29 | int temp = arr[a];
30 | arr[a] = arr[b];
31 | arr[b] = temp;
32 | }
33 |
34 | public static void main(String[] args){
35 | int[] arr = new int[]{1, 2, 3};
36 | permute(arr);
37 |
38 | }
39 | }
--------------------------------------------------------------------------------
/99-answerKey/leetcode/64|MinPathSum/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | class Solution{
3 |
4 |
5 |
6 | public int minPathSum(int[][] grid) {
7 | //DFS
8 | //coordinates
9 | Deque pairs = new ArrayDeque<>();
10 | int minSum= Integer.MAX_VALUE;
11 | int rows = grid.length;;
12 | int columns = grid[0].length;
13 | pairs.push(new int[]{0,0});
14 | Deque sums = new ArrayDeque<>();
15 | int currRow = 0;
16 | int currCol = 0;
17 | sums.push(grid[currRow][currCol]);
18 |
19 | while(true){
20 | if(checkvalid(currRow+1, currCol)){
21 |
22 | }
23 | if(checkvalid(currRow, currCol+1))
24 | break;
25 | }
26 |
27 |
28 | return 0;
29 | }
30 |
31 |
32 | public static void main(String[] args){
33 | Solution caller = new Solution();
34 | caller.minPathSum(new int[][]{{1,2,3}, {1,2,3}});
35 | }
36 | }
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch3-Stacks_n_Queues/6-DogCatShelter/Solution.java:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | class Solution {
5 |
6 | public static void main(String[] args) {
7 | //dequeueAny, dequeueDog, dequeueCat, enqueue
8 | Shelter shelter = new Shelter();
9 | shelter.enqueue(new Cat("Cat-A"));
10 | shelter.enqueue(new Dog("Dog-A"));
11 | shelter.enqueue(new Cat("Cat-B"));
12 | shelter.enqueue(new Cat("Cat-C"));
13 | shelter.enqueue(new Cat("Cat-D"));
14 | shelter.enqueue(new Cat("Cat-E"));
15 |
16 |
17 | shelter.enqueue(new Dog("Dog-B"));
18 | shelter.enqueue(new Dog("Dog-C"));
19 | shelter.enqueue(new Dog("Dog-D"));
20 | shelter.enqueue(new Dog("Dog-E"));
21 |
22 | System.out.println(shelter.dequeueAny().name);
23 | System.out.println(shelter.dequeueAny().name);
24 | System.out.println(shelter.dequeueDog().name);
25 |
26 |
27 | }
28 | }
--------------------------------------------------------------------------------
/99-answerKey/project-Euler/9-min-Multiple-20/minMultiple20.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | public class minMultiple20 {
3 |
4 | //smallest number that's divisible by 1-20.
5 | public static void minDiv1to20()
6 | {
7 | int num = 100;
8 | while(true)
9 | {
10 | if(isitdiv(num))
11 | {
12 | System.out.println("this is the smallest number evenly" +
13 | "\ndivisible by 1-20: " + num);
14 | return;
15 | }
16 | if(num == 2147483646)
17 | {
18 | break; //catch overflow
19 | }
20 | num = num + 2;
21 | }
22 | System.out.println("no valid number: overflow!");
23 | }
24 |
25 | public static boolean isitdiv(int holder) {
26 | for(int i = 3; i <= 20; i++){
27 | if(holder%i != 0){
28 | return false;
29 | }
30 | }
31 | return true;
32 | }
33 |
34 | public static void main(String args[])
35 | {
36 | minDiv1to20();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/1|Two-Sum/Solutions.java:
--------------------------------------------------------------------------------
1 | // 1. Two Sum
2 | public class Solution {
3 | public int[] twoSum(int[] nums, int target) {
4 | // Arrays.sort(nums);
5 | if(nums == null || nums.length == 0) {return null;}
6 |
7 | int i, len = nums.length;
8 |
9 | Map map = new HashMap<>(len);
10 | for(i = 0; i < len; i++)
11 | { //K = i
12 | //i will always be diff => key //nums[i] won't always be diff => value
13 | map.put(nums[i], i);
14 | }
15 | for(i = 0; i < len; i++)
16 | {
17 | int remainder = target - nums[i];
18 | if( map.containsKey(remainder) )
19 | {
20 | if( map.get(remainder) != null ){
21 | if(map.get(remainder) != i ){
22 | return new int[]{i, map.get(remainder)};
23 | }
24 | }
25 | }
26 | }
27 | //DNE
28 | return null;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/99-answerKey/companies/twit/IP/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 |
3 | public static void playKraken(){
4 |
5 | // int n = 6;
6 | // int stopping = n-1;
7 | // while(true){
8 | // int endIt = n-stopping;
9 | // if(stopping==-1){break;}
10 | // for(int i =0; i < endIt; i++){
11 | // System.out.print("#");
12 | // }
13 | // stopping--;
14 | // System.out.println();
15 | // }
16 | // int n = 6;
17 | // int blanks = n-1; ;
18 | // int sharp = n-blanks;;
19 | // while(n > -1){
20 | // if(blanks == -1){break;}
21 | // for(int i = 0; i < blanks; i++){
22 | // System.out.print(" ");
23 | // }
24 | // for(int i = 0; i < sharp; i++){
25 | // System.out.print("#");
26 | // }
27 | // System.out.println();
28 | // blanks--;
29 | // sharp++;
30 | // }
31 |
32 | }
33 |
34 |
35 | public static void main(String[] args){
36 |
37 | playKraken();
38 | }
39 | }
--------------------------------------------------------------------------------
/7-Databases/README.md:
--------------------------------------------------------------------------------
1 | #Databases
2 | * SQL Queries
3 | * Indexing
4 | * Normalization
5 | * ACID
6 | * SQL Injection & Prevention (security)
7 | * Inner and Outer Join
8 |
9 |
10 |
11 |
12 |
13 | | 7. Databases |
14 | Explain |
15 |
16 |
17 | | SQL Queries |
18 | X |
19 |
20 |
21 |
22 | | Indexing |
23 | X |
24 |
25 |
26 |
27 | | Normalization |
28 | X |
29 |
30 |
31 |
32 | | ACID (Atomicity, Consistency, Isolation, Durability) |
33 | X |
34 |
35 |
36 |
37 | | SQL Injection & Prevention |
38 | X |
39 |
40 |
41 |
42 | | Inner & Outer Join |
43 | X |
44 |
45 |
46 |
47 | | Distribute Systems |
48 | X |
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/99-answerKey/companies/airbnb/meals/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | class Solution{
3 |
4 |
5 | static public void printMenu(String[] menu, double[] prices, double cash){
6 |
7 | }
8 |
9 |
10 | static public void simplePrint(List cart, double cash) {
11 | // Deque<>
12 | }
13 |
14 |
15 | public static void main(String[] args){
16 | String[] menu = new String[]{"apple", "berry", "pie", "water"};
17 | double[] prices = new double[]{1.20, 1.30, 10.30, 2.30};
18 | double salary = 30.00;
19 | List shopping = new ArrayList<>();
20 | for(int i = 0; i < menu.length; i++)
21 | shopping.add(new Node(prices[i], menu[i]));
22 | simplePrint(shopping, salary);
23 | }
24 | // printMenu(menu, prices, salary);
25 |
26 | }
27 |
28 |
29 | class Node {
30 | double price;
31 | String item;
32 | public Node(double price, String item){
33 | this.price = price;
34 | this.item=item;
35 | }
36 | }
--------------------------------------------------------------------------------
/99-answerKey/project-Euler/1-Largest-Prime-Factor/largestPrimeFactor.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class largestPrimeFactor {
4 |
5 |
6 | public static void main (String args[]){
7 | long i = 2;
8 | long hi = 600851475143L;
9 | long largest_prime_factor = 0;
10 |
11 | while(i < hi){
12 | if(hi % i == 0)
13 | {
14 | if(isdivprime(i)){
15 | largest_prime_factor = i;
16 | System.out.println(largest_prime_factor);
17 | }
18 | }
19 | i++;
20 | }
21 | System.out.println("this is the largest "
22 | + "prime factor of the number " + largest_prime_factor);
23 | }
24 |
25 | private static boolean isdivprime(long i) {
26 | if(i == 2){
27 | return true;
28 | }
29 | long tracer = 2;
30 | // boolean isprime = true;
31 | for(long ending = 2; ending < i; ending++){
32 | if(i%ending == 0){
33 | return false;
34 | }
35 | }
36 | return true;
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/99-answerKey/algorithms/recursion-dynamic/fibonacci/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | public class Solution {
3 |
4 | public static int dynamicFibonacci(int n) {
5 | int[] fibarr = new int[n];
6 | if (n == 1 || n == 2) {
7 | return 1;
8 | }
9 | fibarr[0] = 1;
10 | fibarr[1] = 1;
11 | for (int i = 2; i < fibarr.length; i++) {
12 | fibarr[i] = fibarr[i - 2] + fibarr[i - 1];
13 | }
14 | return fibarr[n - 1];
15 | }
16 |
17 | public static int recusiveFibonacci(int n)
18 | {
19 | if (n <= 1) {
20 | return n;
21 | } else {
22 | return recusiveFibonacci(n - 1) + recusiveFibonacci(n - 2);
23 | }
24 | }
25 | public static void main(String[] args)
26 | {
27 | Scanner input = new Scanner(System.in);
28 | int r;
29 | System.out.println("What fibonacci number do you want to know?");
30 | r = input.nextInt();
31 | System.out.println("the fibonacci number is " + dynamicFibonacci(r));
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/99-answerKey/unicorns/dynamic/numofwaysCoins/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution{
2 |
3 |
4 | public static int numberWays(int[] coins, int n){
5 | //row=coins | col=value
6 | int len = coins.length+1;
7 | int[][] table = new int[len][n+1];
8 | for(int i= 0; i < len; i++){
9 | table[i][0] = 1;
10 | }
11 |
12 | for(int coin = 1; coin <= coins.length; coin++){
13 | for(int curr = 1; curr <= n; curr++) {
14 | int currCoin = coins[coin-1];
15 | System.out.println(currCoin);
16 | if(currCoin>curr){
17 | table[coin][curr] = table[coin-1][curr];
18 | } else{
19 | table[coin][curr] = table[coin][curr- currCoin] + table[coin-1][curr];
20 | }
21 | }
22 | }
23 |
24 | System.out.println(java.util.Arrays.deepToString(table));
25 | return table[coins.length][n];
26 | }
27 |
28 | public static void main(String[] args){
29 | int want = 10;
30 | System.out.println(numberWays(new int[]{1, 2, 3}, 5));
31 | }
32 | }
--------------------------------------------------------------------------------
/12-EPI/ch6-arrays/buySellStocks/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class Solution {
4 |
5 |
6 | public static Double maxProfit(List stocks) {
7 | if(stocks.size() < 2) {
8 | return 0.00;
9 | }
10 | Double lowestBuy = Math.min(stocks.get(0), stocks.get(1));
11 | Double maxProfit = stocks.get(1) - stocks.get(0); //placeholder!
12 | for(int i = 2; i < stocks.size(); i++) {
13 | Double sellingPrice = stocks.get(i);
14 | maxProfit = Math.max(maxProfit, sellingPrice - lowestBuy);
15 | // is our new price a better buy?
16 | // if so, this will maximize our profit
17 | lowestBuy = Math.min(lowestBuy, sellingPrice);
18 | }
19 | return maxProfit;
20 | }
21 |
22 | public static void main(String[] args) {
23 | List stocks = Arrays.asList(310.00, 315.00, 275.00, 295.00, 260.00, 270.00, 290.00, 230.00, 255.00, 250.00);
24 | System.out.println(maxProfit(stocks));
25 | }
26 | }
--------------------------------------------------------------------------------
/99-answerKey/companies/gusto/Holes.java:
--------------------------------------------------------------------------------
1 | class Holes {
2 |
3 | public static int a_next_server_number(int[] arr){
4 | java.util.Arrays.sort(arr);
5 | int i = 1;
6 | for(int num : arr){
7 | if(num == i){
8 | i++;
9 | } else{
10 | return i;
11 | }
12 | }
13 | System.out.println(i);
14 | return i;
15 | }
16 |
17 |
18 | public static void main(String[] args){
19 | a_next_server_number(new int[]{5, 3, 1});
20 | a_next_server_number(new int[]{3, 2, 1});
21 | a_next_server_number(new int[]{5, 3, 7});
22 | //==> 3,5,7 if(index 0 )
23 | //1-99 105 => return 100
24 | }
25 | }
26 |
27 | // >> tracker = Tracker.new
28 |
29 | // >> tracker.next_server_number([5, 3, 1])
30 | // 2
31 |
32 | // >> tracker.next_server_number([5, 4, 1, 2])
33 | // 3
34 |
35 | // >> tracker.next_server_number([3, 2, 1])
36 | // 4
37 |
38 | // >> tracker.next_server_number([2, 3])
39 | // 1
40 |
41 | // >> tracker.next_server_number([])
42 | // 1
--------------------------------------------------------------------------------
/99-answerKey/leetcode/219-Contains-Duplicate-II/Solution.java:
--------------------------------------------------------------------------------
1 | // 219. Contains Duplicate II
2 | public class Solution {
3 | public boolean containsNearbyDuplicate(int[] nums, int k) {
4 | int len = nums.length, i;
5 | Integer curr = 0;
6 | Map map = new HashMap<>();
7 | for(i = 0; i < len; i++)
8 | {
9 | curr = nums[i];
10 | if(map.containsKey(curr))
11 | {
12 | Integer diff = i - map.get(curr);
13 | if(diff <= k)
14 | {
15 | return true;
16 | }
17 | //else make this the new entry since
18 | //this will be closer than the previous
19 | else
20 | {
21 | map.put(curr, i);
22 | }
23 | }
24 | else
25 | {
26 | map.put(curr,i);
27 | }
28 | }
29 | return false;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Stack/README.md:
--------------------------------------------------------------------------------
1 |
2 | #Stack API:
3 |
4 | Most seem to define a stack as a Singly Linked List when making one implement it. Normally, it is written by extending to a Vector :
5 | [Java SDK](http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/c228a234a3f3/src/share/classes/java/util/Stack.java)
6 |
7 | [Sedgewick](http://algs4.cs.princeton.edu/13stacks/Stack.java.html)
8 |
9 |
10 | ###Stack API defined by CTCI & Sedgewick:
11 | Stack()
12 | void push(Item item)
13 | Iterator pop()
14 | boolean isEmpty()
15 | int size() [Sedgewick]
16 | String toString() [Sedgewick]
17 | Iterator- iterator [Sedgewick]
18 |
19 |
20 |
21 | ###Stack in Java JDK
22 | public class Stack extends Vector
23 | public E push(E item)
24 | public E pop()
25 | public E peek()
26 | public boolean empty()
27 | public int search(Object o) => Uses lastindexof from Vector
28 |
29 |
30 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch3-Stacks_n_Queues/Notes.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | import java.util.*;
4 |
5 | class Notes {
6 |
7 |
8 |
9 | public static void main(String[] args) {
10 | Deque stack = new ArrayDeque<>();
11 | //push => make this the new head!
12 | //push (think of forcing in rather than adding in behind)
13 | stack.push(10);
14 | stack.push(20);
15 | stack.push(30);
16 | System.out.println("PEEK RETURNS HEAD (AKA 30) == " + stack.peek());
17 | System.out.println("POP RETURNS HEAD (AKA 30) == " + stack.pop());
18 | System.out.println("IS EMPTY == " + stack.isEmpty());
19 |
20 | Deque queue = new ArrayDeque<>();
21 | queue.add(10);
22 | queue.add(20);
23 | queue.add(30);
24 | System.out.println("PEEK RETURNS HEAD (AKA 10) == " + queue.peek());
25 | System.out.println("POLL RETURNS HEAD (AKA 10) == " + queue.poll()); //same as pop()
26 | System.out.println("IS EMPTY == " + queue.isEmpty());
27 |
28 | }
29 | }
--------------------------------------------------------------------------------
/99-answerKey/genericFrequent/LongestCommonPrefix/LCPrefix.java:
--------------------------------------------------------------------------------
1 | public class LCPrefix{
2 |
3 | public static String prefix(String[] arr)
4 | {
5 |
6 | if(arr.length == 0 || arr == null) {return "";}
7 | int i, len = arr.length;
8 | String prefix = arr[0];
9 | for(i = 1; i < len; i++)
10 | {
11 | String candidate = arr[i];
12 | //indexOf = + means not prefix but inside the word
13 | //indexOf = - means the prefix might be too long, hence update it and make shorter
14 | //indexOf = 0 means prefix
15 | while(candidate.indexOf(prefix) != 0)
16 | {
17 | prefix = prefix.substring(0, prefix.length() - 1);
18 | if(prefix.equals("")) {return "";}
19 | }
20 | }
21 | return prefix;
22 | }
23 |
24 | public static void main(String[] args)
25 | {
26 | String[] arr = new String[]{"leest", "lees", "leestcode", "leesters", "leesps", "leesp"};
27 | System.out.println(prefix(arr));
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/99-answerKey/hackerrank/cavity-map/Solution.java:
--------------------------------------------------------------------------------
1 |
2 | class Solution {
3 |
4 | public static void main(String[] args) {
5 | //cavity = not on the border of the map
6 | //and each cell adjacent to it is smaller depth
7 | String[] grid = new String[]{"1112", "1912", "1892", "1234"};
8 | int len = grid.length;
9 |
10 | //start at 1 since no edges
11 | //end at up && candidate > down && candidate > left && candidate > right) {
20 | grid[row] = grid[row].substring(0, num) + 'X' + grid[row].substring(num+1);
21 | }
22 | }
23 | }
24 |
25 | for(int k = 0; k < len; k++){
26 | System.out.println(grid[k]);
27 | }
28 | }
29 |
30 | }
--------------------------------------------------------------------------------
/99-answerKey/general/dec/randomNumbersBlacklisting.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | class randomNumbersBlacklisitng {
3 |
4 | static public void evenlyDistrib(int[] blacklisting, int n) {
5 | //let's treat index => actual number rather than -1 offset
6 | int[] distribution = new int[n+1];
7 | boolean[] noTouch = new boolean[n+1]; //all init to False
8 | for(int banned : blacklisting) {
9 | noTouch[banned] = true;
10 | }
11 | Random generateRandom = new Random();
12 |
13 | for(int i = 0; i < 100; i++) {
14 | int dummy = (generateRandom.nextInt(n) + 1);
15 | // System.out.print(dummy + " ");
16 | if(!noTouch[dummy]) {
17 | distribution[dummy] += 1;
18 | }
19 | }
20 | // System.out.println(Arrays.toString(distribution));
21 | for(int j = 0; j < distribution.length; j++ ){
22 | System.out.println("["+j+"]= "+ distribution[j]);
23 | }
24 | }
25 |
26 | public static void main(String[] args) {
27 | evenlyDistrib(new int[]{1, 2, 7}, 10);
28 |
29 | }
30 | }
--------------------------------------------------------------------------------
/12-EPI/ch4/permutable.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class permutable {
4 |
5 | static public boolean permutableNumb(int numb) {
6 | char[] arr = (numb + "").toCharArray();
7 | Map map = new HashMap<>();
8 | for(char indieNumb: arr) {
9 | if(map.containsKey(indieNumb)) {
10 | map.put( indieNumb, map.get(indieNumb)+1);
11 | } else {
12 | map.put(indieNumb, 1);
13 | }
14 | }
15 | int odds = 0;
16 | for (Map.Entry entry : map.entrySet()) {
17 | if (entry.getValue()%2 != 0) {
18 | odds++;
19 | if(odds == 2) {
20 | return false;
21 | }
22 | }
23 | }
24 | return true;
25 |
26 | }
27 |
28 | public static void main(String[] args) {
29 | int numb = 1321352;
30 | System.out.println(numb+ " is permutable => " + permutableNumb(numb));
31 | numb = 111222;
32 | System.out.println(numb+ " is permutable => " + permutableNumb(numb));
33 | }
34 | }
--------------------------------------------------------------------------------
/6-OS/README.md:
--------------------------------------------------------------------------------
1 | # OS
2 | * Process & Threads
3 | * Memory organization
4 | * Booting Process
5 | * Deadlock
6 | * Starvation
7 | * IPC
8 | * Inode
9 | * Extras: Daemon, etc.
10 |
11 |
12 |
13 |
14 |
15 | | 6. OS |
16 | Explain |
17 |
18 |
19 |
20 | | Process & Threads |
21 | X |
22 |
23 |
24 |
25 | | Memory Organization (Stack & Heap) |
26 | X |
27 |
28 |
29 |
30 | | Booting Process |
31 | X |
32 |
33 |
34 |
35 | | Starvation |
36 | X |
37 |
38 |
39 |
40 | | IPC |
41 | X |
42 |
43 |
44 |
45 | | Inode |
46 | X |
47 |
48 |
49 |
50 | | daemon |
51 |
52 | Program running as a background process rather than direct control of an interactive user.
53 | |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/99-answerKey/general/dec-week2/compression.java:
--------------------------------------------------------------------------------
1 | class compression {
2 |
3 | public static void compressMe(String nums){
4 | int len = nums.length();
5 | if(len == 0) {
6 | System.out.println("");
7 | return;
8 | }
9 | char[] container = nums.toCharArray();
10 | String compressed = "";
11 | char prev = container[0];
12 | int counter = 1;
13 | for(int i = 1; i < len; i++) {
14 | if (container[i] == prev) {
15 | counter++;
16 | } else {
17 | compressed = compressed + counter + prev;
18 | counter = 1;
19 | prev = container[i];
20 | }
21 | }
22 |
23 | if(container[len-1] == prev) {
24 | compressed = compressed + counter + prev;
25 | System.out.println(compressed);
26 | }
27 | else {
28 | compressed = compressed + "1" + prev;
29 | System.out.println(compressed);
30 | }
31 | }
32 |
33 |
34 | public static void main(String[] args) {
35 | compressMe("111223333");
36 | }
37 | }
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch2-Linked_list/2-kth_last/UseRunner.java:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | class UseRunner {
5 |
6 |
7 | /*
8 | It's going to end kth before the list ends!!!
9 | */
10 | public static Node getKthNode(Node head, int kthToLast) {
11 | Node ptr = head;
12 | Node ptr2 = head;
13 | for(int i = 0; i < kthToLast; i++) {
14 | if(ptr == null) return null;
15 | ptr = ptr.next;
16 | }
17 | while(ptr != null) {
18 | ptr = ptr.next;
19 | ptr2 = ptr2.next;
20 | }
21 |
22 | return ptr2;
23 | }
24 |
25 |
26 | public static void main(String[] args) {
27 | Node head = new Node(0);
28 | Node ptr = head;
29 | for(int i : new int[]{1, 2, 3, 4, 5, 6, 7}) {
30 | ptr.next = new Node(i);
31 | ptr = ptr.next;
32 | }
33 | ptr = head;
34 |
35 | System.out.println(getKthNode(ptr, 2).data);
36 | }
37 | }
38 |
39 |
40 |
41 | class Node {
42 | int data;
43 | Node next;
44 | public Node(int data) {
45 | this.data = data;
46 | }
47 | }
--------------------------------------------------------------------------------
/99-answerKey/leetcode/6|ZigZag-Conversion/Solution.java:
--------------------------------------------------------------------------------
1 | //17.66 percentile
2 | class Solution {
3 |
4 | public static String convert(String s, int numRows){
5 | if(s == null){return "";}
6 | if(numRows == 1){return s;}
7 | //need to init arr with empties could do Arrays.fill(row, "");
8 | String[] row = new String[numRows];
9 | for(int i = 0; i < numRows; i++){
10 | row[i]="";
11 | }
12 | int currIndex = 0;
13 | int len = s.length();
14 | boolean direction = true; //true=> + & false -
15 |
16 | for(int i = 0; i < len; i++){
17 | row[currIndex] = row[currIndex] +""+s.charAt(i) ;
18 | if(currIndex==0){direction = true;}
19 | if(currIndex+1==numRows){direction=false;}
20 | currIndex = (direction) ? currIndex+1:currIndex-1;
21 | }
22 | String zigzag = "";
23 | for(String horiz : row){
24 | zigzag += horiz;
25 | }
26 | return zigzag;
27 | }
28 |
29 | public static void main(String[] args){
30 | System.out.println(convert("PAYPALISHIRING", 3));
31 | }
32 | }
--------------------------------------------------------------------------------
/99-answerKey/algorithms/search/binary-search/BinarySearch.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by christian on 5/16/16.
3 | */
4 | public class BinarySearch {
5 |
6 |
7 |
8 | public static int binarySearch(int[] numbers, int want)
9 | {
10 | int low = 0;
11 | int high = numbers.length;
12 | int mid;
13 | while(low < high)
14 | { //the (high-low)/2 is done for avoiding overflow
15 | mid = low + (high-low)/2;
16 | if(numbers[mid] > want)
17 | {
18 | high = mid - 1;
19 | }
20 | else if(numbers[mid] < want)
21 | {
22 | low = mid + 1;
23 | }
24 | else
25 | return mid;
26 |
27 | }
28 |
29 | return -1;
30 | }
31 |
32 | public static void main(String[] args)
33 | {
34 | int[] numbers = new int[]{1, 2, 3, 4, 5, 6, 99, 101, 432, 890};
35 | int index = binarySearch(numbers, 900);
36 | System.out.println(index);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/99-answerKey/companies/gusto/questions.txt:
--------------------------------------------------------------------------------
1 |
2 |
3 | April 21
4 | Implement a Linked List with unique elements
5 | Array of loans, return an array of loans representing loands
6 | cleared from redundant amounts.
7 | Input:
8 | A owes B 100
9 | B owes A 100
10 | Output: []
11 |
12 | Input:
13 | A owes B 100
14 | B owes C 100
15 | C owes A 100
16 | Output: []
17 |
18 | Implement a simple ft in app. Add two new columns to the table in react
19 | view and update backend method to feed data for the columns.
20 |
21 | Dec 25
22 | DS (arrays, trees)
23 |
24 | Dec 22
25 | Split-wise function
26 |
27 | Oct 11
28 | Implement reduce() [ruby feature]
29 | implement a way to divide deposits across accounts
30 |
31 | Feb 13
32 | Implement a simple payroll function
33 |
34 | Sep 3
35 | DFS with a twist?
36 |
37 | Jun 18
38 | Implement a js method for deep diff b/w 2 objects
39 |
40 | Dec 18
41 | BFS & BST
42 |
43 |
44 | Oct 27
45 | Bit manipulation:Unsigned value, given an unsigned value
46 | implement two's complement.
47 | Float an element in CSS
48 |
49 |
--------------------------------------------------------------------------------
/99-answerKey/genericFrequent/Binary-Search/BinarySearch.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | /**
4 | * Created by christian on 5/16/16.
5 | */
6 | public class BinarySearch {
7 |
8 |
9 |
10 | public static int binarySearch(int[] numbers, int want)
11 | {
12 | int low = 0;
13 | int high = numbers.length;
14 | int mid;
15 | while(low < high)
16 | { //the (high-low)/2 is done for avoiding overflow
17 | mid = low + (high-low)/2;
18 | if(numbers[mid] > want)
19 | {
20 | high = mid - 1;
21 | }
22 | else if(numbers[mid] < want)
23 | {
24 | low = mid + 1;
25 | }
26 | else
27 | return mid;
28 |
29 | }
30 |
31 | return -1;
32 | }
33 |
34 | public static void main(String[] args)
35 | {
36 | int[] numbers = new int[]{1, 2, 3, 4, 5, 6, 99, 101, 432, 890};
37 | int index = binarySearch(numbers, 900);
38 | System.out.println(index);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/36|Valid-Sudoku/README.md:
--------------------------------------------------------------------------------
1 | #Valid Sudoku WORKS
2 | ####Level: Easy || Inc: Snap, Uber, Apl
3 |
4 | Test Cases
5 |
6 |
7 | //{"......5..",".........",".........","93..2.4..","..7...3..",".........","...34....",".....3...",".....52.."} return false
8 |
9 | //["...9.....",".........","..3.....1",".........","1.....3..","....2.6..",".9.....7.",".........","8..8....."] return false;
10 |
11 | //{"..4...63.",".........","5......9.","...56....","4.3.....1","...7.....","...5.....",".........","........."}; return false;
12 |
13 | // {".87654321","2........","3........","4........","5........","6........","7........","8........","9........"}; return true
14 |
15 | // {"....5..1.",".4.3.....",".....3..1","8......2.","..2.7....",".15......",".....2...",".2.9.....","..4......"};
16 |
17 | //{".87654321","2........","3........","4........","5........","6........","7........","8........","9........"}; return true
18 |
19 | //{"..4...63.",".........","5......9.","...56....","4.3.....1","...7.....","...5.....",".........","........."} return false;
20 |
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Queue/QueueTest.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 | public class QueueTest
8 | {
9 |
10 | public static void putTo(String words, Queue myQueue)
11 | {
12 | String[] letter = words.split("");
13 | for(String s : letter)
14 | myQueue.add(s);
15 | }
16 |
17 |
18 | @Test
19 | public void test() {
20 | Queue queue = new Queue<>();
21 | String aBet = "abcdefghijklmnopqrstuvwxyz";
22 | putTo(aBet, queue);
23 | testSize(queue);
24 | testPeek(queue, "a");
25 | testPoll(queue, "a");
26 | testPeek(queue, "b");
27 | }
28 |
29 | //make assertion in void
30 | void testSize(Queue queue)
31 | {
32 | assertEquals(26, queue.size());
33 | }
34 |
35 |
36 | void testPeek(Queue queue, String want)
37 | {
38 | assertEquals(want, queue.peek());
39 | }
40 |
41 |
42 | void testPoll(Queue queue, String expect)
43 | {
44 | assertEquals(expect, queue.poll());
45 | }
46 |
47 |
48 |
49 |
50 |
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/2-Data-Structures/trie/Trie.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class Trie{
4 |
5 | TrieNode root;
6 |
7 | public Trie()
8 | {
9 | root = new TrieNode();
10 | }
11 |
12 | public void putword(String key)
13 | {
14 | char[] path = key.toCharArray();
15 | int i, len = path.length;
16 | TrieNode currNode = root;
17 | for(i = 0; i < len; i++)
18 | {
19 | currNode = currNode.addChild(path[i]);
20 | }
21 | //done
22 | }
23 |
24 | public void putarr(String[] arr)
25 | {
26 | for(String word: arr)
27 | putword(word);
28 | }
29 | public boolean containsPrefix(String word)
30 | {
31 | TrieNode currNode = root;
32 | int i, len = word.length();
33 | for(i = 0; i < len; i++)
34 | {
35 | char currLetter = word.charAt(i);
36 |
37 | if( !currNode.children.containsKey(currLetter) )
38 | {
39 | return false; //letter DNE
40 | }
41 | currNode = currNode.children.get(currLetter);
42 | }
43 | return true;
44 | }
45 |
46 |
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/99-answerKey/companies/snap/gamelife/failed.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | class failed {
3 |
4 | public static void banner(int row, int col, int rows, int cols, List list){
5 | // int leftup = (row-1 && col-1);
6 | if(row-1 >= 0 && col-1 >= 0){
7 | list.add(new int[]{row-1, col-1} );
8 | }
9 | // int up = (row-1 => 0):
10 | if(row-1 >= 0){
11 | list.add(new int[]{row-1, col});
12 | }
13 | // int rightup = (row-1 + col+1);
14 | if(row+1 < rows && col+1 < cols){
15 | list.add(new int[]{row+1, col+1});
16 | }
17 | // int left = (col-1);
18 | if(col-1 >= 0){
19 | list.add(new int[]{row, col-1});
20 | }
21 | // int right = (col+1);
22 | if(col+1 < cols){
23 | list.add(new int[]{row, col+1});
24 | }
25 | // int leftDown = (row+1 + col-1);
26 | if(row+1 < rows && col-1 >= 0){
27 | list.add(new int[]{row+1, col-1});
28 | }
29 | // int rightDown = (row+1 + col+1)
30 | if(row+1 < rows && col+1 < cols){
31 | list.add(new int[]{row+1, col+1});
32 | }
33 |
34 | }
35 |
36 | public static void main(String[] args){
37 |
38 | }
39 | }
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Graphs/Graph/Graph.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayDeque;
2 | import java.util.ArrayList;
3 | import java.util.Deque;
4 | import java.util.HashSet;
5 | import java.util.List;
6 | import java.util.Set;
7 |
8 | public class Graph{
9 |
10 |
11 |
12 | private List[] sources;
13 | //Edge = sourceVertex----edgeWeight------->targetVertex
14 |
15 | @SuppressWarnings("unchecked")
16 | public Graph(int size)
17 | {
18 | sources = (ArrayList[])new ArrayList[size];
19 | initarr(sources, size);
20 | }
21 |
22 |
23 | public void initarr(List[] sources, int size)
24 | {
25 | for(int i = 0; i < size; i++)
26 | {
27 | sources[i] = new ArrayList();
28 | }
29 | }
30 |
31 | public List getOtherSources(int target)
32 | {
33 | return sources[target];
34 | }
35 |
36 |
37 |
38 |
39 | public Edge setDirectedEdge(int vSource, int vTarget,
40 | double eWeight)
41 | {
42 | List sources = getOtherSources(vTarget);
43 | Edge edge = new Edge(vSource, vTarget, eWeight);
44 | sources.add(edge)
45 | }
46 |
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/12-EPI/ch6-arrays/jumpToTheEnd/Solution.java:
--------------------------------------------------------------------------------
1 | /*
2 | You can jump arr[i] steps, see if you can reach the end of the board
3 | */
4 | import java.util.*;
5 |
6 | class Solution {
7 |
8 |
9 | public static boolean canReachEnd(List list) {
10 | //we just care about reaching the end!
11 | int end = list.size() - 1; //last index
12 | int reachableRange = 0;
13 |
14 | //keep going as long as this index is reachable & we haven't landed
15 | //to the end
16 | for(int i = 0; i <= reachableRange && reachableRange < end; i++) {
17 | //index + jumpingMax
18 | reachableRange = Math.max(i+list.get(i), reachableRange);
19 | }
20 | return (reachableRange >= end) ? true : false;
21 | }
22 |
23 |
24 | public static void main(String[] args) {
25 | System.out.println(canReachEnd(Arrays.asList(0, 1, 2, 3)));
26 |
27 | System.out.println(canReachEnd(Arrays.asList(1, 0, 2, 3)));
28 |
29 | System.out.println(canReachEnd(Arrays.asList(1, 1, 2, 3)));
30 |
31 | System.out.println(canReachEnd(Arrays.asList(3, 3, 1, 0, 2, 0, 1)));
32 | }
33 |
34 | }
--------------------------------------------------------------------------------
/99-answerKey/companies/yelp/1-stringcompression/stringcompression.java:
--------------------------------------------------------------------------------
1 | class stringcompression{
2 |
3 |
4 | public static String compression(String candidate)
5 | {
6 | candidate = candidate + " "; //last letter
7 | int length = candidate.length();
8 | char[] seperated = candidate.toCharArray();
9 | String possibleAlt = "";
10 | int count = 1;
11 | for(int i = 1; i < length; i++)
12 | {
13 | if(seperated[i] != seperated[i-1])
14 | {
15 | possibleAlt = possibleAlt + seperated[i-1] + "" + count;
16 | count = 1; //reset count
17 | }
18 | else
19 | count++;
20 | }
21 | int newLength = possibleAlt.length();
22 | if(length <= newLength)
23 | {
24 | return candidate;
25 | }
26 | return possibleAlt;
27 | }
28 |
29 |
30 | public static void main(String[] a)
31 | {
32 | String longated = "aabcccccaaa";
33 | System.out.println(compressIt(longated));
34 | System.out.println(compression(longated));
35 | longated = "aaccaa";
36 | System.out.println(compressIt(longated));
37 | System.out.println(compression(longated));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/283-Move-Zeroes/README.md:
--------------------------------------------------------------------------------
1 | #Passed 28 seconds
2 | ###Only beats ~8% of other Java solutions
3 |
4 |
5 |
6 |
7 | In-place and Minimize operations!
8 |
9 |
10 |
11 |
12 | | Data Structure/Other |
13 | Method |
14 | Space Complexity [If applicable] |
15 | Explain |
16 |
17 |
18 |
19 |
20 |
21 | | Insertion Sort |
22 | The logic followed is from Insertion-Sort with two add-ons.
23 | 1. I do a check if the current index contains a 0.
24 | 2. I am not sorting it, I am just moving all the zeroes to the right, while
25 | maintaining the original order. |
26 | WC: O(n2), via Gauss partial sum
27 | BC: O(n), it's already sorted, but you still have to iterate through the whole thing |
28 | Insertion sort with 2 add-ons of my own. |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
42 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch3-Stacks_n_Queues/5-SortedStack/ActualSolution.java:
--------------------------------------------------------------------------------
1 | /*
2 | NOT A STACK THAT MAINTAINS SORTING
3 | RATHER, WE WANT TO SORT A PRE-FILLED STACK
4 | */
5 |
6 |
7 | import java.util.*;
8 | class ActualSolution {
9 |
10 | public static void sort(Deque stack) {
11 | //maintains descending ordering
12 | Deque aux = new ArrayDeque<>();
13 | while(!stack.isEmpty()){
14 | int candidate = stack.pop();
15 | //want to introduce candidate below all higher elements
16 | while(!aux.isEmpty() && aux.peek() > candidate) {
17 | stack.push(aux.pop());
18 | }
19 | //insert ourselves here
20 | aux.push(candidate);
21 | }
22 | while(!aux.isEmpty()) {
23 | stack.push(aux.pop());
24 | }
25 | }
26 |
27 | public static void main(String[] args) {
28 | Deque stack = new ArrayDeque<>();
29 | stack.push(10);
30 | stack.push(1);
31 | stack.push(3);
32 | stack.push(300);
33 | stack.push(13);
34 | System.out.println(stack);
35 | sort(stack);
36 | System.out.println(stack);
37 | }
38 | }
39 |
40 |
--------------------------------------------------------------------------------
/1-Sorting-Algorithms/Bubble_Sort/Solution.java:
--------------------------------------------------------------------------------
1 |
2 | import java.util.Arrays;
3 |
4 | class Bubble {
5 | public static void sort(int[] array){
6 | boolean trip_wire = false;
7 | int unsorted_len = array.length - 1;
8 | while(!trip_wire){
9 | trip_wire = true;
10 | for(int i = 0; i < unsorted_len; i++){
11 | //if we go through the entire array without having prev > next
12 | //we can imply it's sorted, since we would just be going over: prev < next < next.next
13 | if(array[i] > array[i+1]){
14 | swap(array, i, i+1);
15 | trip_wire = false;
16 | }
17 | }
18 | unsorted_len--;
19 | }
20 | }
21 | public static void swap(int[] array, int i, int j){
22 | int temp = array[i];
23 | array[i] = array[j];
24 | array[j] = temp;
25 | }
26 | }
27 |
28 |
29 | class Solution {
30 |
31 | public static void main(String[] args) {
32 | int[] array = {2, 3, 5, 1, 10};
33 | System.out.println("Before: "+Arrays.toString(array));
34 | Bubble.sort(array);
35 | System.out.println("After: "+Arrays.toString(array));
36 | }
37 | }
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch4-Trees&Graphs/1-RouteBetweenNodes/TestPath.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | class TestPath {
3 |
4 |
5 |
6 |
7 | public static void main(String[] args) {
8 | Graph graph = new Graph();
9 | graph.insertEdge("A", "B");
10 | graph.insertEdge("A", "C");
11 | graph.insertEdge("A", "B");
12 | graph.insertEdge("A", "E");
13 | graph.insertEdge("A", "M");
14 | graph.insertEdge("A", "B");
15 | graph.insertEdge("C", "D");
16 | graph.insertEdge("A", "V");
17 | graph.insertEdge("V", "B");
18 | graph.insertEdge("D", "Z");
19 | graph.insertEdge("D", "E");
20 | graph.insertEdge("D", "J");
21 | graph.insertEdge("C", "E");
22 | System.out.println(graph.pathExists("A", "Z")); //yes!
23 | System.out.println(graph.pathExists("C", "J")); //yes
24 | System.out.println(graph.pathExists("Z", "J")); //no
25 | System.out.println(graph.pathExists("A", "K")); //no
26 |
27 | List hellos = new ArrayList<>();
28 | String yop = "hjl";
29 | int index = hellos.indexOf(yop);
30 | if(index >= 0){
31 | hellos.get(index);
32 | }
33 | hellos.size();
34 |
35 | }
36 | }
--------------------------------------------------------------------------------
/99-answerKey/companies/thumbtack/StreamOfInts/Solution.java:
--------------------------------------------------------------------------------
1 | import java.io.BufferedReader;
2 | import java.io.FileInputStream;
3 | import java.io.InputStream;
4 | import java.io.InputStreamReader;
5 | import java.util.List;
6 | import java.util.ArrayList;
7 | import java.util.Random;
8 | import java.util.Arrays;
9 | class Solution {
10 |
11 | public static void meanAndMedian(int[] arr){
12 | //don't know the size!!!! => cannot use arr.length since constant stream
13 |
14 |
15 | }
16 |
17 |
18 | public static void main(String[] args) throws Exception{
19 | List dict = new ArrayList<>();
20 | InputStream in = new FileInputStream("numbers.txt");
21 | BufferedReader reader = new BufferedReader(new InputStreamReader(in));
22 | String word;
23 | while((word = reader.readLine()) != null){
24 | String[] splitIt = word.split(",");
25 | for(String official : splitIt){
26 | dict.add(official);
27 | }
28 | }
29 | // Random generator = new Random();
30 | // for(int i = 0; i < 1000; i++){
31 | // System.out.print(generator.nextInt(1001) +", ");
32 | // if(i!=0&&i%100==0){System.out.println();}
33 | // }
34 | }
35 | }
--------------------------------------------------------------------------------
/2-Data-Structures/LinkedLists/LinkedList/AbstractDoublyLinkedList.java:
--------------------------------------------------------------------------------
1 | package LinkedLists;
2 |
3 | import DoublyLinkedList.Node;
4 |
5 | /*===================================================
6 | These are the methods every Linked Lists should have: Interface
7 | ===================================================*/
8 | public abstract class AbstractDoublyLinkedList{
9 |
10 | /*================================================
11 | SETTERS
12 | ================================================*/
13 | public abstract void putNode(int data);
14 |
15 | public abstract void newHead(int head);
16 |
17 | public abstract void putMultiNodes(int[] nodes);
18 |
19 | public abstract Node removeHead() throws Exception;
20 |
21 | public abstract Node removeTail() throws Exception ;
22 |
23 | public abstract void deleteNode(int data) throws Exception ;
24 |
25 | public abstract void autoLinkedList(int size);
26 |
27 | /*================================================
28 | GETTERS
29 | ================================================*/
30 | public abstract int getSize();
31 |
32 | public abstract Node getHead();
33 |
34 | public abstract void listToString();
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/2-Data-Structures/LinkedLists/LinkedList/AbstractLinkedList.java:
--------------------------------------------------------------------------------
1 | package LinkedLists;
2 |
3 | import SinglyLinkedList.Node;
4 | //this is how it is allowed to used Node
5 |
6 | /*===================================================
7 | These are the methods every Linked Lists should have: Interface
8 | ===================================================*/
9 | public abstract class AbstractLinkedList{
10 |
11 | /*================================================
12 | SETTERS
13 | ================================================*/
14 | public abstract void putNode(int data);
15 |
16 | public abstract void newHead(Node head);
17 |
18 | public abstract void putMultiNodes(int[] nodes);
19 |
20 | public abstract Node removeHead() throws Exception;
21 |
22 | public abstract Node removeTail();
23 |
24 | public abstract Node deleteNode(int data);
25 |
26 | public abstract void autoLinkedList(int size);
27 |
28 | /*================================================
29 | GETTERS
30 | ================================================*/
31 | public abstract int getSize();
32 |
33 | public abstract Node getHead();
34 |
35 | public abstract void listToString();
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/99-answerKey/algorithms/graphSearch/Edge.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | public class Edge{
4 |
5 | private int vertexSource;
6 | private int vertexTarget;
7 | private double edgeWeight;
8 |
9 | public Edge(int vertexSource, int vertexTarget,
10 | double edgeWeight)
11 | {
12 | this.vertexSource = vertexSource;
13 | this.vertexTarget = vertexTarget;
14 | this.edgeWeight = edgeWeight;
15 | }
16 |
17 | /*================================
18 | Setters
19 | ================================**/
20 | public void increaseWeight(double moreWeight)
21 | {
22 | edgeWeight += moreWeight;
23 | }
24 |
25 | public void resetWeight(double edgeWeight)
26 | {
27 | this.edgeWeight = edgeWeight;
28 | }
29 |
30 |
31 | /*================================
32 | Getters
33 | ================================**/
34 | public int getSource()
35 | {
36 | return vertexSource;
37 | }
38 |
39 | public int getTarget()
40 | {
41 | return vertexTarget;
42 | }
43 |
44 | public double getEdgeWeight()
45 | {
46 | return edgeWeight;
47 | }
48 |
49 | public String toString()
50 | {
51 | return getSource() + " -------" + getEdgeWeight() + "----->" + getTarget();
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Graphs/Graph/Edge.java:
--------------------------------------------------------------------------------
1 |
2 | public class Edge{
3 |
4 | private int vertexSource;
5 | private int vertexTarget;
6 | private double edgeWeight;
7 |
8 | public Edge(int vertexSource, int vertexTarget,
9 | double edgeWeight)
10 | {
11 | this.vertexSource = vertexSource;
12 | this.vertexTarget = vertexTarget;
13 | this.edgeWeight = edgeWeight;
14 | }
15 |
16 | /*================================
17 | Setters
18 | ================================**/
19 | public void increaseWeight(double moreWeight)
20 | {
21 | edgeWeight += moreWeight;
22 | }
23 |
24 | public void resetWeight(double edgeWeight)
25 | {
26 | this.edgeWeight = edgeWeight;
27 | }
28 |
29 |
30 | /*================================
31 | Getters
32 | ================================**/
33 | public int getSource()
34 | {
35 | return vertexSource;
36 | }
37 |
38 | public int getTarget()
39 | {
40 | return vertexTarget;
41 | }
42 |
43 | public double getEdgeWeight()
44 | {
45 | return edgeWeight;
46 | }
47 |
48 | public String toString()
49 | {
50 | return getSource() + " -------" + getEdgeWeight() + "----->" + getTarget();
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/49|Group-Anagrams/Solution.java:
--------------------------------------------------------------------------------
1 | // 49. Group Anagrams
2 |
3 | public class Solution {
4 | public List> groupAnagrams(String[] strs)
5 | {
6 | Arrays.sort(strs);
7 |
8 | List> gramMaster = new ArrayList<>();
9 | int length = strs.length;
10 |
11 |
12 | if(length < 2)
13 | {
14 | gramMaster.add(Arrays.asList(strs));
15 | return gramMaster;
16 | }
17 | //keyvalue
18 | Map> abcMap = new HashMap>();
19 | for(int i = 0; i < length; i++)
20 | {
21 | char[] abc = strs[i].toCharArray();
22 | Arrays.sort(abc);
23 | String candidate = new String(abc);
24 | if(abcMap.containsKey(candidate))
25 | {
26 | //get corresp. AL.add()
27 | abcMap.get(candidate).add(strs[i]);
28 |
29 | }//else make new AL and add sorted string as value
30 | else{
31 | ArrayList unseen = new ArrayList<>();
32 | unseen.add(strs[i]);
33 | abcMap.put(candidate, unseen);
34 | }
35 | }
36 | gramMaster.addAll(abcMap.values());
37 | return gramMaster;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch2-Linked_list/3-deleteMiddleNode/Solution.java:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | class Solution {
5 |
6 |
7 | /*
8 | Clone the node after the mid node,
9 | since the mid node is a clone of the upcoming node, we can drop the upcoming node.
10 | */
11 | public static void removeMid(Node mid) {
12 | if(mid == null || mid.next == null) return;
13 |
14 | mid.data = mid.next.data; //copy the data of the upcoming node
15 | mid.next = mid.next.next; //since we cloned the data we can drop the next node
16 |
17 | }
18 |
19 |
20 | public static void main(String[] args) {
21 | Node head = new Node(0);
22 | Node ptr = head;
23 | for(int i: new int[]{1, 2, 3, 4, 5, 6}){
24 | ptr.next = new Node(i);
25 | ptr = ptr.next;
26 | }
27 | ptr = head;
28 | int i = 0;
29 | while(i < 3) {
30 | i++;
31 | ptr = ptr.next;
32 | }
33 | removeMid(ptr);
34 | ptr = head;
35 | while(ptr != null) {
36 | System.out.println(ptr.data);
37 | ptr = ptr.next;
38 | }
39 | }
40 | }
41 |
42 | class Node {
43 | int data;
44 | Node next;
45 |
46 | public Node(int data) {
47 | this.data = data;
48 | }
49 | }
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Linked-List/LinkedList/AbstractDoublyLinkedList.java:
--------------------------------------------------------------------------------
1 | package LinkedLists;
2 |
3 | import DoublyLinkedList.Node;
4 |
5 | /*===================================================
6 | These are the methods every Linked Lists should have: Interface
7 | ===================================================*/
8 | public abstract class AbstractDoublyLinkedList{
9 |
10 | /*================================================
11 | SETTERS
12 | ================================================*/
13 | public abstract void putNode(int data);
14 |
15 | public abstract void newHead(int head);
16 |
17 | public abstract void putMultiNodes(int[] nodes);
18 |
19 | public abstract Node removeHead() throws Exception;
20 |
21 | public abstract Node removeTail() throws Exception ;
22 |
23 | public abstract void deleteNode(int data) throws Exception ;
24 |
25 | public abstract void autoLinkedList(int size);
26 |
27 | /*================================================
28 | GETTERS
29 | ================================================*/
30 | public abstract int getSize();
31 |
32 | public abstract Node getHead();
33 |
34 | public abstract void listToString();
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Linked-List/LinkedList/AbstractLinkedList.java:
--------------------------------------------------------------------------------
1 | package LinkedLists;
2 |
3 | import SinglyLinkedList.Node;
4 | //this is how it is allowed to used Node
5 |
6 | /*===================================================
7 | These are the methods every Linked Lists should have: Interface
8 | ===================================================*/
9 | public abstract class AbstractLinkedList{
10 |
11 | /*================================================
12 | SETTERS
13 | ================================================*/
14 | public abstract void putNode(int data);
15 |
16 | public abstract void newHead(Node head);
17 |
18 | public abstract void putMultiNodes(int[] nodes);
19 |
20 | public abstract Node removeHead() throws Exception;
21 |
22 | public abstract Node removeTail();
23 |
24 | public abstract Node deleteNode(int data);
25 |
26 | public abstract void autoLinkedList(int size);
27 |
28 | /*================================================
29 | GETTERS
30 | ================================================*/
31 | public abstract int getSize();
32 |
33 | public abstract Node getHead();
34 |
35 | public abstract void listToString();
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/392-Is-Subsequence/Solution.java:
--------------------------------------------------------------------------------
1 | /*
2 | Given a string s and a string t, check if s is subsequence of t.
3 |
4 | You may assume that there is only lower case
5 | English letters in both s and t. t is potentially a
6 | very long (length ~= 500,000) string, and s is a short string (<=100).
7 |
8 | A subsequence of a string is a new string
9 | which is formed from the original string by
10 | deleting some (can be none) of the characters
11 | without disturbing the relative positions of the
12 | remaining characters.
13 | (ie, "ace" is a subsequence of "abcde" while "aec" is not).
14 |
15 | Example 1:
16 | s = "abc", t = "ahbgdc"
17 |
18 | Return true.
19 |
20 | Example 2:
21 | s = "axc", t = "ahbgdc"
22 |
23 | Return false.
24 |
25 | Follow up:
26 | If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B,
27 | and you want to check one by one to see if T has its subsequence.
28 | In this scenario, how would you change your code?
29 |
30 | **/
31 | import java.uti.*;
32 | public class Solution {
33 |
34 | public boolean isSubsequence(String s, String t) {
35 |
36 | }
37 |
38 |
39 | public static void main(String[] args) {
40 |
41 | }
42 | }
--------------------------------------------------------------------------------
/99-answerKey/algorithms/graphSearch/README.md:
--------------------------------------------------------------------------------
1 | #Data Structures & Methods Used
2 |
3 |
4 | ###List
5 |
7 |
8 | List(String) list = new ArrayList<>();
9 |
10 | You can preset size if you would like; it still has dynamic growth.
11 |
12 |
13 | add(E object)
14 |
15 | - add an object to the current index
16 | - returns a boolean value
17 |
18 |
19 | get(int index)
20 |
21 | - grab the object at the given index
22 |
23 |
24 | addAll(Collection extends E> collection)
25 |
26 | - List(String) newList = new ArrayList<>();
27 |
newList.addAll(list);
28 |
this adds every element in list into newList as if it were doing
29 |
a for loop for(E element: list) newList[i]=E
30 |
31 | - returns a boolean value
32 |
33 |
34 |
35 |
36 |
37 |
44 |
52 |
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Graphs/Graph/README.md:
--------------------------------------------------------------------------------
1 | #Data Structures & Methods Used
2 |
3 |
4 | ###List
5 |
7 |
8 | List(String) list = new ArrayList<>();
9 |
10 | You can preset size if you would like; it still has dynamic growth.
11 |
12 |
13 | add(E object)
14 |
15 | - add an object to the current index
16 | - returns a boolean value
17 |
18 |
19 | get(int index)
20 |
21 | - grab the object at the given index
22 |
23 |
24 | addAll(Collection extends E> collection)
25 |
26 | - List(String) newList = new ArrayList<>();
27 |
newList.addAll(list);
28 |
this adds every element in list into newList as if it were doing
29 |
a for loop for(E element: list) newList[i]=E
30 |
31 | - returns a boolean value
32 |
33 |
34 |
35 |
36 |
37 |
44 |
52 |
--------------------------------------------------------------------------------
/12-EPI/ch6-arrays/deletingDuplicates/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 |
4 | class Solution {
5 |
6 |
7 | public static void deletingDuplicates(List A) {
8 | int validEntry = 1;
9 | int len = A.size() - 1;
10 | for(int i = 1; i <= len; ++i) {
11 | //if not duplicates from prev => add it to our new list!
12 | if(!A.get(validEntry -1 ).equals(A.get(i))) {
13 | A.set(validEntry++, A.get(i));
14 | }
15 | }
16 |
17 | System.out.println(A);
18 |
19 | }
20 |
21 | ///bad since extra storage
22 | public static void bruteForceSolution(List A) {
23 | //keep track of duplicate
24 | // int duplicate;
25 | List container = new ArrayList<>();
26 | for(int i = 1; i < A.size(); i++) {
27 | if( !A.get(i).equals(A.get(i-1)) ) {
28 | container.add(A.get(i));
29 | }
30 | }
31 | System.out.println(container);
32 | }
33 |
34 | public static void main(String[] args) {
35 | deletingDuplicates(Arrays.asList(2, 3, 5, 7, 7, 7, 11, 11, 11, 13, 15));
36 | bruteForceSolution(Arrays.asList(2, 3, 5, 7, 7, 7, 11, 11, 11, 13, 15));
37 | int[] ne = new int[]{1, 2};
38 |
39 | }
40 | }
--------------------------------------------------------------------------------
/99-answerKey/leetcode/67|Add-Binary/README.md:
--------------------------------------------------------------------------------
1 | #Add Binary [Success]
2 |
3 | Runtime only beats 2.10% of Java Submissions
4 | Runtime: 27 ms
5 | Comps: FB
6 | Tagged: Math & String
7 |
8 |
9 |
10 |
11 |
12 | #Thinking
13 |
14 |
15 |
16 | | Data Structure/Other |
17 | Method |
18 | Space Complexity [If applicable] |
19 | Explain |
20 |
21 |
22 |
23 |
24 |
25 | | Array & int |
26 | Character.getNumeric Value(a.charAt(i)) |
27 | This is what is making this extremely slow. The look-up is O(1), but then it seems that Character.getNumericValue(char)
28 | might be expensive. If not that, then my string traversal that makes both string the same length O(n)
29 | is what is slowing it down. |
30 | If I want to improve the runtime, then I would make a switch that goes off when I reach the max
31 | length limit of the shorter string rather than making both string the same length since by doing that
32 | I am adding O(n) to make them the same length and on top of that I am adding O(lengthDifference) to
33 | for when I am adding both binary strings. |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/362-Design-HitCounter/HitCounter.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | public class HitCounter {
3 |
4 | /** Initialize your data structure here. */
5 | Deque deque;
6 |
7 | public HitCounter() {
8 | deque = new ArrayDeque<>();
9 | }
10 |
11 | /** Record a hit.
12 | @param timestamp - The current timestamp (in seconds granularity). */
13 | public void hit(int timestamp) {
14 | int within = timestamp - 300;
15 | deque.push(timestamp);
16 | while(!deque.isEmpty() && (int)deque.peekLast() < within){
17 | deque.pollLast();
18 | }
19 | }
20 |
21 | /** Return the number of hits in the past 5 minutes.
22 | @param timestamp - The current timestamp (in seconds granularity). */
23 | public int getHits(int timestamp) {
24 | int within = timestamp - 300;
25 | while(!deque.isEmpty() && (int)deque.peekLast() <= within){
26 | deque.pollLast();
27 | }
28 | return deque.size();
29 | }
30 | }
31 |
32 | /**
33 | * Your HitCounter object will be instantiated and called as such:
34 | * HitCounter obj = new HitCounter();
35 | * obj.hit(timestamp);
36 | * int param_2 = obj.getHits(timestamp);
37 | */
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Stack/Stack.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | public class Stack >
3 | {
4 |
5 | public static class StackNode
6 | {
7 | public T data;
8 | public StackNode next;
9 | public StackNode(T data)
10 | {
11 | this.data = data;
12 | }
13 | }
14 |
15 | public StackNode top;
16 |
17 | /**
18 | * LIFO, stack of dishes
19 | * @return the top-most (last placed) element
20 | */
21 | public T pop()
22 | {
23 | if(top == null){
24 | throw new EmptyStackException();
25 | }
26 | T item = top.data;
27 | top = top.next;
28 | return item;
29 | }
30 |
31 | /**
32 | * LIFO, hence placed at the top
33 | * @param an Object item, that'll be placed on the top
34 | */
35 | public void push(T item)
36 | {
37 | StackNode node = new StackNode<>(item);
38 | node.next = top;
39 | top = node;
40 | }
41 |
42 |
43 | /**
44 | * LIFO stack
45 | * @return top-most element on the stack
46 | */
47 | public T peek()
48 | {
49 | return top.data;
50 | }
51 |
52 | /**
53 | * This is used to see if the stack still has elements left in it.
54 | * @return if Empty return true, else reeturn false
55 | */
56 | public boolean isEmpty()
57 | {
58 | return top == null;
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/99-answerKey/algorithms/graphSearch/Graph.java:
--------------------------------------------------------------------------------
1 |
2 | import java.util.ArrayDeque;
3 | import java.util.ArrayList;
4 | import java.util.Deque;
5 | import java.util.HashSet;
6 | import java.util.List;
7 | import java.util.Set;
8 |
9 | public class Graph{
10 |
11 |
12 |
13 | private List[] sources;
14 | int size;
15 | //Edge = sourceVertex----edgeWeight------->targetVertex
16 |
17 | @SuppressWarnings("unchecked")
18 | public Graph(int size)
19 | {
20 | this.size = size;
21 | sources = (ArrayList[])new ArrayList[size];
22 | initarr(sources, size);
23 | }
24 |
25 |
26 | public void initarr(List[] sources, int size)
27 | {
28 | for(int i = 0; i < size; i++)
29 | {
30 | sources[i] = new ArrayList();
31 | }
32 | }
33 |
34 | public List getOtherSources(int target)
35 | {
36 | return sources[target];
37 | }
38 |
39 | public int size() {
40 | return size;
41 | }
42 |
43 | public Edge setDirectedEdge(int vSource, int vTarget, double eWeight)
44 | {
45 | List sources = getOtherSources(vTarget);
46 | Edge edge = new Edge(vSource, vTarget, eWeight);
47 | sources.add(edge);
48 | return edge;
49 | }
50 |
51 | public Edge notDirectedEdeg(int vertexSource, int vertexTarget, double eWeight) {
52 |
53 | }
54 |
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Graphs/Graph/testing.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | import java.io.*;
3 | import java.util.regex.Pattern;
4 | public class testing{
5 |
6 | public static void formLinks(InputStream sourceWlink, int vertices) throws Exception
7 | {
8 | BufferedReader reader = new BufferedReader(new InputStreamReader(sourceWlink));
9 | Pattern spaced = Pattern.compile(" ");
10 | int[][] sourceTarget = new int[vertices][];
11 | int[] linksToID;
12 | String connections;
13 | String[] allTargets;
14 | int i = 0, j;
15 | while( (connections = reader.readLine()) != null )
16 | {
17 | connections = connections.trim();
18 | if(connections.isEmpty())
19 | {
20 | sourceTarget[i] = new int[0]; //safe-guard from future null checks.
21 | }
22 | else
23 | {
24 | allTargets = connections.split(" ");
25 | linksToID = new int[allTargets.length]; // contain all ID of nodes connected to
26 | for(j = 0; j < linksToID.length; j++)
27 | {
28 | linksToID[j] = Integer.parseInt(allTargets[j]);
29 | }
30 | }
31 | }
32 | }
33 |
34 | public static void main(String[] args) throws Exception
35 | {
36 | int vertices = 100;
37 | String LINK_FILE = "wiki-links.txt";
38 | formLinks( new FileInputStream(LINK_FILE) , vertices) ;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch1-Arrays-Strings/1-unqiueString/unqiueString.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by christian on 5/15/16.
3 | */
4 | import java.util.*;
5 | public class unqiueString {
6 |
7 | /*Chapter 1 Problem 1:
8 | See if the string contains all unique characters
9 | There are only 256 possible characters **/
10 |
11 | public static boolean unqiueString(String test)
12 | {
13 |
14 | int length = test.length();
15 | if(length == 0) return true; //not 1 b/c can have 2 blanks
16 | if(length >= 256) return false; //pigeon hole
17 | boolean[] sliceString = new boolean[256]; //256 unique
18 | for(int i = 0; i < length; i++)
19 | {
20 | int checkChar = test.charAt(i);
21 | if(!sliceString[checkChar])
22 | {
23 | sliceString[checkChar] = true;
24 | }
25 | else {return false;}
26 | }
27 | return true;
28 |
29 | }
30 |
31 | public static void main(String[] args)
32 | {
33 | Scanner input = new Scanner(System.in);
34 | System.out.println("True or false, this String contains all unique chars?");
35 | String myString = input.nextLine();
36 | System.out.println(unqiueString(myString));
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/290|Word-Pattern-I/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class Solution {
4 |
5 | public static boolean wordPattern(String pattern, String str){
6 | Map map = new HashMap<>();
7 | int plen = pattern.length();
8 | String[] words = (plen==1)? new String[]{str}: str.split(" ");
9 | if(plen != words.length){return false;}
10 | for(int i = 0; i < plen; i++){
11 | String holdit = "" +pattern.charAt(i);
12 | String wordnow = words[i];
13 | if(map.containsKey(holdit)){
14 | if(!map.get(holdit).equals(wordnow)){
15 | return false;
16 | }
17 | } else {
18 | if(map.containsValue(wordnow)){
19 | return false;
20 | }
21 | map.put(holdit, wordnow);
22 | }
23 | }
24 | return true;
25 | }
26 |
27 | public static void main(String[] args){
28 | String ptrn = "abc";
29 | String words = "dog dog dog";
30 | System.out.println(wordPattern(ptrn, words));
31 | ptrn = "abba";
32 | words = "dog dog dog dog";
33 | System.out.println(wordPattern(ptrn, words));
34 | ptrn = "abba";
35 | words = "dog cat cat fish";
36 | System.out.println(wordPattern(ptrn, words));
37 | ptrn = "aaa";
38 | words = "dog cat cat dog";
39 | System.out.println(wordPattern(ptrn, words));
40 |
41 | }
42 | }
--------------------------------------------------------------------------------
/99-answerKey/algorithms/graphSearch/testing.java:
--------------------------------------------------------------------------------
1 | package graph;
2 | import java.util.*;
3 | import java.io.*;
4 | import java.util.regex.Pattern;
5 | public class testing{
6 |
7 | public static void formLinks(InputStream sourceWlink, int vertices) throws Exception
8 | {
9 | BufferedReader reader = new BufferedReader(new InputStreamReader(sourceWlink));
10 | Pattern spaced = Pattern.compile(" ");
11 | int[][] sourceTarget = new int[vertices][];
12 | int[] linksToID;
13 | String connections;
14 | String[] allTargets;
15 | int i = 0, j;
16 | while( (connections = reader.readLine()) != null )
17 | {
18 | connections = connections.trim();
19 | if(connections.isEmpty())
20 | {
21 | sourceTarget[i] = new int[0]; //safe-guard from future null checks.
22 | }
23 | else
24 | {
25 | allTargets = connections.split(" ");
26 | linksToID = new int[allTargets.length]; // contain all ID of nodes connected to
27 | for(j = 0; j < linksToID.length; j++)
28 | {
29 | linksToID[j] = Integer.parseInt(allTargets[j]);
30 | }
31 | }
32 | }
33 | }
34 |
35 | public static void main(String[] args) throws Exception
36 | {
37 | int vertices = 100;
38 | String LINK_FILE = "wiki-links.txt";
39 | formLinks( new FileInputStream(LINK_FILE) , vertices) ;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch3-Stacks-Queues/3-generic-Stack/Stack.java:
--------------------------------------------------------------------------------
1 | import java.util.EmptyStackException;
2 | public class Stack >
3 | {
4 |
5 | public static class StackNode
6 | {
7 | public T data;
8 | public StackNode next;
9 | public StackNode(T data)
10 | {
11 | this.data = data;
12 | }
13 | }
14 |
15 | public StackNode top;
16 |
17 | /**
18 | * LIFO, stack of dishes
19 | * @return the top-most (last placed) element
20 | */
21 | public T pop()
22 | {
23 | if(top == null){
24 | throw new EmptyStackException();
25 | }
26 | T item = top.data;
27 | top = top.next;
28 | return item;
29 | }
30 |
31 | /**
32 | * LIFO, hence placed at the top
33 | * @param an Object item, that'll be placed on the top
34 | */
35 | public void push(T item)
36 | {
37 | StackNode node = new StackNode<>(item);
38 | node.next = top;
39 | top = node;
40 | }
41 |
42 |
43 | /**
44 | * LIFO stack
45 | * @return top-most element on the stack
46 | */
47 | public T peek()
48 | {
49 | return top.data;
50 | }
51 |
52 | /**
53 | * This is used to see if the stack still has elements left in it.
54 | * @return if Empty return true, else reeturn false
55 | */
56 | public boolean isEmpty()
57 | {
58 | return top == null;
59 | }
60 |
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/99-answerKey/genericFrequent/getSum/sumints.java:
--------------------------------------------------------------------------------
1 | import java.util.Map;
2 | import java.util.HashMap;
3 | import java.util.Arrays;
4 |
5 | public class sumints{
6 |
7 | /**
8 | * [sum] gets you the indices of the two integers
9 | * that sum up to target
10 | * @param nums [an array of integers]
11 | * @param target [the integer you want to sum up for]
12 | * @return [the indices of the numbers that sum up to target]
13 | */
14 | public static int[] sum(int[] nums, int target)
15 | {
16 |
17 | if(nums == null || nums.length == 0) {return null;}
18 |
19 | int i, len = nums.length;
20 | Map map = new HashMap<>(len); //Cost: O(N)
21 |
22 | for(i = 0; i < len; i++)
23 | {
24 | map.put(nums[i], i);
25 | }//Runtime: O(N)
26 |
27 | for(i = 0; i < len; i++)
28 | {
29 | int remainder = target - nums[i];
30 | if( map.containsKey(remainder) && map.get(remainder) != i)
31 | {
32 | return new int[]{i, map.get(remainder)};
33 | }
34 | }//Runtime: O(N)
35 |
36 | return null;
37 | }
38 |
39 | public static void main(String[] args)
40 | {
41 | int[] nums = new int[]{1, 2, 13, 4, 9, 30, 39, 1000, 80, 900};
42 | int want = 8100;
43 | System.out.println( Arrays.toString(sum(nums, want) ) );
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/12-EPI/ch6-arrays/carryOverAdd/Solution.java:
--------------------------------------------------------------------------------
1 | /*
2 | <9, 9, 9, 9> + 1 => <1, 0, 0, 0, 0>
3 | <1, 9, 9, 9> + 1 => <2, 0, 0, 0>
4 | In this case only add one to our list
5 | take care of carryovers
6 | */
7 |
8 | import java.util.*;
9 | class Solution {
10 |
11 | public static void addOne(List list) {
12 | //start from the end work to the beg!
13 | int len = list.size();
14 | list.set(len-1, list.get(len-1) + 1);
15 | //we only want to keep iterating if there is a carry over
16 | for(int i = len-1; i > 0 && list.get(i) == 10; i--) {
17 | list.set(i, 0); //make this 0
18 | list.set(i-1, list.get(i-1) + 1); //ready up the next index
19 | }
20 |
21 | //does our head (first index) have a carry over?
22 | if(list.get(0)==10) {
23 | list.set(0,0);
24 | list.add(0,1); //pushes all elements to the right
25 | }
26 |
27 | System.out.println("Done: " + list);
28 |
29 | }
30 |
31 | public static void main(String[] args) {
32 | List list = new ArrayList<>();
33 | for(Integer i: new Integer[]{9, 9, 9, 9}) {
34 | list.add(i);
35 | }
36 | addOne(list);
37 |
38 | list = new ArrayList<>();
39 | for(Integer i: new Integer[]{1, 9, 9, 9}) {
40 | list.add(i);
41 | }
42 | addOne(list);
43 | System.out.println(true ^ false);
44 | }
45 | }
--------------------------------------------------------------------------------
/99-answerKey/leetcode/2|Add-Two-Numbers/practice/addTwoNumbers.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class addTwoNumbers{
4 |
5 | //inner class defined
6 | public class ListNode{
7 | int val;
8 | ListNode next;
9 |
10 | //no access modifier => default
11 | ListNode(int x)
12 | {
13 | val = x;
14 | }
15 | }
16 |
17 | public ListNode putNode(int newnode)
18 | {
19 | size++;
20 | ListNode head = new ListNode(newnode);
21 | while(ptr.next != null)
22 | {
23 | ptr = ptr.next; //we break at an empty spot
24 | }
25 | ptr.next = node;
26 | node.next = null;
27 | return node;
28 | }
29 |
30 | public void listofints(int[] list)
31 | {
32 | ListNode head;
33 | for(int i: list)
34 | if(i==0){head = new ListNode(list[i]);}
35 | }
36 |
37 |
38 |
39 |
40 | public ListNode addTwoNumbers(ListNode l1, ListNode l2)
41 | {
42 | ListNode linkedSum = new ListNode(l1.val + l2.val);
43 | while((l1 = l1.next) != null && (l2 = l2.next) != null)
44 | {
45 | ListNode sum = new ListNode(l1.val + l2.val);
46 | linkedSum.next = sum;
47 | linkedSum = linkedSum.next;
48 | }
49 | return linkedSum;
50 | }
51 |
52 |
53 |
54 | public static void main(String[] args)
55 | {
56 |
57 |
58 |
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/439-ternary-exprsn-parser/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | class Solution{
3 |
4 | //similar to reverse polish notation
5 | public static String parseTernary(String expression){
6 | if(expression == null){return "";}
7 | int len = expression.length();
8 | Deque stack = new ArrayDeque<>();
9 | String current;
10 | String[] expr = expression.split("");
11 | for(int i = len-1; i >= 0; i--){
12 | current = expr[i];
13 | if(!stack.isEmpty() && stack.peek().equals("?")){
14 | //?T:F
15 | stack.pop();
16 | String yep = stack.pop();
17 | stack.pop();
18 | String nope = stack.pop();
19 | if(current.equals("T")){
20 | stack.push(yep);
21 | } else{
22 | stack.push(nope);
23 | }
24 | }
25 | else {
26 | stack.push(current);
27 | }
28 | }
29 | return stack.pop();
30 | }
31 |
32 |
33 |
34 |
35 |
36 | public static void main(String[] args){
37 | String candidate = "T?2:3";
38 | System.out.println(parseTernary(candidate));
39 | candidate = "T?T?1:3:4";
40 | System.out.println(parseTernary(candidate));
41 | }
42 | }
--------------------------------------------------------------------------------
/99-answerKey/algorithms/graphSearch/Dijkstra.java:
--------------------------------------------------------------------------------
1 |
2 | import java.util.*;
3 |
4 |
5 | class Dijkstra {
6 | public static void intit(double[] distances, Integer[] previous, int target) {
7 | for(int i = 0; i < distances.length; i++) {
8 | if(distances[i] == target) {
9 | distances[i] = 0; //distance is 0 since starting point
10 | }
11 | distances[i] = Double.MAX_VALUE; //all infinite
12 | previous[i] = null; //Object
13 | }
14 | }
15 |
16 | public static Integer[] shortestPath(Graph graph, int source, int target) {
17 | Queue q = new PriorityQueue<>();
18 | double[] distances = new double[graph.size()];
19 | Integer[] previous = new Integer[graph.size()];
20 | Set vertixVisted = new HashSet<>();
21 | intit(distances, previous, target);
22 | q.add(new VertexDistancePair(0, target));
23 | while(!q.isEmpty()) {
24 | //visit what is on top
25 | VertexDistancePair current = q.poll();
26 | visited.add(current.vertex);
27 |
28 | }
29 | return null;
30 | }
31 |
32 |
33 |
34 | public static class VertexDistancePair{
35 | double distance;
36 | int vertex;
37 | public VertexDistancePair(double distance, int vertex){
38 | this.distance = distance;
39 | this.vertex = vertex;
40 | }
41 | }
42 |
43 | public static void main(String[] args) {
44 |
45 | }
46 | }
--------------------------------------------------------------------------------
/99-answerKey/leetcode/266-Palindrome-Permutation/Solution.java:
--------------------------------------------------------------------------------
1 | /*
2 | Given a string, determine if a permutation of the
3 | string could form a palindrome.
4 |
5 | For example,
6 | "code" -> False, "aab" -> True, "carerac" -> True.
7 | **/
8 | import java.util.*;
9 | public class Solution {
10 | public boolean canPermutePalindrome(String s) {
11 | String[] characters = s.split("");
12 |
13 |
14 |
15 |
16 | if(s.length() == 0){return true;}
17 | String[] container = s.replaceAll(" ", "").split("");
18 | Map map = new HashMap<>();
19 | for(String c : container)
20 | {
21 | if(map.containsKey(c))
22 | {
23 | map.put(c, map.get(c)+1);
24 | }
25 | else
26 | {
27 | map.put(c, 1);
28 | }
29 | }
30 |
31 | Iterator iter = map.entrySet().iterator();
32 | boolean tripwire = false;
33 | while(iter.hasNext())
34 | {
35 | Map.Entry paired = (Map.Entry) iter.next();
36 | int val = (int)paired.getValue();
37 | if(val%2 != 0)
38 | {
39 | if(tripwire)
40 | {
41 | return false;
42 | }
43 | else
44 | {
45 | tripwire=true;
46 | }
47 | }
48 | }
49 | return true;
50 |
51 | }
52 |
53 | public static void main(String[] args) {
54 |
55 | }
56 |
57 | }
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch2-Linked_list/1-remove_dups/SolutionNoBuffer.java:
--------------------------------------------------------------------------------
1 | class SolutionNoBuffer {
2 |
3 |
4 | /*
5 | No buffer!
6 | */
7 | public static void removedDuplicates(Node head) {
8 | Node ptr = head; //head is just a pointer!
9 | while(ptr != null) {
10 | Node ahead = ptr;
11 | while(ahead.next != null) {
12 | if(ahead.next.data == ptr.data) {
13 | //move the .next reference to the next node
14 | //don't change the pointer itself, since this new .next could be a dupe
15 | ahead.next = ahead.next.next;
16 | } else {
17 | ahead = ahead.next;
18 | }
19 | }
20 | ptr = ptr.next; //our next node search
21 | }
22 | }
23 |
24 | public static void main(String[] args) {
25 | Node head = new Node(2);
26 | Node ptr = head;
27 | //dupes = 1, 4, 5, 2
28 |
29 | for(int i: new int[]{1, 1, 3, 4, 5, 1, 4, 2, 5}){
30 | ptr.next = new Node(i);
31 | ptr = ptr.next;
32 | }
33 | //final form = 2, 1, 3, 4, 5
34 | //checkit(head);
35 | removedDuplicates(head);
36 | Node ptrCheck = head;
37 | while(ptrCheck!=null) {
38 | System.out.println(ptrCheck.data);
39 | ptrCheck = ptrCheck.next;
40 | }
41 | }
42 |
43 | }
44 |
45 | class Node {
46 | int data;
47 | Node next;
48 | public Node(int data) {
49 | this.data = data;
50 | }
51 | }
--------------------------------------------------------------------------------
/99-answerKey/companies/thumbtack/meds/RevPolish.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | class RevPolish{
3 |
4 |
5 | public int evalRPN(String[] tokens) {
6 | int len = tokens.length;
7 | Deque eq = new ArrayDeque<>();
8 | doMath("", "a", "b");
9 | List operators = Arrays.asList( new String[]{"/","-","*", "+"} );
10 | eq.push(tokens[0]);
11 | for(int i=1; i< len;i++){
12 | String curr = tokens[i];
13 | if(operators.contains(curr)){
14 | eq.push(doMath(curr, eq.poll(), eq.poll()) + "");
15 | } else {
16 | eq.push(curr);
17 | }
18 | }
19 | System.out.println(eq.peek());
20 | return Integer.parseInt(eq.poll());
21 | }
22 |
23 | public int doMath(String op, String b, String a){
24 | switch(op){
25 | case ("-"): return (Integer.parseInt(a))-(Integer.parseInt(b));
26 | case ("+"): return (Integer.parseInt(a))+(Integer.parseInt(b));
27 | case ("/"): return (Integer.parseInt(a))/(Integer.parseInt(b));
28 | case ("*"): return (Integer.parseInt(a))*(Integer.parseInt(b));
29 | }
30 | return 0;
31 | }
32 |
33 |
34 |
35 | public static void main(String[] args){
36 | RevPolish call = new RevPolish();
37 | call.evalRPN(new String[]{"2", "1", "+", "3", "*"});
38 | call.evalRPN(new String[]{"4", "13", "5", "/", "+"});
39 | //3 4 − 5 + => 3 − 4 + 5
40 | // ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
41 | //["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
42 | }
43 | }
--------------------------------------------------------------------------------
/99-answerKey/leetcode/234-Palindrome-LL/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * public class ListNode {
4 | * int val;
5 | * ListNode next;
6 | * ListNode(int x) { val = x; }
7 | * }
8 | */
9 | import java.util.*;
10 | public class Solution {
11 |
12 | public static boolean isPalindrome(ListNode head){
13 | ListNode ptr = head;
14 | List candidate = new ArrayList<>();
15 | while(ptr!= null) {
16 | candidate.add(ptr.val);
17 | ptr = ptr.next;
18 | }
19 |
20 | //have string now do palindrome check
21 | int len = candidate.size();
22 | if(len == 0|| len ==1){return true;}
23 | int start = 0;
24 | int end = len-1;
25 | for(start = 0; start <= len/2; start++, end--){
26 | if((int)candidate.get(start)!=(int)candidate.get(end)){
27 | return false;
28 | }
29 | }
30 | return true;
31 | }
32 |
33 | public static void main(String[] args){
34 | ListNode head = new ListNode(-1);
35 | ListNode second = new ListNode(1);
36 | ListNode clonetwo = new ListNode(1);
37 | ListNode third = new ListNode(-1);
38 | head.next = second;
39 | second.next = clonetwo;
40 | clonetwo.next = third;
41 | System.out.println(isPalindrome(head));
42 | }
43 | }
44 |
45 | class ListNode {
46 | int val;
47 | ListNode next;
48 | public ListNode(int val){
49 | this.val = val;
50 | }
51 |
52 |
53 | }
--------------------------------------------------------------------------------
/99-answerKey/leetcode/67|Add-Binary/Solution.java:
--------------------------------------------------------------------------------
1 | public class Solution {
2 |
3 | public String addBinary(String a, String b)
4 | {
5 | int diff = a.length() - b.length(), i, bin;
6 | int len = a.length(); //in case equal
7 | if(diff > 0){
8 | b = stringCap(diff, b);
9 | len = a.length();
10 | System.out.println(b);
11 | }
12 | else if(diff < 0){
13 | a = stringCap((int)Math.abs(diff) , a);
14 | len = b.length(); //doesn't matter
15 | }
16 | int rem = 0;
17 | String result = "";
18 | for(i = len-1 ; i >-1; i--)
19 | {
20 | bin = Character.getNumericValue(a.charAt(i)) + Character.getNumericValue(b.charAt(i)) + rem;
21 | if(bin > 1)
22 | {
23 | rem = 1;
24 | result = Integer.toString(bin%2) + result;
25 | }
26 | else
27 | {
28 | rem = 0;
29 | result = Integer.toString(bin) + result;
30 | }
31 | }
32 | if(rem == 1){
33 | result = "1" + result;
34 | }
35 | System.out.println(result);
36 | return result;
37 | }
38 |
39 | public static String stringCap(int n, String addTo)
40 | {
41 | while(n!=0)
42 | {
43 | addTo = "0" + addTo;
44 | n--;
45 | }
46 | return addTo;
47 | }
48 |
49 |
50 | public static void main(String[] args)
51 | {
52 | Solution caller = new Solution();
53 | caller.addBinary("101", "1111");
54 | }
55 |
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/12-EPI/ch4/squaresWithinRange.java:
--------------------------------------------------------------------------------
1 | public class squaresWithinRange {
2 |
3 | public static boolean isPerfect(int numb) {
4 | return (Math.pow(numb, 0.5)%1 == 0);
5 | }
6 |
7 | public static int singlyRange(int numb) {
8 | int start = 0;
9 | int numbPerfs = 0;
10 | for(int i = 1; i < numb; i++) {
11 | boolean perfSquare;
12 | if (perfSquare = isPerfect(i)) {
13 | System.out.println("this is perfect: " + i);
14 | numbPerfs++;
15 | }
16 | }
17 | return numbPerfs;
18 | }
19 |
20 | public static int rangeSquares(int[] pair) {
21 | int len = pair.length;
22 | if(len == 0 ) {
23 | return 0;
24 | }
25 | if (len == 1) {
26 | return singlyRange(pair[0]);
27 | }
28 | int numbPerfs = 0,
29 | start = pair[0],
30 | end = pair[1];
31 | for(int i = start+1; i < end; i++) {
32 | boolean perf;
33 | if( perf = isPerfect(i) ){
34 | System.out.println("this is perfect: " + i);
35 | numbPerfs++;
36 | }
37 | }
38 | return numbPerfs;
39 | }
40 |
41 | public static void main(String[] args) {
42 | int[] pairing = new int[]{9, 90};
43 | System.out.println("there are " + rangeSquares(pairing) + " perfect squares");
44 | int[] singly = new int[]{500};
45 | double container = Math.pow(500, 0.5);
46 | System.out.println("hello: " + container);
47 | System.out.println("there are " + rangeSquares(singly) + " perfect squares");
48 | }
49 | }
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch1-arrays-and-strings/3-urlify/Solution.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Solution {
4 |
5 | public static String urlify(char[] c, int realLength) {
6 | //The "holes" will be from [0, realLength]
7 | int holes = 0;
8 |
9 | for(int i = 0; i < realLength; i++) {
10 | if(c[i] == ' ') {
11 | holes++;
12 | }
13 | }
14 |
15 |
16 | //holes = 1 spot, need 2 more spaces
17 | //endpoint start building string from here
18 | int totalLength = realLength + 2*holes;
19 |
20 | for(int i = realLength - 1; i >= 0; i--) {
21 | if(c[i] != ' ') {
22 | //nothing to add, just place it
23 | c[totalLength - 1] = c[i];
24 | totalLength--;
25 | }
26 | else {
27 | //%20
28 | c[totalLength - 1] = '0';
29 | c[totalLength - 2] = '2';
30 | c[totalLength - 3] = '%';
31 | totalLength -= 3;
32 | }
33 | }
34 |
35 | //System.out.println(c);
36 | return new String(c);
37 | }
38 |
39 | public static void main(String[] args) {
40 | String str = "Mr John Smith";
41 | int real_len = str.length();
42 | char[] c = new char[str.length() + 11];
43 | int index = 0;
44 | for(char i: str.toCharArray()){
45 | c[index++] = i;
46 | }
47 |
48 | /*
49 | index = 1;
50 | for(char o: c) {
51 | System.out.println(index++ + " =>" + o);
52 | }
53 | */
54 | System.out.println(str + "=>" + urlify(c, real_len));
55 | }
56 | }
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch1-Arrays-Strings/7-setzeroMatrix/setzeroMatrix.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by christian on 5/15/16.
3 | */
4 |
5 | import java.util.*;
6 | public class setzeroMatrix{
7 |
8 | //assuming nbyn
9 | //zero matrix: if index contains 0, then its entire row and col = 0
10 | public static int[][] setZeros(int[][] matrix)
11 | {
12 | int nbyn = matrix.length;
13 | boolean[] rows = new boolean[nbyn];
14 | boolean[] cols = new boolean[nbyn];
15 | int i,j;
16 |
17 | //look for zeros
18 | for( i = 0; i < nbyn; i++)
19 | {
20 | for( j = 0; j < nbyn; j++)
21 | {
22 | if(matrix[i][j] == 0) //found one
23 | {
24 | rows[i] = true;
25 | cols[j] = true;
26 | break;
27 | }
28 | }
29 | }
30 | for( i = 0; i < nbyn; i++)
31 | {
32 | for( j = 0; j < nbyn; j++)
33 | {
34 | if(rows[i] || cols[j]) //found one
35 | {
36 | matrix[i][j] = 0;
37 | }
38 | }
39 | }
40 | return matrix;
41 | }
42 | public static void main(String[] args)
43 | {
44 | int[][] matrix = new int[][]{{1, 2, 0},{3, 4, 0},{1, 2, 3}};
45 | System.out.println(Arrays.deepToString(matrix));
46 | System.out.println( Arrays.deepToString(setZeros(matrix)) );
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/438|SubstringAnagrams/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class Solution {
4 |
5 |
6 |
7 | public List findAnagrams(String s, String p) {
8 | int sLen = s.length();
9 | int pLen = p.length();
10 | String[] parr = p.split("");
11 | Arrays.sort(parr);
12 | String[] sarr = s.split("");
13 | Deque window = new ArrayDeque<>();
14 | List list = new ArrayList<>();
15 | for(int i = 0; i < sLen; i++){
16 | // if(window.size() == pLen){
17 | // window.pollFirst();
18 | // }
19 | window.addLast(sarr[i]);
20 | System.out.println("=>"+window);
21 | //check if matched sum aka
22 | // if(comparisonNow(parr, window)){
23 | // list.add(i);
24 | // }
25 | }
26 | System.out.println(list);
27 | return list;
28 | }
29 |
30 | public boolean comparisonNow(String[] parr, Deque window){
31 | Deque reference = new ArrayDeque<>();
32 | String[] arr = new String[window.size()];
33 | int i = 0;
34 | while(!window.isEmpty()){
35 | arr[i] = window.poll();//head
36 | reference.pushFirst(arr[i])l
37 | i++;
38 | }//need to push everything back now
39 | window = reference;
40 | Arrays.sort(arr);
41 | if(Arrays.toString(parr).equals(Arrays.toString(parr))){
42 | return true;
43 | }
44 | return false;
45 | }
46 |
47 |
48 | public static void main(String[] args){
49 | Solution invoker = new Solution();
50 | String s = "abab";
51 | String p = "abc";
52 | invoker.findAnagrams(s, p);
53 | }
54 | }
--------------------------------------------------------------------------------
/99-answerKey/companies/pin/reachZero/Solution.java:
--------------------------------------------------------------------------------
1 |
2 | import java.util.*;
3 |
4 | class Solution {
5 |
6 | public static boolean landZero(int[] bridge, int start){
7 | //can move left or right
8 | int len = bridge.length;
9 | Deque current = new ArrayDeque<>();
10 | List visted = new ArrayList<>();
11 | current.push(start);
12 | while(!current.isEmpty()){
13 | int indexOn = (int)current.poll(); //index
14 | int jump = bridge[indexOn]; //jump
15 | int left = indexOn - jump;
16 | int right = indexOn + jump;
17 |
18 | if(markJump(bridge, left)){
19 | if(bridge[left] ==0){return true;}
20 | if(!visted.contains(left)){
21 | visted.add(left);
22 | current.push(left);
23 | }
24 | }
25 | if(markJump(bridge, right)){
26 | if(bridge[right]==0){return true;}
27 | if(!visted.contains(right)){
28 | visted.add(right);
29 | current.push(right);
30 | }
31 | }
32 | }
33 | return false;
34 | }
35 |
36 | public static boolean markJump(int[] bridge, int dir){
37 | if(dir < bridge.length && dir >= 0 ){
38 | return true;
39 | }
40 | else{
41 | return false;
42 | }
43 | }
44 |
45 |
46 |
47 | public static void main(String[] args) {
48 | System.out.println(landZero(new int[]{1, 2, 3, 1, 2, 1, 1}, 1)); //false
49 | System.out.println(landZero(new int[]{1, 0, 2, 1, 2, 1, 1}, 2)); //true
50 | System.out.println(landZero(new int[]{1, 1, 2, 1, 2, 0, 3}, 2)); //false
51 | }
52 | }
--------------------------------------------------------------------------------
/2-Data-Structures/LinkedLists/DoublyLinkedList/DoublyTasks.java:
--------------------------------------------------------------------------------
1 | package DoublyLinkedList;
2 | public class DoublyTasks
3 | {
4 | //don't want client to see in main
5 | public static void caller(DoublyLinkedList list, String where)
6 | {
7 | if( "head".equals(where) )
8 | {
9 | try {
10 | list.removeHead();
11 | }
12 | catch( Exception e)
13 | {
14 | System.out.println("Removing from an empty list");
15 | }
16 | }
17 | else if( "tail".equals(where) )
18 | {
19 | try {
20 | Node hold = list.removeTail();
21 | }
22 | catch( Exception e)
23 | {
24 | System.out.println("Removing from an empty list");
25 | }
26 | }
27 | else
28 | System.out.println("Invalid Request!");
29 | }
30 |
31 |
32 | public static void removeCaller(DoublyLinkedList list, int data)
33 | {
34 | try{
35 | list.deleteNode(data);
36 | } catch (Exception e)
37 | {
38 | System.out.println("Removing from an empty list");
39 | }
40 | }
41 |
42 | public static void main(String[] args)
43 | {
44 | DoublyLinkedList list = new DoublyLinkedList();
45 | list.putMultiNodes(5, 6, 9, 12, 15);
46 | System.out.println("Complete List: ");
47 | list.listToString();
48 | System.out.println("Removed Head: ");
49 | caller(list, "head");
50 | list.listToString();
51 | System.out.println("Removed Tail: ");
52 | caller(list, "tail");
53 | list.listToString();
54 | int data = 9;
55 | System.out.println("Removing desired: " + data);
56 | removeCaller(list, data);
57 | list.listToString();
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Linked-List/DoublyLinkedList/DoublyTasks.java:
--------------------------------------------------------------------------------
1 | package DoublyLinkedList;
2 | public class DoublyTasks
3 | {
4 | //don't want client to see in main
5 | public static void caller(DoublyLinkedList list, String where)
6 | {
7 | if( "head".equals(where) )
8 | {
9 | try {
10 | list.removeHead();
11 | }
12 | catch( Exception e)
13 | {
14 | System.out.println("Removing from an empty list");
15 | }
16 | }
17 | else if( "tail".equals(where) )
18 | {
19 | try {
20 | Node hold = list.removeTail();
21 | }
22 | catch( Exception e)
23 | {
24 | System.out.println("Removing from an empty list");
25 | }
26 | }
27 | else
28 | System.out.println("Invalid Request!");
29 | }
30 |
31 |
32 | public static void removeCaller(DoublyLinkedList list, int data)
33 | {
34 | try{
35 | list.deleteNode(data);
36 | } catch (Exception e)
37 | {
38 | System.out.println("Removing from an empty list");
39 | }
40 | }
41 |
42 | public static void main(String[] args)
43 | {
44 | DoublyLinkedList list = new DoublyLinkedList();
45 | list.putMultiNodes(5, 6, 9, 12, 15);
46 | System.out.println("Complete List: ");
47 | list.listToString();
48 | System.out.println("Removed Head: ");
49 | caller(list, "head");
50 | list.listToString();
51 | System.out.println("Removed Tail: ");
52 | caller(list, "tail");
53 | list.listToString();
54 | int data = 9;
55 | System.out.println("Removing desired: " + data);
56 | removeCaller(list, data);
57 | list.listToString();
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/99-answerKey/general/dec/properGrammer.java:
--------------------------------------------------------------------------------
1 |
2 | class properGrammer {
3 |
4 | static public void rollcall(String[] names) {
5 | if(names.length < 2)
6 | {
7 | System.out.println(names[0]);
8 | }
9 | int len = names.length; //4
10 | int lastname = len - 1; //3
11 | String rollcalling = names[0];
12 | for(int i = 1; i < len; i++) {
13 | if(lastname == i) {
14 | rollcalling = rollcalling + ", and " + names[i];
15 | }
16 | else{
17 | rollcalling = rollcalling + ", " + names[i];
18 | }
19 | }
20 | System.out.println(rollcalling);
21 | }
22 |
23 | static public void summation(String[] names, int limit){
24 | int len = names.length;
25 | int leftovers = len - limit;
26 | String rollcall = names[0];
27 | for(int i = 1; i < limit; i++) {
28 | if(i==1 && i+1== limit) {
29 | rollcall = rollcall + " and " + names[i];
30 | }
31 | else if(limit-1 == i && leftovers == 0) {
32 | rollcall = rollcall + ", and " + names[i];
33 | }
34 | else{
35 | rollcall = rollcall + ", " + names[i];
36 | }
37 | }
38 | if(leftovers != 0){
39 | rollcall = rollcall + ", and " + leftovers + " more";
40 | System.out.println(rollcall);
41 | }
42 | else{
43 | System.out.println(rollcall);
44 | }
45 |
46 | }
47 |
48 |
49 |
50 | public static void main(String[] args) {
51 | rollcall(new String[]{"John", "Steven", "Adam", "Computer", "Nancy", "Jeb", "Apple"});
52 | summation(new String[]{"John", "Steven", "Adam", "Computer", "Nancy", "Jeb", "Apple"}, 1);
53 | }
54 | }
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch1-Arrays-Strings/6-matrixtranspose/matrixtranspose.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by christian on 5/15/16.
3 | */
4 |
5 | import java.util.*;
6 |
7 | public class matrixtranspose {
8 |
9 | //Has to be NxN matrix
10 | //Needs to be improved as of now too slow: O(N^2)
11 | public static void turn90(int[][] img)
12 | {
13 | // System.out.println("Before being flipped:\n" + Arrays.deepToString(img));
14 | if(img.length == 1 || img.length != img[0].length)
15 | {
16 | System.out.println("Invalid matrix");
17 | return;
18 | }
19 | int length = img.length, i;
20 | int[] inverter = new int[length*length];
21 | int count = 0;
22 | for( i = 0; i < length; i++)
23 | {
24 | for(int j = length - 1; j >= 0; j--)
25 | {
26 | inverter[count] = img[j][i];
27 | count++;
28 | }
29 | }
30 | System.out.println(Arrays.toString(inverter));
31 | count = 0;
32 | for( i = 0; i < length; i++)
33 | {
34 | for( int j = 0; j < length; j++)
35 | {
36 | img[i][j] = inverter[count];
37 | count++;
38 | }
39 | }
40 |
41 |
42 | // System.out.println("It is flipped 90 degrees:\n" + Arrays.deepToString(img));
43 |
44 | }
45 |
46 | public static void main(String[] a)
47 | {
48 | turn90( new int[][]{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}} );
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/99-answerKey/interviewcake/appleStocks/appleStocks.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | class appleStocks{
3 |
4 | //stockPrice[i = minutes]
5 | //Want best return
6 | // stock_prices_yesterday = [10, 7, 5, 8, 11, 9]
7 | //buy at minute 5 and sell at 11 => Profit 6
8 |
9 | public static int profit(int[] stocks)
10 | {
11 | int len = stocks.length;
12 | int stopper = len -1;
13 | boolean[] track = new boolean[stopper];
14 | int mindex = stopper;
15 | Arrays.fill(track, true);
16 |
17 | int min = (int)Integer.MAX_VALUE;
18 | int i;
19 | int max = (int)Integer.MIN_VALUE;
20 | int payoff = 0;
21 | int potPayoff;
22 | boolean tripped = true;
23 | while(tripped)
24 | {
25 | tripped = false;
26 | for( i = 0; i <= stopper; i++)
27 | {
28 | if(stocks[i] < min && track[i])
29 | {
30 | min = stocks[i];
31 | mindex = i;
32 | }
33 | }
34 | if(mindex+1 != len){
35 | for( i = mindex; i <= stopper; i++)
36 | {
37 | if(stocks[i] > max)
38 | {
39 | track[mindex] = false;
40 | max = stocks[i];
41 | tripped = true;
42 | }
43 | }
44 | }//check if in scope
45 | potPayoff = max - min;
46 | if(payoff < potPayoff)
47 | {
48 | payoff = potPayoff;
49 | }
50 | min = (int)Integer.MAX_VALUE; //reset min so it can be reset
51 | //don't need to reset max
52 | }//while
53 | return payoff;
54 | }
55 |
56 | public static void main(String[] args)
57 | {
58 | System.out.println(profit(new int[]{4, 211, 0, 3, 1118, 10, 19}));
59 | profit(new int[]{1, 21, 0, 15, 8, 10, 19});
60 | }
61 | }
62 |
63 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch1-arrays-and-strings/6-string_compression/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class Solution {
4 |
5 | //BAD NOT ORDERED!!!!!
6 | public static String hashCompression(String str){
7 | //NOT ORDERED!!!!!
8 | Map map = new HashMap<>();
9 |
10 | for(Character c : str.toCharArray()){
11 | if(map.containsKey(c)){
12 | map.put(c, map.get(c)+1);
13 | } else{
14 | map.put(c, 1);
15 | }
16 | }
17 | StringBuilder cmprsd = new StringBuilder();
18 | for(Map.Entry entry : map.entrySet()) {
19 | //cmprsd.append();
20 | }
21 |
22 | return "";
23 | }
24 |
25 | public static String compression(String str) {
26 | char prev = str.charAt(0);
27 | int count = 1;
28 | StringBuilder cmprsd = new StringBuilder();
29 | int len = str.length();
30 | for(int i = 1; i < len; i++) {
31 | if(prev == str.charAt(i)) {
32 | count++;
33 | if(i + 1 == len) {
34 | cmprsd.append(prev);
35 | cmprsd.append(count);
36 | }
37 | } else {
38 | cmprsd.append(prev);
39 | cmprsd.append(count);
40 | prev = str.charAt(i);
41 | count = 1;
42 | }
43 | }
44 | String candidate = cmprsd.toString();
45 | return (len > candidate.length()) ? candidate : str;
46 | }
47 |
48 | public static void main(String[] args) {
49 | System.out.println(compression("aabbcc"));
50 | System.out.println(compression("abc"));
51 | System.out.println(compression("aaaaaaaaaaaabc"));
52 | }
53 | }
--------------------------------------------------------------------------------
/99-answerKey/genericFrequent/repeatingWords/repeatingWords.java:
--------------------------------------------------------------------------------
1 | package SideLines.Palindromes; /**
2 | * Created by christian on 5/15/16.
3 | */
4 | import java.util.*;
5 | public class repeatingWords {
6 | //which words repeat in the given string
7 | //if it has it already then add key again, with current value + 1
8 | public static String wordRepeats(String sentence)
9 | {
10 | Map repeat = new HashMap<>();
11 | int length = sentence.length();
12 | if(length == 0){return repeat.toString();}
13 | String[] allWords =sentence.split(" ");
14 | length = allWords.length;
15 | for(int i = 0; i < length; i++)
16 | {
17 | String word = allWords[i];
18 | if( repeat.containsKey(word) )
19 | {
20 | repeat.put(word, repeat.get(word) + 1);
21 | }
22 | else
23 | repeat.put(word, 1);
24 | }
25 |
26 |
27 | return repeat.toString();
28 | }
29 |
30 | public static void main(String[] args)
31 | {
32 | String sentence = "The man went to the store" +
33 | "and he bought bread and then he bought " +
34 | "some apples; boy was he a rich man! After that, he" +
35 | "left and went on the road. He headed to his house and " +
36 | ",but before entering his garage, he noticed that his car" +
37 | "was a horse. Not only that, but he realized he wasn't a man, " +
38 | "in fact, he was a camel. ";
39 | System.out.println(wordRepeats(sentence));
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/99-answerKey/project-Euler/2-largest-Product-drome/largestProductdrome.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class largestProductdrome {
4 |
5 | private static int loopthroghthem() {
6 | int i,j;
7 | int yourdrome = 0;
8 | for(i = 100; i < 1000; i++){
9 | for(j = 100; j < 1000; j++){
10 | if(theRealDrome(i, j)){
11 | if((i*j) > yourdrome){
12 | yourdrome = i*j;
13 | }
14 | }
15 | }
16 | }
17 | return yourdrome;
18 | }
19 |
20 |
21 | private static boolean theRealDrome(int outer, int inner)
22 | {
23 | int potenialDrome = outer*inner;
24 | String[] drome = (((Integer)potenialDrome).toString()).split("");
25 | int len = drome.length - 1;
26 | int i;
27 | for(i = 0; i <= len/2; i++)
28 | {
29 | if(! drome[i].equals(drome[len-i]) )
30 | {
31 | return false;
32 | }
33 | }
34 | return true;
35 | }
36 |
37 | private static boolean oldDrome(int i, int j) {
38 | int potentialdrome = i * j;
39 | String maybes = Integer.toString(potentialdrome);
40 | int length = maybes.length();
41 | int o, p = 0;
42 | for(o = 0, p = length - 1; o < length/2; o++, p--){
43 | String front = maybes.substring(o, o+1);
44 | String back;
45 | if(p == length - 1){
46 | back = maybes.substring(p);
47 | }
48 | else
49 | {
50 | back = maybes.substring(p, p+1);
51 | }
52 | if(front.compareTo(back) != 0){
53 | return false;
54 | }
55 | }
56 | return true;
57 | }
58 |
59 | public static void main (String args[])
60 | {
61 | int holder = loopthroghthem();
62 | System.out.println(holder);
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch3-Stacks_n_Queues/4-QueueAs2Stacks/MyQueue.java:
--------------------------------------------------------------------------------
1 | /*
2 | NOTE: Only transfer when user requests peek() or poll()
3 | ONLY transfer if pseudo_queue is empty.
4 | If it's not empty, then we still have elements ahead of our newer
5 | */
6 | import java.util.*;
7 |
8 | /*
9 | Hide the fact that they are stacks => use poll() & add() naming
10 | */
11 | class MyQueue {
12 |
13 | Deque stack;
14 | // constrained to push() & pop()
15 | Deque pseudo_queue;
16 | public MyQueue() {
17 | stack = new ArrayDeque<>();
18 | pseudo_queue = new ArrayDeque<>();
19 | }
20 |
21 | /*
22 | only relevant to stack
23 | */
24 | public void add(int data) {
25 | stack.push(data);
26 | }
27 |
28 | public void shiftToQueue(){
29 | //only shift if pseudo_queue is empty
30 | //else you will be pushing newer elements on top of the old
31 | //already stored!
32 | if(pseudo_queue.isEmpty()) {
33 | //pop all our elements from our stack into our queue
34 | //we should result with queue ordering in our stack
35 | while(!stack.isEmpty()) {
36 | pseudo_queue.push(stack.pop());
37 | }
38 | }
39 | }
40 |
41 | //we want the oldest element not the newest!
42 | public int poll(){
43 | shiftToQueue();
44 | return pseudo_queue.pop(); //the head of or pseudo
45 | }
46 |
47 | public int peek(){
48 | shiftToQueue();
49 | //remember peek() is same for both,
50 | // except we are manipulating the head in stacks,
51 | // while maintaing our original head in queue
52 | return pseudo_queue.peek();
53 | }
54 |
55 | }
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch2-Linked_list/1-remove_dups/Solution.java:
--------------------------------------------------------------------------------
1 | /*
2 | EASY: REAL PROBLEM IS WITHOUT A BUFFER
3 | */
4 | import java.util.*;
5 |
6 | class Solution {
7 |
8 |
9 | public static Node removedDuplicates(Node head) {
10 |
11 | Set seen = new HashSet<>(); //buffer
12 | Node ptr = head;
13 | seen.add(ptr.data);
14 |
15 | while(ptr != null) {
16 | if(ptr.next != null) {
17 | if(seen.contains(ptr.next.data)){
18 | System.out.println("=>" + ptr.next.data);
19 | ptr.next = ptr.next.next; //point to the one after it
20 | ptr.next.next = null; //drop the node
21 | } else {
22 | //just move on to next node
23 | seen.add(ptr.next.data);
24 | ptr = ptr.next;
25 |
26 | }
27 | } else {
28 | ptr = ptr.next;
29 | }
30 | }
31 | checkit(head);
32 | return null;
33 | }
34 |
35 | public static void checkit(Node head){
36 | Node ptr = head;
37 | while(ptr != null) {
38 | System.out.println(ptr.data);
39 | ptr = ptr.next;
40 | }
41 | }
42 |
43 | public static void main(String[] args) {
44 | Node head = new Node(2);
45 | Node ptr = head;
46 | //dupes = 1, 4, 5, 2
47 |
48 | for(int i: new int[]{1, 1, 3, 4, 5, 1, 4, 2, 5}){
49 | ptr.next = new Node(i);
50 | ptr = ptr.next;
51 | }
52 | //final form = 2, 1, 3, 4, 5
53 | //checkit(head);
54 | removedDuplicates(head);
55 | }
56 | }
57 |
58 | class Node {
59 | Node next;
60 | int data;
61 | public Node(int data){
62 | this.data = data;
63 | }
64 |
65 | }
--------------------------------------------------------------------------------
/99-answerKey/algorithms/sorting/comparison-based/README.md:
--------------------------------------------------------------------------------
1 | #Sorting Algorithms
2 | The following sorting algorithms will be implemented
3 |
4 | -
5 | Selection, Bubble, Insertion, Merge, Quick, Intro Sort, Timsort
6 |
7 | -
8 | O(1) < O(log(n)) < O(n) < O(n*log(n)) < O(n2) < O(2n) < O(n!)
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | | Sorting Algorithm |
17 | Best Case |
18 | Worst Case |
19 | Space Complexity |
20 |
21 |
22 |
23 |
24 |
25 |
26 | | Selection Sort |
27 | O(n2) |
28 | O(n2) |
29 | |
30 |
31 |
32 |
33 | | Bubble Sort |
34 | O(n) |
35 | O(n2) |
36 | |
37 |
38 |
39 |
40 | | Insertion Sort |
41 | O(n) |
42 | O(n2) |
43 | |
44 |
45 |
46 |
47 |
48 | | Merge Sort |
49 | O(n*log(n)) |
50 | O(n*log(n)) |
51 | |
52 |
53 |
54 |
55 |
56 | | Quick Sort |
57 | O(n*log(n)) |
58 | O(n2) |
59 | |
60 |
61 |
62 |
63 | | Intro Sort |
64 | O(n*log(n)) |
65 | O(n*log(n)) |
66 | |
67 |
68 |
69 |
70 | | Timsort |
71 | O(n) |
72 | O(n*log(n)) |
73 | |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/38|countNsay/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | class Solution {
3 |
4 |
5 | public static String countAndSay(int n){
6 | String count = "1";
7 | String say = Integer.parseInt(count) + count;
8 | String total = say;
9 | boolean wire = true;
10 | int me =1;
11 | int saying = 1;
12 | while(me!=n){
13 | for(int i = 0; i < total.length(); i=i){
14 |
15 | for(int j = i+1; j 1 || prev.length()+1 == prev.length()) {
50 | say = Integer.toString(count) + prev.charAt(i);
51 | }
52 | } else{
53 | count++;
54 | }
55 | }
56 | want++;
57 | }
58 | return prev;
59 | }
60 |
61 | public static void main(String[] args){
62 | countAndSay(3);
63 | countAndSay(4);
64 | }
65 | }
--------------------------------------------------------------------------------
/2-Data-Structures/LinkedLists/CircularLinked/CircularLinkedList.java:
--------------------------------------------------------------------------------
1 | package CircularLinkedList;
2 |
3 | import linkedlists.AbstractLinkedList;
4 |
5 | public class CircularLinkedList extends AbstractLinkedList
6 | {
7 | private int size;
8 | private Node head;
9 | private Node tail;
10 |
11 | public CircularLinkedList()
12 | {
13 | size = 0;
14 | head = null;
15 | tail = null;
16 | }
17 | @Override
18 | public void putNode(int data) {
19 | // TODO Auto-generated method stub
20 |
21 | }
22 | @Override
23 | public void newHead(SinglyLinkedList.Node head) {
24 | // TODO Auto-generated method stub
25 |
26 | }
27 | @Override
28 | public void putMultiNodes(int[] nodes) {
29 | // TODO Auto-generated method stub
30 |
31 | }
32 | @Override
33 | public SinglyLinkedList.Node removeHead() throws Exception {
34 | // TODO Auto-generated method stub
35 | return null;
36 | }
37 | @Override
38 | public SinglyLinkedList.Node removeTail() {
39 | // TODO Auto-generated method stub
40 | return null;
41 | }
42 | @Override
43 | public SinglyLinkedList.Node deleteNode(int data) {
44 | // TODO Auto-generated method stub
45 | return null;
46 | }
47 | @Override
48 | public void autoLinkedList(int size) {
49 | // TODO Auto-generated method stub
50 |
51 | }
52 | @Override
53 | public int getSize() {
54 | // TODO Auto-generated method stub
55 | return 0;
56 | }
57 | @Override
58 | public SinglyLinkedList.Node getHead() {
59 | // TODO Auto-generated method stub
60 | return null;
61 | }
62 | @Override
63 | public void listToString() {
64 | // TODO Auto-generated method stub
65 |
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/99-answerKey/data-structures/Linked-List/CircularLinked/CircularLinkedList.java:
--------------------------------------------------------------------------------
1 | package CircularLinkedList;
2 |
3 | import linkedlists.AbstractLinkedList;
4 |
5 | public class CircularLinkedList extends AbstractLinkedList
6 | {
7 | private int size;
8 | private Node head;
9 | private Node tail;
10 |
11 | public CircularLinkedList()
12 | {
13 | size = 0;
14 | head = null;
15 | tail = null;
16 | }
17 | @Override
18 | public void putNode(int data) {
19 | // TODO Auto-generated method stub
20 |
21 | }
22 | @Override
23 | public void newHead(SinglyLinkedList.Node head) {
24 | // TODO Auto-generated method stub
25 |
26 | }
27 | @Override
28 | public void putMultiNodes(int[] nodes) {
29 | // TODO Auto-generated method stub
30 |
31 | }
32 | @Override
33 | public SinglyLinkedList.Node removeHead() throws Exception {
34 | // TODO Auto-generated method stub
35 | return null;
36 | }
37 | @Override
38 | public SinglyLinkedList.Node removeTail() {
39 | // TODO Auto-generated method stub
40 | return null;
41 | }
42 | @Override
43 | public SinglyLinkedList.Node deleteNode(int data) {
44 | // TODO Auto-generated method stub
45 | return null;
46 | }
47 | @Override
48 | public void autoLinkedList(int size) {
49 | // TODO Auto-generated method stub
50 |
51 | }
52 | @Override
53 | public int getSize() {
54 | // TODO Auto-generated method stub
55 | return 0;
56 | }
57 | @Override
58 | public SinglyLinkedList.Node getHead() {
59 | // TODO Auto-generated method stub
60 | return null;
61 | }
62 | @Override
63 | public void listToString() {
64 | // TODO Auto-generated method stub
65 |
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch4-Trees&Graphs/1-RouteBetweenNodes/Graph.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | /*Given: Direct Graph. Design an algorithm to find out if a route exists!**/
3 |
4 |
5 |
6 | class Graph {
7 |
8 | Map edges;
9 | public Graph(){
10 | edges = new HashMap<>();
11 | }
12 | public void insertEdge(String source, String target){
13 | if(edges.containsKey(source)){
14 | edges.get(source).insertTarget(new Node(target));
15 | } else {
16 | Node node = new Node(source);
17 | edges.put(source, node);
18 | edges.get(source).insertTarget(new Node(target));
19 | }
20 | }
21 | class Node{
22 | String node;
23 | List targets;
24 | public Node(String node){
25 | targets = new ArrayList<>();
26 | this.node = node;
27 | }
28 | public void insertTarget(Node x){
29 | targets.add(x);
30 | }
31 | }
32 |
33 |
34 | public boolean pathExists(String source, String target) {
35 | Set visted = new HashSet<>();
36 | Deque path = new ArrayDeque<>();
37 | Map parentChild = new HashMap<>();
38 | path.push(source);
39 | while(!path.isEmpty()){
40 | String node = path.poll();
41 | if(node == target){
42 | return true;
43 | }
44 | if(!visted.contains(node) && edges.containsKey(node)){
45 | visted.add(node);
46 | Node objNode = edges.get(node);
47 | if(objNode.targets.size() > 0){
48 | for(Node targets:objNode.targets){
49 | path.push(targets.node);
50 | parentChild.put(node, targets.node);
51 | }
52 | }
53 | }
54 | }
55 | return false;
56 | }
57 |
58 | }
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch1-arrays-and-strings/5-one_away/Solution.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Solution {
4 |
5 | public static boolean addOne(String one, String two){
6 | int j = 0;
7 | int diffs = 0;
8 | for(int i = 0; i < one.length(); i++) {
9 | //could be appended at the very end
10 | if(two.length() -1 < i || one.charAt(i) != two.charAt(j)) {
11 | diffs++;
12 | if(diffs > 1) return false;
13 | } else {
14 | j++;
15 | }
16 | }
17 | return true;
18 | }
19 |
20 | public static boolean changeOne(String one, String two) {
21 | int diffs = 0;
22 | for(int i = 0; i < one.length(); i++) {
23 | if(one.charAt(i) != two.charAt(i)) {
24 | diffs++;
25 | if(diffs > 1) return false;
26 | }
27 | }
28 | return true;
29 | }
30 |
31 | public static boolean oneAway(String one, String two){
32 | int diff = one.length() - two.length();
33 | System.out.println(diff);
34 | if(diff == -1 || diff == 1) {
35 | if(one.length() > two.length()){
36 | return addOne(one, two);
37 | } else {
38 | return addOne(two, one);
39 | }
40 | }
41 | else if(diff == 0) {
42 | return changeOne(one, two);
43 | } else {
44 | return false;
45 | }
46 | }
47 | public static void main(String[] args) {
48 | System.out.println("True ==>" + oneAway("change", "changer"));
49 | System.out.println("True ==>" +oneAway("changer", "change"));
50 | System.out.println("True ==>" +oneAway("ahange", "change"));
51 | System.out.println("False ==>" +oneAway("ssahange", "change"));
52 | System.out.println("False ==>" +oneAway("chanr", "change"));
53 | }
54 | }
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch2-Linked_list/implementations/Demo.java:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Demo {
4 |
5 |
6 |
7 | public static Node doublyDeleteNode(Node head, int val) {
8 | if(head.data == val) {
9 | head = head.next;
10 | head.prev = null;
11 | return head;
12 | }
13 | Node n = head;
14 | n = n.next;
15 | while(n != null) {
16 | if(n.data == val) {
17 | n.prev.next = n.next;
18 | if(n.next != null)
19 | n.next.prev = n.prev;
20 | n.next = null;
21 | n.prev = null;
22 | return head;
23 | }
24 | System.out.println("NOPE: " + n.data);
25 | n = n.next;
26 | }
27 | return head;
28 | }
29 |
30 | public static void main(String[] args) {
31 | Node node = new Node(10);
32 | node.prev = null;
33 | Node n = node;
34 | for(int i : new int[]{11, 12, 13, 14, 15, 16, 17}){
35 | n.next = new Node(i);
36 | n.next.prev = n;
37 | n = n.next;
38 | }
39 | System.out.println(n.data);
40 | n.next = null;
41 | System.out.println(n.data);
42 | n = node;
43 | n = doublyDeleteNode(n, 10);
44 | // n = node;
45 | System.out.println();
46 | System.out.println(n.data);
47 | while(n.next != null) {
48 | if(n.prev == null) {
49 | System.out.println( "null" + " = >" + n.data + " => " + n.next.data + " => ");
50 | }
51 | else {
52 | System.out.println( n.prev.data + " <= >" +n.data+ " <=>" + n.next.data + " => ");
53 | }
54 | n = n.next;
55 | }
56 | }
57 |
58 | }
59 |
60 |
61 | class Node {
62 | int data;
63 | Node next;
64 | Node prev;
65 |
66 | public Node(int data) {
67 | this.data = data;
68 | }
69 |
70 | }
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch2-Linked_list/implementations/DoublyLinkedList.java:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | class DoublyLinkedList {
5 |
6 |
7 |
8 | public static Node removeNode(Node head, int val) {
9 | if(head.data == val) {
10 | head = head.next;
11 | head.prev = null;
12 | return head;
13 | }
14 | Node ptr = head;
15 | ptr = ptr.next;
16 | while(ptr != null) {
17 | if(ptr.data == val) {
18 | ptr.next.prev = ptr.prev; //these are actual nodes
19 | ptr.prev.next = ptr.next; //these are actual nodes
20 |
21 | ptr.next = null; //what i point to
22 | ptr.prev = null; //what i point to
23 | return head;
24 | }
25 | ptr = ptr.next;
26 | }
27 | return head;
28 | }
29 |
30 | public static Node makeDLL(int size) {
31 | Node node = new Node(0);
32 | node.prev = null;
33 | Node n = node;
34 | for(int i = 1; i < size; i++){
35 | n.next = new Node(i);
36 | n.next.prev = n;
37 | n = n.next;
38 | }
39 | n.next = null;
40 | return node;
41 | }
42 |
43 | public static void main(String[] args) {
44 | Node head = makeDLL(10);
45 | Node ptr = removeNode(head, 8);
46 | while(ptr != null) {
47 | if(ptr.prev == null)
48 | System.out.println("NULL" + "<=>" + ptr.data + "<=>" + ptr.next.data);
49 | else
50 | if(ptr.next != null) System.out.println(ptr.prev.data + "<=>" + ptr.data + "<=>" + ptr.next.data);
51 | else System.out.println(ptr.prev.data + "<=>" + ptr.data);
52 | ptr = ptr.next;
53 | }
54 | }
55 | }
56 |
57 | class Node {
58 | int data;
59 | Node next;
60 | Node prev;
61 | public Node(int data) {
62 | this.data = data;
63 | }
64 | }
--------------------------------------------------------------------------------
/2-Data-Structures/wordladder/pathAttempt.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | class pathAttempt{
3 |
4 | public int pathLength(String beingWord, String endWord, Set wordList)
5 | {
6 | if(beingWord.length() != endWord.length()) {return -1;}
7 | wordList.add(endWord);
8 | WordLadder firstPath = new WordLadder(beingWord, 1);
9 | Queue pathsqueue = new ArrayDeque<>();
10 | pathsqueue.add(firstPath);
11 | while(!pathsqueue.isEmpty())
12 | {
13 | WordLadder currPath = pathsqueue.remove();
14 | String pathEndsHere = currPath.atWord;
15 | int pathLength = currPath.pathLength;
16 | if(pathEndsHere.equals(endWord)){return pathLength;}
17 | Iterator it = wordList.iterator();
18 | while(it.hasNext())
19 | {
20 | String myWord = it.next(); //it.next() don't make repeated calls
21 | if(diffByOne(pathEndsHere, myWord))
22 | {
23 | //make new path
24 | pathsqueue.add(new WordLadder(myWord, pathLength+1));
25 | it.remove();
26 | }//if()
27 | }//while()
28 | }//while()
29 | return -1;
30 | }
31 |
32 | public boolean diffByOne(String wordAt, String branchTo)
33 | {
34 | int diffs = 0;
35 | for(int i = 0; i < wordAt.length(); i++)
36 | {
37 | if( !(wordAt.charAt(i) == branchTo.charAt(i) ) )
38 | {
39 | diffs++;
40 | if(diffs > 1){return false;}
41 | }
42 | }
43 | return true;
44 | }
45 |
46 | }
47 |
48 | class WordLadder{
49 | String atWord;
50 | int pathLength;
51 | public WordLadder(String atWord, int pathLength)
52 | {
53 | this.atWord = atWord;
54 | this.pathLength = pathLength;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/8-Architecture/README.md:
--------------------------------------------------------------------------------
1 | #Architecture
2 |
3 |
4 | | 8. Architecture |
5 | Explain |
6 |
7 |
8 |
9 |
10 | | Backend Architecture |
11 |
12 | Scaling:
13 | Buy commodity hardware. Using cloud storage to expand.
14 | Web Servers:
15 | Apache, lightHTTP, nginx => These all require httpd.conf. Simpler things like max connections
16 | , worker MPM, usually unconfig'd
17 | Languages: Languages aren't meant to scale for you. Use bytecode caches (PHP, Python, etc).
18 | Databases: Slow, partition datat into shards and tune database.
19 | The above : A good example of the architecture above would be a LAMP stack.
20 | |
21 |
22 |
23 |
24 | | Questions |
25 |
26 |
27 | How do you scale easily? :
28 | - Use caches
29 | - Disk based caching [cache-lite via php pear] RAM disks on SSDs.
30 | - In-memory caching (APC memcached). .
31 | - Cloud-based caching.
32 |
33 |
34 |
35 | Why memcache :
36 | - Fast over networks
37 | - Scales, failover, wide support
38 | - Centralized/shared across site .
39 |
40 |
41 |
42 | S3:
43 | - Databases are bad for blob storage.
44 | - Databases are good for relational data.
45 | - S3 = file and data storage that runs over HTTP.
46 | - Centralized and shared across site.
47 |
48 | |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch2-Linked_list/6-IsPalindrome/StackMid.java:
--------------------------------------------------------------------------------
1 | /*
2 | Space complexity: O(N/2) [uses stack to store first half]
3 | Run time: O(N) [traverse entire LL]
4 | */
5 |
6 | import java.util.*;
7 |
8 | class StackMid {
9 |
10 |
11 | /*
12 | Need to be considerate about even lengths
13 | */
14 | public static boolean isPalindrome(Node head) {
15 | Deque stack = new ArrayDeque<>();
16 |
17 | //start at head for both
18 | Node ptr = head;
19 | Node runner = head;
20 | //we jump by 2's so make sure we have a .next ref something!
21 | while(runner!=null && runner.next != null) {
22 | stack.push(ptr.data);
23 | ptr = ptr.next;
24 | runner = runner.next.next;
25 | }
26 |
27 | //an odd LL will have runner end on non null (runner.next == null)
28 | //that means ptr will be on the mid point (we don't care for that)
29 | if(runner != null) {
30 | ptr = ptr.next; //skip midpoint since we start our comparison on the latter half
31 | }
32 |
33 | //now pop from the list and run through the rest of the list!
34 |
35 | while(ptr != null) {
36 | if(stack.pop() != ptr.data) {
37 | return false;
38 | }
39 | ptr = ptr.next;
40 | }
41 |
42 | return true;
43 | }
44 |
45 | public static void main(String[] args) {
46 | Node head = new Node(1);
47 | Node ptr = head;
48 | int[] pair = new int[]{0, 0, 1, 0, 0, 1}; //true
49 | //int[] pair = new int[]{0, 0, 1, 0, 0, 0}; //false
50 | for(int i : pair) {
51 | ptr.next = new Node(i);
52 | ptr = ptr.next;
53 | }
54 |
55 | ptr = head;
56 | System.out.println("1011001 is not palindrome => " + isPalindrome(ptr));
57 | }
58 | }
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch2-Linked_list/8-LoopDetection/Solution.java:
--------------------------------------------------------------------------------
1 | /*
2 | Runner Technique
3 | Reference Equality
4 |
5 | */
6 |
7 | class Solution {
8 |
9 |
10 | public static Node getLoopHead(Node head) {
11 | Node runner = head;
12 | Node ptr = head;
13 |
14 | //they will eventually clash
15 | //they clash at K nodes away from the head of the loop!
16 | //where K = size of the LL that isn't part of the cycle
17 | //IOW, head of LL is also K distance from head of loop.
18 | while(runner != null && runner.next != null) {
19 | runner = runner.next.next;
20 | ptr = ptr.next;
21 | if(runner == ptr) {
22 | break;
23 | }
24 | }
25 | //this LL doesn't have a cycle
26 | if(runner == null || runner.next == null) return null;
27 |
28 | //move one pointer to the head
29 | //remember: head is also K nodes from the head of the loop.
30 | ptr = head;
31 | while(ptr != runner) {
32 | ptr = ptr.next;
33 | runner = runner.next;
34 | }
35 |
36 | return runner;
37 | }
38 |
39 | public static void main(String[] args) {
40 | //save ref to third node!
41 | Node head = new Node(0);
42 | Node ptr = head;
43 | Node cycleHead = null;
44 | for(int i : new int[]{1, 2, 3, 4, 5, 6}){
45 | Node container = new Node(i);
46 | ptr.next = container;
47 | if(i == 3) {
48 | cycleHead = container;
49 | }
50 | ptr = ptr.next;
51 | }
52 | ptr.next = cycleHead;
53 | ptr = head;
54 | System.out.println("HEAD OF LOOP IS THREE: => " + getLoopHead(ptr).data);
55 | }
56 | }
57 |
58 |
59 |
60 | class Node {
61 | int data;
62 | Node next;
63 |
64 | public Node(int data) {
65 | this.data = data;
66 | }
67 | }
--------------------------------------------------------------------------------
/99-answerKey/algorithms/sorting/comparison-based/Heap-Sort/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 |
3 |
4 | public static void heapsort(int[] arr){
5 | //make it into a heap!
6 | int len = arr.length;
7 | if(len <= 1){
8 | return;
9 | }
10 | int mid = len/2-1;
11 | //start at the rightmost node with a child!
12 | //bottom-up
13 | for(int i = mid; i >= 0; i--){
14 | heapit(arr, i, len);
15 | }
16 | System.out.println(java.util.Arrays.toString(arr));
17 | //have a maxHeap now! Now sort it!
18 | //We start at the rightmost leaf!
19 | for(int i = len-1; i >= 0; i--){
20 | //swap with root => sink [sunk=> permenantely there]
21 | swap(arr, i, 0);
22 | //then swim the new root down until we are a heap again.
23 | //len should be decreasing per sink => make length = i
24 | heapit(arr, 0, i);
25 | }
26 | System.out.println(java.util.Arrays.toString(arr));
27 | }
28 |
29 |
30 | public static void heapit(int[] arr, int parent, int len){
31 | int newParent = parent;//could change
32 | int leftChild = parent*2 + 1;
33 | int rightChidl = parent*2+2;
34 | if(leftChild arr[newParent]){
35 | newParent=leftChild;//do LC and Parent follow maxHeap rules?
36 | }
37 | if(rightChidlarr[newParent]){
38 | newParent=rightChidl;//is parent still the greatest of the 3?
39 | }
40 | if(newParent!=parent){
41 | //swap!
42 | swap(arr, newParent, parent);
43 | //is it in it's final position?
44 | heapit(arr, newParent, len);
45 | }
46 | }
47 |
48 | public static void swap(int[] arr, int a, int b){
49 | int temp = arr[a];
50 | arr[a]=arr[b];
51 | arr[b]=temp;
52 | }
53 |
54 |
55 |
56 |
57 | public static void main(String[] args){
58 | heapsort(new int[]{4, 3, 2, 8, 10, 11});
59 | }
60 | }
--------------------------------------------------------------------------------
/99-answerKey/algorithms/sorting/comparison-based/quicksort/quicksort.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class quicksort{
4 |
5 |
6 | public void sort(int[] arr, int beg, int end)
7 | {
8 | if(end <= beg){return;} //base case
9 |
10 | int pivot = partition(arr, beg, end); //the pivot is in final position; nothing else
11 | sort(arr, beg, pivot - 1); //sort left half
12 | sort(arr, pivot + 1, end); //sort right half
13 | }
14 |
15 | public int partition(int[] arr, int beg, int end)
16 | {
17 |
18 | int left = beg;
19 | int right = end;
20 | int pivot = arr[(beg+end)/2];
21 | int pivotIndex;
22 | while(right > left)
23 | {
24 | while(arr[right] > pivot)//will be on the right
25 | { //stay there already in greater position
26 | right--;
27 | }
28 | while(arr[left] < pivot)
29 | { //stay there already in less than position
30 | left++;
31 | }
32 | if(left <= right)
33 | { //have to do = or else never cross
34 | swap(arr, left, right);
35 | left++;
36 | right--;
37 | }
38 |
39 | }
40 | /*|LeftPointer|pivot|RightPointer|
41 | ends up as
42 | |RightPointer|pivot|LeftPointer|
43 | **/
44 |
45 | return (pivotIndex = left - 1);
46 | }
47 |
48 | public void swap(int[] arr, int a, int b)
49 | {
50 | int temp = arr[a];
51 | arr[a] = arr[b];
52 | arr[b] = temp;
53 | }
54 |
55 | public static void main(String[] args)
56 | {
57 | quicksort caller = new quicksort();
58 | //non-static hence have to make an instance of the class
59 | int[] unorg = new int[]{2, 3, 5, 1, 0, 4, 3};
60 | caller.sort(unorg, 0, unorg.length-1);
61 | for(int num : unorg)
62 | System.out.println(num);
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch1-Arrays-Strings/B4-dromePerm/dromePerm.java:
--------------------------------------------------------------------------------
1 |
2 | import java.util.*;
3 | public class dromePerm
4 | {
5 | //can a word's permutation be a palindrome
6 | //this cannot read palindromes that include punctuation.
7 | //if one want this, then use the commented out expression
8 | public static void arrangedDrome(String word)
9 | {
10 | if(word == null || word.length() < 2) {return;}
11 | // word = word.replaceAll("[^A-Za-z0-9]", "");
12 | String[] letters = word.toLowerCase().replaceAll(" ", "").split("");
13 | Map map = new HashMap<>();
14 |
15 | for(String aLetter : letters)
16 | {
17 | if(map.containsKey(aLetter))
18 | {
19 | map.put(aLetter, map.get(aLetter) + 1);
20 | }
21 | else
22 | {
23 | map.put(aLetter, 1);
24 | }
25 | }
26 | //now iterate through it and see if it can be palindrome
27 | //def of palindrome: Only 1 instance of odd pairs!
28 | Iterator iter = map.entrySet().iterator();
29 | boolean wire = false;
30 | while(iter.hasNext())
31 | {
32 | Map.Entry paired = (Map.Entry) iter.next();
33 | int value = (int)paired.getValue();
34 | if( (value = value%2) != 0)
35 | {
36 | if(wire)
37 | {
38 | wire = false;
39 | break; //break out of loop {if = a branch}
40 | }
41 | wire = true; //tripped wire
42 | }
43 |
44 | }
45 |
46 | if(wire)
47 | {
48 | System.out.println("this can be a palindrome");
49 | }
50 | else
51 | {
52 | System.out.println("this cannot be a palindrome since it breaks the def.");
53 | }
54 |
55 |
56 | }
57 |
58 | public static void main(String[] args)
59 | {
60 | arrangedDrome("Tact Coa");
61 | arrangedDrome("oe was Ir ere I sasw Eros");
62 | arrangedDrome("Gatename manseesman atgarage sees name g");
63 | arrangedDrome("Not so Boston");
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch3-Stacks_n_Queues/5-SortedStack/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 |
4 | class Solution {
5 |
6 |
7 | public static void main(String[] args) throws Exception{
8 | SortedStack stack = new SortedStack();
9 | stack.add(10);
10 | stack.add(20);
11 | stack.add(3);
12 | stack.add(13);
13 | stack.add(200);
14 | stack.add(15);
15 | System.out.println(stack.sortedStack);
16 | stack.pop();
17 | System.out.println(stack.sortedStack);
18 | System.out.println(stack.peek());
19 | stack.add(1);
20 | System.out.println(stack.sortedStack);
21 | }
22 | }
23 |
24 |
25 | class SortedStack{
26 | Deque sortedStack;
27 | Deque auxStack;
28 |
29 | public SortedStack() {
30 | sortedStack = new ArrayDeque<>();
31 | auxStack = new ArrayDeque<>();
32 | }
33 |
34 |
35 | public void add(int data){
36 | if(sortedStack.isEmpty()){
37 | sortedStack.push(data);
38 | return;
39 | }
40 | boolean inserted = false;
41 | //keep going until you insert
42 | while(!inserted){
43 | //TWO CASES: Inside the stack OR At the end of the stack
44 | if(!sortedStack.isEmpty() && sortedStack.peek() < data) {
45 | //keep going
46 | auxStack.push(sortedStack.pop());
47 | } else {
48 | sortedStack.push(data);
49 | inserted = true;
50 | }
51 | }
52 | //now reinsert all the elements less than data
53 | while(!auxStack.isEmpty()){
54 | sortedStack.push(auxStack.pop());
55 | }
56 | }
57 |
58 | public int pop() throws EmptyException{
59 | if(sortedStack.isEmpty()) throw new EmptyException();
60 | return sortedStack.pop();
61 | }
62 |
63 | public int peek(){
64 | return sortedStack.peek();
65 | }
66 |
67 | }
68 |
69 | class EmptyException extends Exception{
70 |
71 | }
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch1-arrays-and-strings/7-rotation/Question.java:
--------------------------------------------------------------------------------
1 | // import java.util.*;
2 |
3 | // public class Question {
4 |
5 | // public static void printit(int n){
6 | // System.out.println(n);
7 | // }
8 | // public static boolean rotate(int[][] matrix) {
9 | // if (matrix.length == 0 || matrix.length != matrix[0].length) return false; // Not a square
10 | // int n = matrix.length;
11 |
12 | // for (int layer = 0; layer < n / 2; layer++) {
13 | // int first = layer;
14 | // int last = n - 1 - layer;
15 | // for(int i = first; i < last; i++) {
16 | // int offset = i - first;
17 | // int top = matrix[first][i]; // save top
18 | // // left -> top
19 | // matrix[first][i] = matrix[last-offset][first];
20 |
21 | // // bottom -> left
22 | // matrix[last-offset][first] = matrix[last][last - offset];
23 |
24 | // // right -> bottom
25 | // matrix[last][last - offset] = matrix[i][last];
26 |
27 | // // top -> right
28 | // matrix[i][last] = top; // right <- saved top
29 | // }
30 | // }
31 | // return true;
32 | // }
33 |
34 | // public static void main(String[] args) {
35 | // int[][] matrix = new int[3][3];
36 | // matrix[0][0] = 1;
37 | // matrix[0][1] = 2;
38 | // matrix[0][2] = 3;
39 |
40 | // matrix[1][0] = 4;
41 | // matrix[1][1] = 5;
42 | // matrix[1][2] = 6;
43 |
44 | // matrix[2][0] = 7;
45 | // matrix[2][1] = 8;
46 | // matrix[2][2] = 9;
47 | // for(int[] row : matrix) {
48 | // System.out.println(Arrays.toString(row));
49 | // }
50 | // rotate(matrix);
51 | // System.out.println();
52 | // for(int[] row : matrix) {
53 | // System.out.println(Arrays.toString(row));
54 | // }
55 |
56 | // }
57 | // }
58 |
59 |
--------------------------------------------------------------------------------
/99-answerKey/companies/gusto/payments.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | class payments {
4 |
5 |
6 |
7 | public static int[] owes(String[] payments){
8 | Map> map =
9 | new HashMap<>();
10 |
11 | for(String transaction: payments){
12 | //is the person they are paying, already exist
13 |
14 | String[] owes = transaction.replace(" owes ", " ").split(" ");
15 | String a = owes[0];
16 | String b = owes[1];
17 | Integer c = Integer.parseInt(owes[2]);
18 | if(!couldBePaying(b, a, c, map)){
19 | //is owed
20 | //needsPayment(a, b, c, map);
21 | }
22 |
23 |
24 | if(map.containsKey(a)){
25 | //that means possibly there already
26 | if(map.get(a).containsKey(b)){
27 |
28 | }
29 | }
30 | System.out.println(Arrays.toString(owes));
31 | }
32 |
33 |
34 | return null;
35 | }
36 |
37 | public static boolean couldBePaying(String a, String b, Integer isOwed, Map> map){
38 | if(map.containsKey(a)){
39 | //already owed by others
40 | if(map.get(a).containsKey(b)){
41 | //this person owes more on top of recent
42 |
43 | }
44 | }
45 | }
46 |
47 | public static boolean couldBePaying(String a, String b, Integer paying, Map> map){
48 | if(map.containsKey(a)){
49 | if(map.get(a).containsKey(b)){
50 | Integer owes = map.get(a).get(b);
51 | Integer diff = owes - paying;
52 | if(diff == 0){
53 | map.get(a).remove(b);
54 | return true;
55 | } else{
56 | map.get(a).put(b, diff);
57 | return true;
58 | }
59 | }
60 | }
61 | return false;
62 | }
63 |
64 |
65 | public static void main(String[] args){
66 | String[] payments = new String[]{"A owes B 100", "B owes A 100"};
67 | owes(payments);
68 | }
69 | }
--------------------------------------------------------------------------------
/99-answerKey/companies/pin/isSubSeq/Solution.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 |
3 | public static boolean isSubsequenceBAD(String s, String t){
4 | if(s==null || t == null){ return false;}
5 | int slen = s.length();
6 | int tlen = t.length();
7 | int confirmedMatch = 0;
8 | if(tlen < slen){return false; }
9 | int j = 0;
10 | byte[][] table = new byte[slen+1][tlen+1];
11 | //need to 0 row so skip index 0
12 | for(int i = 1; i <= slen; i++){
13 | for( j = 1; j <= tlen; j++){
14 | //if match letter
15 | if(s.charAt(i-1)==t.charAt(j-1)) {
16 | //get the count from diagonal + 1
17 | table[i][j]= (byte)(table[i-1][j-1] + 1);
18 | if(confirmedMatch < i){
19 | confirmedMatch++;
20 | }
21 | }
22 | //don't match letter
23 | else{
24 | table[i][j]= (table[i-1][j] > table[i][j-1]) ? table[i-1][j] : table[i][j-1];
25 | }
26 | }//for j
27 | if(table[i][j-1] != i){
28 | return false;
29 | }
30 | }
31 | return (table[slen][tlen] == slen)? true: false;
32 | }
33 |
34 | //we care for existence of a subsequence not
35 | //length!
36 | public static boolean isSubsequence(String s, String t) {
37 | if(s== null || t== null){return false;}
38 | int slen = s.length();
39 | int tlen = t.length();
40 | if(slen == 0 && (tlen != 0|| tlen==0)){return true;}
41 | if(slen > tlen){return false;}
42 | int count = 0;
43 | for(int i = 0; i < t.length(); i++){
44 | if(s.charAt(count) == t.charAt(i)){
45 | count++;
46 | if(count == slen){return true;}
47 | }
48 | }
49 | return false;
50 | }
51 |
52 | public static void main(String[] args) {
53 | String s = "abc";
54 | String t = "ahbgdc";
55 | //s = new String("ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss");
56 | System.out.println(isSubsequence(s, t));
57 | }
58 | }
--------------------------------------------------------------------------------
/99-answerKey/genericFrequent/groupAnagrams/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.Map;
2 | import java.util.HashMap;
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.ArrayList;
6 |
7 | public class Solution {
8 |
9 | public List> groupAnagrams(String[] strs)
10 | {
11 | Arrays.sort(strs);
12 |
13 | List> gramMaster = new ArrayList<>();
14 | int length = strs.length;
15 |
16 |
17 | if(length < 2)
18 | {
19 | gramMaster.add(Arrays.asList(strs));
20 | return gramMaster;
21 | }
22 | //keyvalue
23 | Map> abcMap = new HashMap>();
24 |
25 |
26 | for(int i = 0; i < length; i++)
27 | {
28 | char[] abc = strs[i].toCharArray();
29 | Arrays.sort(abc);
30 | String candidate = new String(abc);
31 | if(abcMap.containsKey(candidate))
32 | {
33 | //get corresp. AL.add()
34 | abcMap.get(candidate).add(strs[i]);
35 |
36 | }//else make new AL and add sorted string as value
37 | ArrayList unseen = new ArrayList<>();
38 | unseen.add(strs[i]);
39 | abcMap.put(candidate, unseen);
40 | }
41 |
42 | gramMaster.addAll(abcMap.values());
43 | return gramMaster;
44 | }
45 |
46 | /*
47 | public String[] abcSortString(String[] strs)
48 | {
49 | for(int i = 0; i < strs.length; i++)
50 | {
51 | char[] abc = strs[i].toCharArray();
52 | Arrays.sort(abc);
53 | strs[i] = new String(abc);
54 | }
55 | return strs;
56 | }
57 | */
58 |
59 | public static void main(String[] args)
60 | {
61 | compromise caller = new compromise();
62 | String[] test = new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
63 | System.out.println(caller.groupAnagrams(test));
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/2-Data-Structures/Trees/BST.java:
--------------------------------------------------------------------------------
1 | class BST{
2 |
3 | //node is not built in
4 | Node root;
5 |
6 | public BST()
7 | {
8 | root = null;
9 | }
10 |
11 | //declared a what a node is with constructor
12 | public class Node
13 | {
14 | String sortKey;
15 | String data;
16 | Node left, right;
17 |
18 | public Node(String sortKey, String data)
19 | {
20 | this.sortKey = sortKey;
21 | this.data = data;
22 | }
23 | }
24 |
25 | //alphabetical order
26 | public void insert(String data, String sortKey)
27 | {
28 | root = insert(root, data, sortKey);
29 | }
30 |
31 | public Node insert(Node node, String data, String sortKey)
32 | {
33 | if(node == null){return new Node(data, sortKey);}//empty tree
34 |
35 | //node does exist, but now where should our node go?
36 | int abcOrder = sortKey.compareToIgnoreCase(node.sortKey);
37 |
38 | if(abcOrder > 0)
39 | {
40 | node.right = insert(node.right, data, sortKey);
41 | }
42 | else if(abcOrder < 0)
43 | {
44 | node.left = insert(node.left, data, sortKey);
45 | }
46 | // else dumb mistake; you would just return since it's equal
47 | return node;
48 | }
49 |
50 | //key is just how our nodes are filed in our tree
51 | public String findData(String sortKey)
52 | {
53 | return findData(root, sortKey);
54 | }
55 |
56 | public String findData(Node node, String sortKey)
57 | {
58 | if(node == null){return null;} //this sortKey DNE
59 | int abcOrder = sortKey.compareToIgnoreCase(node.sortKey);
60 | if(abcOrder > 0){ return findData(node.right, sortKey);} //node.right = findData(x.right, sortKey);} No you want data not a node
61 | else if(abcOrder < 0){ return findData(node.right, sortKey);}
62 | return node.data;
63 | }
64 | }//BinaryST
65 |
66 |
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch1-Arrays-Strings/2-reverseString/reverseString.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by christian on 5/15/16.
3 | */
4 | import java.util.*;
5 | public class reverseString{
6 |
7 |
8 | /*Chapter 1 Problem 2:
9 | Reverse a string.
10 | Do manually and easy way **/
11 |
12 | public static String reverseString(String forward)
13 | {
14 | StringBuilder reverser = new StringBuilder(forward);
15 | return reverser.reverse().toString();
16 | }
17 |
18 | public static String manReverse(String forward)
19 | {
20 | if(forward == null){ forward = "null";} //return null;
21 | int length = forward.length();
22 | if(length == 0 || length == 1) return forward;
23 | char[] reversed = new char[length];
24 | for(int i = 0; i < length; i++)
25 | {
26 |
27 | }
28 | return " ";
29 | }
30 |
31 | public static void manuallyReverse()
32 | {
33 | String hello = "abcdef";
34 | int length = hello.length();
35 |
36 | for(int i = 0; i < length; i++)
37 | {
38 | String seeforward = hello.substring(1, length - i);
39 | String seebackw = hello.substring(0,1);
40 | String seePasLimit = hello.substring(length-i, length);
41 | System.out.println("0,1 => " + seeforward + "\n1,0 => " + seebackw +
42 | "\n5,6 (index max = 5) => " + seePasLimit);
43 | hello = seeforward + seebackw + seePasLimit;
44 | }
45 | System.out.println(hello);
46 | }
47 |
48 |
49 |
50 | public static void main(String[] args)
51 | {
52 | Scanner input = new Scanner(System.in);
53 | System.out.println("What do you want me to reverse?");
54 | String myString = input.nextLine();
55 | System.out.println(reverseString(myString));
56 | }
57 |
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/11-Infrastructure/README.md:
--------------------------------------------------------------------------------
1 | # Infrastructure
2 |
3 | ## Pandora
4 |
5 | `Languages`: Java
6 | `NoSQL`: redis, memcache
7 | `Big Data`: Hadoop, HDFS, Hive, Spark
8 | `CLI`: Linux
9 | `DB`: PostgresSQL, MySQL
10 | `Testing`: JUnit, Mockito
11 |
12 |
13 | ## Dropbox
14 |
15 | `Languages`: C/C++, Java, Go
16 | `Other`: OS (Internals), Filesystems, databases, compilers, Linux
17 |
18 |
19 | ## Pinterest
20 | `Debug`: wireshark, tshark, tcpdump, dig, curl, openssl, nc, hping, scapy
21 | `CLI`: GNU/Linux
22 |
23 |
24 | ## Uber
25 | `Languages`: Python
26 | `Other`: Multi-master systems, real-time analysis, Puppet
27 | `Storage`: Cassandra, MySQL, Replicated data stores
28 | `Networking`: RPC frameworks, Goolang, Zookeeper, gRPC
29 | `Data`: Analytics, fault detection, business metrics (Hadoop, Spark, Kafka, Samza)
30 | `Performance`: Distributed Systems, tracing, profiling, System performance (Java,C++, Go)
31 | `Compute`: Job Scheduling, containerization (Docker, Mesos, Aurora)
32 | `Know`: When to use hashtable, red-black tree, eye for architecture
33 | `CLI`: Linux (Ubuntu, Aptitude)
34 | `Monitoring`: Nagios, Graphite
35 | `Big Data Analytics`: Hadoop (HDFS, YARN), Hive, Spark, Docker/Mesos, Tez, Presto, Vertica, Apache Impala,
36 | Drill, Google Borg, Google BigQuery, Amazon Redshit, Kubernetes, Mesos, Pinot/Scuba, Storm, Kafka/Flume/Scribe.
37 |
38 |
39 | ## Uber (Self-Driving)
40 | `Languages`:C/C++, Python, PHP
41 | `Other`:Phabricator, ROS, ground robotics systems
42 | `Tools`:V&V, SW/HW release
43 | `Sensing`: LIDAR, radar, or cameras, triaging, isolating, documenting, and tracking issues systematically
44 |
45 |
46 | # Analytics
47 | `Languages`: D3, Angular, HTML/CSS (Visualize)
48 | `Data Infrastructure`: Hadoop, Spark, Storm, Kafka
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/0-Refresher/CTCI/ch2-Linked_list/4-partition/Solution.java:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | class Solution {
5 |
6 |
7 | public static Node partition(Node head, int x) {
8 |
9 |
10 | //two individual linked lists
11 | //can't do dual pointers, since singly ll
12 | Node before = null;
13 | Node after = null;
14 |
15 | while(head != null) {
16 | //save next reference
17 | Node next = head.next;
18 | if(head.data < x) {
19 | //make next point to our head (lost ref to old LL)
20 | head.next = before;
21 | //move our head to newly added node
22 | before = head;
23 | } else {
24 | //same logic
25 | head.next = after;
26 | after = head;
27 | }
28 | head = next;
29 | }
30 |
31 | //merge them (first check if anything to merge)
32 | if(before == null) {
33 | return after;
34 | }
35 |
36 | Node ptr = before;
37 | //you want the pointer right before you hit null
38 | //you are overwritting the null reference
39 | //[] -> [] -> null (stop on the first to last node not on the null)
40 | while(ptr.next != null) {
41 | ptr = ptr.next;
42 | }
43 | //overwrite
44 | ptr.next = after;
45 | return before;
46 | }
47 |
48 | public static void main(String[] args) {
49 | //3, 1, 5, 7, 8, 2, 9, 1
50 | //x = 5
51 | //3, 1, 2, 1, 5, 7, 8, 9
52 | Node head = new Node(3);
53 | Node ptr = head;
54 | for(int i: new int[]{1, 5, 7, 8, 2, 9, 1}){
55 | ptr.next = new Node(i);
56 | ptr = ptr.next;
57 | }
58 | ptr = head;
59 | Node newList = partition(ptr, 5);
60 | //Node ptr = newList;
61 | while(newList != null) {
62 | System.out.println(newList.data);
63 | newList = newList.next;
64 | }
65 |
66 | }
67 |
68 | }
69 |
70 |
71 | class Node {
72 | int data;
73 | Node next;
74 |
75 | public Node(int data){
76 | this.data = data;
77 | }
78 | }
--------------------------------------------------------------------------------
/99-answerKey/CTCI/Ch1-Arrays-Strings/3-permutation-Of-Other/permutationOfOther.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by christian on 5/15/16.
3 | */
4 |
5 | import java.util.*;
6 |
7 | public class permutationOfOther {
8 | /*Chapter 1 Problem 3:
9 | Given two strings, write a method to decide
10 | if one is a permutation of the other.
11 | Q's: Is it case sensitive?
12 | **/
13 |
14 | public static boolean permutationOfOther(String word1, String word2)
15 | {
16 | try{
17 | if(word1.length() != word2.length()) { return false;}
18 | }catch(NullPointerException e)
19 | {
20 | System.out.println("bad input");
21 | return false;
22 | }
23 | word1 = sortThem(word1);
24 | word2 = sortThem(word2);
25 | return word1.equals(word2);
26 | }
27 |
28 | public static String sortThem(String word)
29 | {
30 | char[] seperateIt = word.toCharArray();
31 | Arrays.sort(seperateIt);
32 | return Arrays.toString(seperateIt);
33 | }
34 |
35 | public static void main(String[] args)
36 | {
37 | Scanner input = new Scanner(System.in);
38 | String att = "hello ello";
39 | String[] attt = att.split(" ");
40 |
41 | System.out.println(Arrays.deepToString(attt) + " " + attt.length);
42 | String usr;
43 | System.out.println("Please input two words seperated by a space");
44 |
45 | while( (usr = input.nextLine() ) != null)
46 | {
47 | String[] canidates = usr.split(" ");
48 | if(canidates.length != 2)
49 | {
50 | System.out.println("bad input");
51 | continue;
52 | }
53 | else{
54 | System.out.println(permutationOfOther(canidates[0], canidates[1]));
55 | }
56 |
57 | System.out.println("Please input two words seperated by a space");
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/99-answerKey/genericFrequent/invert-BST/BST.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | public class BST{
3 |
4 | //TreeNode is not built in
5 | TreeNode root;
6 |
7 | public BST()
8 | {
9 | root = null;
10 | }
11 |
12 | //declared a what a TreeNode is with constructor
13 | public class TreeNode
14 | {
15 | String sortKey;
16 | String data;
17 | TreeNode left, right;
18 |
19 | public TreeNode(String sortKey, String data)
20 | {
21 | this.sortKey = sortKey;
22 | this.data = data;
23 | }
24 | }
25 |
26 |
27 |
28 | //alphabetical order
29 | public void insert(String data, String sortKey)
30 | {
31 | root = insert(root, data, sortKey);
32 | }
33 |
34 | public TreeNode insert(TreeNode root, String data, String sortKey)
35 | {
36 | if(root == null){return new TreeNode(data, sortKey);}//empty tree
37 |
38 | //TreeNode does exist, but now where should our TreeNode go?
39 | int abcOrder = sortKey.compareToIgnoreCase(root.sortKey);
40 |
41 | if(abcOrder > 0)
42 | {
43 | root.right = insert(root.right, data, sortKey);
44 | }
45 | else if(abcOrder < 0)
46 | {
47 | root.left = insert(root.left, data, sortKey);
48 | }
49 | // else dumb mistake; you would just return since it's equal
50 | return root;
51 | }
52 |
53 | //key is just how our TreeNodes are filed in our tree
54 | public String findData(String sortKey)
55 | {
56 | return findData(root, sortKey);
57 | }
58 |
59 | public String findData(TreeNode root, String sortKey)
60 | {
61 | if(root == null){return null;} //this sortKey DNE
62 | int abcOrder = sortKey.compareToIgnoreCase(root.sortKey);
63 | if(abcOrder > 0){ return findData(root.right, sortKey);} //TreeNode.right = findData(x.right, sortKey);} No you want data not a TreeNode
64 | else if(abcOrder < 0){ return findData(root.right, sortKey);}
65 | return root.data;
66 | }
67 | }//BinaryST
68 |
--------------------------------------------------------------------------------
/99-answerKey/leetcode/68|Text-Justification/caller.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class caller{
4 |
5 | static public void printer(List need, int max)
6 | {
7 | System.out.println("Should be: "+ max);
8 | for(String here : need)
9 | {
10 |
11 | // System.out.println("|"+here + "|");
12 | // System.out.println(here.length());
13 | if(here.length() != max)
14 | {
15 | System.out.println("|"+here + "|");
16 | System.out.println(here.length());
17 | }
18 | }
19 | System.out.println("\n\n");
20 |
21 | }
22 | public static void main(String[] args)
23 | {
24 | Solution call = new Solution();
25 | String[] candidate = new String[]{"Here", "is", "an", "example", "of", "text",
26 | "justification."};
27 | String[] blanks = new String[]{""};
28 | String[] letters = new String[]{"a","b","c","d","e"};
29 | String[] moreStrings = new String[]{"Listen","to","many,","speak","to","a","few."};
30 | String[] spacing = new String[]{"What","must","be","shall","be."};
31 | String[] checkEvenWire = new String[]{"Don't","go","around","saying",
32 | "the","world","owes","you","a","living;","the","world","owes","you","nothing;",
33 | "it","was","here","first."};
34 |
35 | List need = new ArrayList<>();
36 | SecondTry anotherone = new SecondTry();
37 |
38 |
39 | need = anotherone.fullJustify(candidate, 15);
40 | System.out.println("-----------------------");
41 | printer(need, 15);
42 |
43 | need = anotherone.fullJustify(letters, 6);
44 | printer(need, 6);
45 |
46 | need = anotherone.fullJustify(blanks, 6);
47 | printer(need, 6);
48 |
49 | need = anotherone.fullJustify(spacing, 12);
50 | printer(need, 12);
51 |
52 | need = anotherone.fullJustify(moreStrings, 6);
53 | printer(need, 6);
54 |
55 | need = anotherone.fullJustify(checkEvenWire, 30);
56 | printer(need, 30);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/2-Data-Structures/Trees/Test-tree/invertBST.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | /*=================================
3 | This inverts a BST
4 | 4
5 | / \
6 | 2 7
7 | / \ / \
8 | 1 3 6 9
9 |
10 | 4
11 | / \
12 | 7 2
13 | | |
14 | ------- (still have the same children)
15 | | |
16 | / \ / \
17 | 1 3 6 9
18 |
19 | When you hit temp/right/left nodes 7 and 2 will still
20 | be pointing to their left and right children unitl you
21 | update them
22 |
23 | 4
24 | / \
25 | 7 2
26 | / \ / \
27 | 9 6 3 1
28 |
29 | =================================*/
30 | public class invertBST{
31 |
32 | public TreeNode invertTree(TreeNode root)
33 | {
34 | //base case
35 | if(root == null) {return null;}
36 |
37 | //run
38 | TreeNode temp = root.left;
39 | root.left = root.right;
40 | root.right = temp;
41 |
42 | //recursion
43 |
44 | if(root.left != null)
45 | {
46 | // System.out.println("Parent: " + root.data + " new LEFT child: " + root.left.data );
47 | invertTree(root.left);
48 | }
49 | if(root.right != null)
50 | {
51 | // System.out.println("Parent: " + root.data + " new RIGHT child: " + root.right.data );
52 | invertTree(root.right);
53 | }
54 | return root;
55 | }
56 |
57 | //do BFS: queue
58 | public TreeNode iterInvert(TreeNode root)
59 | {
60 | Queue queue = new ArrayDeque<>();
61 | if(root != null){queue.add(root);}
62 | while(root != null)
63 | {
64 | TreeNode currNode = queue.poll();
65 | if(currNode.left != null)
66 | {
67 | queue.add(currNode.left);
68 | }
69 | if(currNode.right != null)
70 | {
71 | queue.add(currNode.right);
72 | }
73 |
74 | TreeNode temp = currNode.left;
75 | currNode.left = currNode.right;
76 | currNode.right = temp;
77 | }
78 | return null;
79 | }
80 | }
81 |
82 |
--------------------------------------------------------------------------------