├── .gitignore ├── C ├── Algorithms │ ├── quicksort.c │ └── quicksort_modified.c └── Chapter_1 │ ├── Question1_1 │ └── ChapQ1.1.c │ ├── Question1_2 │ └── ChapQ1.2.c │ ├── Question1_3 │ └── ChapQ1.3.c │ └── Question1_4 │ └── ChapQ1.4.c ├── Go ├── Chapter 1 │ ├── Question1_1 │ │ ├── Question.go │ │ └── Question_test.go │ ├── Question1_2 │ │ ├── Question.go │ │ └── Question_test.go │ ├── Question1_3 │ │ ├── Question.go │ │ ├── QuestionB.go │ │ └── Question_test.go │ ├── Question1_4 │ │ ├── Question.go │ │ └── Question_test.go │ ├── Question1_5 │ │ ├── Question.go │ │ └── Question_test.go │ ├── Question1_6 │ │ ├── Question.go │ │ └── Question_test.go │ ├── Question1_7 │ │ ├── Question.go │ │ └── Question_test.go │ └── Question1_8 │ │ ├── Question.go │ │ └── Question_test.go ├── Chapter 2 │ ├── Question2_1 │ │ └── Question.go │ ├── Question2_2 │ │ └── Question.go │ ├── Question2_3 │ │ └── Question.go │ ├── Question2_4 │ │ └── Question.go │ ├── Question2_5 │ │ └── Question.go │ ├── Question2_6 │ │ └── Question.go │ ├── Question2_7 │ │ └── Question.go │ ├── list │ │ ├── list.go │ │ └── list_test.go │ └── stack │ │ └── stack.go └── Chapter 3 │ ├── Question3_1 │ └── Question.go │ ├── Question3_2 │ └── Question.go │ ├── Question3_3 │ └── Question.go │ ├── Question3_4 │ └── Question.go │ ├── Question3_5 │ └── Question.go │ ├── Question3_6 │ └── Question.go │ ├── Question3_7 │ └── Question.go │ ├── list │ ├── list.go │ └── list_test.go │ └── stack │ └── stack.go ├── README.md ├── README.md.orig ├── Swift ├── Chapter 1 │ ├── Chapter 1.playground │ │ ├── contents.xcplayground │ │ ├── section-1.swift │ │ └── timeline.xctimeline │ └── Question 6 │ │ ├── README.md │ │ └── Rotate.swift ├── Chapter 18 │ └── Question-1 │ │ ├── Question.swift │ │ └── README.md ├── Chapter 2 │ └── Chapter 2.playground │ │ ├── contents.xcplayground │ │ ├── section-1.swift │ │ └── timeline.xctimeline ├── Chapter 5 │ ├── Question-1 │ │ └── Question.swift │ ├── Question-2 │ │ ├── Question.swift │ │ ├── README.md │ │ └── untitled │ ├── Question-3 │ │ ├── Question.swift │ │ └── README.md │ ├── Question-4 │ │ └── ReadMe.md │ ├── Question-5 │ │ ├── Question.swift │ │ └── README.md │ ├── Question-6 │ │ ├── Question.swift │ │ └── README.md │ └── Question-7 │ │ ├── Question5_7.swift │ │ └── README.md └── README.md ├── c++ ├── Chapter 1 │ ├── Chapter 1.vcxproj │ ├── Chapter 1.vcxproj.filters │ ├── Misc │ │ ├── SimpleHashTable.h │ │ └── SimpleHashTable.inl │ ├── Question1_1 │ │ ├── Question1_1.cpp │ │ └── Question1_1.h │ ├── Question1_2 │ │ ├── Question1_2.cpp │ │ └── Question1_2.h │ ├── Question1_3 │ │ ├── Question1_3.cpp │ │ ├── Question1_3.h │ │ ├── Question1_3_B.cpp │ │ └── Question1_3_B.h │ ├── Question1_4 │ │ ├── Question1_4.cpp │ │ └── Question1_4.h │ ├── Question1_5 │ │ ├── Question1_5.cpp │ │ └── Question1_5.h │ ├── Question1_6 │ │ ├── Question1_6.cpp │ │ └── Question1_6.h │ ├── Question1_7 │ │ ├── Question1_7.cpp │ │ └── Question1_7.h │ ├── Question1_8 │ │ ├── Question1_8.cpp │ │ └── Question1_8.h │ ├── Question2_1.h │ ├── Question2_2.h │ ├── Question2_3.h │ ├── Question2_4.h │ ├── Question2_5.h │ ├── Question2_6.h │ ├── Question2_7.h │ └── main.cpp ├── Chapter 11 │ ├── Chapter11.h │ ├── Chapter11_1.cpp │ ├── Chapter11_2.cpp │ ├── Chapter11_3.cpp │ ├── Chapter11_5.cpp │ ├── Chapter11_6.cpp │ ├── Chapter11_7.cpp │ └── Chapter11_8.cpp ├── Chapter 17 │ ├── Question17_1.cpp │ ├── Question17_3.cpp │ └── Question17_5.cpp ├── Chapter 2 │ ├── LinkedListClass │ │ ├── LinkedList.cpp │ │ └── LinkedList.h │ ├── Question2_1.cpp │ ├── Question2_2.cpp │ ├── Question2_3.cpp │ ├── Question2_4.cpp │ ├── Question2_5.cpp │ ├── Question2_6.cpp │ └── Question2_7.cpp ├── Chapter 3 │ ├── Question3_1.cpp │ ├── Question3_2.cpp │ ├── Question3_3.cpp │ ├── Question3_4.cpp │ ├── Question3_5.cpp │ ├── Question3_6.cpp │ └── Question3_7.cpp ├── Chapter 4 │ ├── 4.2.in │ ├── Question4_1.cpp │ ├── Question4_2.cpp │ ├── Question4_3.cpp │ ├── Question4_4.cpp │ ├── Question4_5.cpp │ ├── Question4_6.cpp │ ├── Question4_7.cpp │ ├── Question4_8.cpp │ └── Question4_9.cpp ├── Chapter 5 │ ├── Question5_1.cpp │ ├── Question5_2.cpp │ ├── Question5_3.cpp │ ├── Question5_5.cpp │ ├── Question5_6.cpp │ ├── Question5_7.cpp │ └── Question5_8.cpp ├── Chapter 9 │ ├── Question9_1.cpp │ ├── Question9_10.cpp │ ├── Question9_10.in │ ├── Question9_11.cpp │ ├── Question9_2.cpp │ ├── Question9_3.cpp │ ├── Question9_4.cpp │ ├── Question9_5.cpp │ ├── Question9_6.cpp │ ├── Question9_7.cpp │ ├── Question9_7.in │ ├── Question9_8.cpp │ └── Question9_9.cpp └── ctci.sln ├── c-sharp ├── Chapter01 │ ├── Chapter01.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Q01_1.cs │ ├── Q01_2.cs │ ├── Q01_3.cs │ ├── Q01_4.cs │ ├── Q01_5.cs │ ├── Q01_6.cs │ ├── Q01_7.cs │ └── Q01_8.cs ├── Chapter02 │ ├── Chapter02.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Q02_1.cs │ ├── Q02_2.cs │ ├── Q02_3.cs │ ├── Q02_4.cs │ ├── Q02_5.cs │ ├── Q02_6.cs │ ├── Q02_7.cs │ └── Q02_Bonus1.cs ├── Chapter03 │ ├── Chapter03.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Q03_1_A.cs │ ├── Q03_1_B.cs │ ├── Q03_2.cs │ ├── Q03_3.cs │ ├── Q03_4.cs │ ├── Q03_5.cs │ ├── Q03_6.cs │ └── Q03_7.cs ├── Chapter04 │ ├── Chapter04.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Q04_1.cs │ ├── Q04_2.cs │ ├── Q04_3.cs │ ├── Q04_4.cs │ ├── Q04_5.cs │ ├── Q04_6.cs │ ├── Q04_7.cs │ ├── Q04_8.cs │ └── Q04_9.cs ├── Chapter05 │ ├── Chapter05.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Q05_1.cs │ ├── Q05_2.cs │ ├── Q05_3.cs │ ├── Q05_5.cs │ ├── Q05_6.cs │ ├── Q05_7.cs │ └── Q05_8.cs ├── Chapter07 │ ├── Chapter07.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Q07_3.cs │ ├── Q07_4.cs │ ├── Q07_5.cs │ ├── Q07_6.cs │ └── Q07_7.cs ├── Chapter09 │ ├── Chapter09.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ └── Q09_6.cs ├── Chapter11 │ ├── Chapter11.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Q11_1.cs │ ├── Q11_2.cs │ └── Q11_3.cs ├── Chapter17 │ ├── Chapter17.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Q17_11.cs │ ├── Q17_12.cs │ ├── Q17_3.cs │ └── Q17_4.cs ├── Chapter18 │ ├── Chapter18.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Q18_1.cs │ ├── Q18_10.cs │ ├── Q18_11.cs │ ├── Q18_2.cs │ └── Q18_9.cs ├── Introduction │ ├── CompareBinaryToHex.cs │ ├── Introduction.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ └── SwapMinMax.cs ├── ctci.Contracts │ ├── IQuestion.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ └── ctci.Contracts.csproj ├── ctci.Library │ ├── AssortedMethods.cs │ ├── BTreePrinter.cs │ ├── BitVector.cs │ ├── LinkedListNode.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Set.cs │ ├── TreeNode.cs │ ├── Trie.cs │ ├── TrieNode.cs │ └── ctci.Library.csproj ├── ctci.sln └── ctci │ ├── Program.cs │ ├── Properties │ └── AssemblyInfo.cs │ └── ctci.csproj ├── clojure └── chapter01 │ ├── 01_01.clj │ ├── 01_02.clj │ ├── 01_03.clj │ ├── 01_04.clj │ └── 01_05.clj ├── dart ├── Chapter1 │ ├── Question1_1 │ │ └── question.dart │ ├── Question1_2 │ │ └── question.dart │ ├── Question1_3 │ │ ├── question.dart │ │ └── question_b.dart │ ├── Question1_4 │ │ └── question.dart │ ├── Question1_5 │ │ └── question.dart │ ├── Question1_6 │ │ └── question.dart │ ├── Question1_7 │ │ └── question.dart │ └── Question1_8 │ │ └── question.dart ├── Chapter11 │ ├── Introduction │ │ ├── binary_search.dart │ │ ├── merge_sort.dart │ │ └── quick_sort.dart │ ├── Question11_1 │ │ └── question.dart │ ├── Question11_2 │ │ ├── question.dart │ │ └── questionB.dart │ ├── Question11_3 │ │ └── question.dart │ ├── Question11_5 │ │ └── question.dart │ ├── Question11_6 │ │ ├── question.dart │ │ └── questionB.dart │ ├── Question11_7 │ │ └── question.dart │ └── Question11_8 │ │ └── question.dart ├── Chapter17 │ ├── Question17_1 │ │ └── question.dart │ ├── Question17_10 │ │ ├── question.dart │ │ └── questionString.dart │ ├── Question17_11 │ │ ├── question.dart │ │ └── questionB.dart │ ├── Question17_12 │ │ └── question.dart │ ├── Question17_13 │ │ ├── bi_node.dart │ │ ├── questionA.dart │ │ ├── questionB.dart │ │ └── questionC.dart │ ├── Question17_14 │ │ └── question.dart │ ├── Question17_2 │ │ ├── question.dart │ │ └── questionB.dart │ ├── Question17_3 │ │ ├── questionA.dart │ │ └── questionB.dart │ ├── Question17_4 │ │ └── question.dart │ ├── Question17_5 │ │ └── question.dart │ ├── Question17_6 │ │ └── question.dart │ ├── Question17_7 │ │ └── question.dart │ ├── Question17_8 │ │ └── question.dart │ └── Question17_9 │ │ └── question.dart ├── Chapter18 │ ├── Question18_1 │ │ └── question.dart │ ├── Question18_10 │ │ └── question.dart │ ├── Question18_11 │ │ ├── question.dart │ │ ├── square_cell.dart │ │ └── subsquare.dart │ ├── Question18_12 │ │ ├── questionB.dart │ │ └── questionC.dart │ ├── Question18_13 │ │ ├── question.dart │ │ ├── rectangle.dart │ │ └── word_group.dart │ ├── Question18_2 │ │ └── question.dart │ ├── Question18_3 │ │ └── question.dart │ ├── Question18_4 │ │ ├── question.dart │ │ └── questionBrute.dart │ ├── Question18_5 │ │ └── question.dart │ ├── Question18_6 │ │ └── question.dart │ ├── Question18_7 │ │ └── question.dart │ ├── Question18_8 │ │ └── question.dart │ └── Question18_9 │ │ ├── maxPQ.dart │ │ ├── minPQ.dart │ │ └── question.dart ├── Chapter2 │ ├── Question2_1 │ │ └── question.dart │ ├── Question2_2 │ │ └── question.dart │ ├── Question2_3 │ │ └── question.dart │ ├── Question2_4 │ │ ├── question.dart │ │ └── questionB.dart │ ├── Question2_5 │ │ ├── questionA.dart │ │ └── questionB.dart │ ├── Question2_6 │ │ └── question.dart │ └── Question2_7 │ │ ├── questionA.dart │ │ └── questionB.dart ├── Chapter3 │ ├── Question3_1 │ │ ├── question.dart │ │ └── questionB.dart │ ├── Question3_2 │ │ └── question.dart │ ├── Question3_3 │ │ └── question.dart │ ├── Question3_4 │ │ └── question.dart │ ├── Question3_5 │ │ └── question.dart │ ├── Question3_6 │ │ └── question.dart │ └── Question3_7 │ │ └── question.dart ├── Chapter4 │ ├── Question4_1 │ │ ├── question_brute.dart │ │ └── question_improved.dart │ ├── Question4_2 │ │ └── question.dart │ ├── Question4_3 │ │ └── question.dart │ ├── Question4_4 │ │ ├── question_bfs.dart │ │ └── question_dfs.dart │ ├── Question4_5 │ │ ├── question.dart │ │ └── question_b.dart │ ├── Question4_6 │ │ └── question.dart │ ├── Question4_7 │ │ ├── question.dart │ │ ├── question_b.dart │ │ ├── question_c.dart │ │ └── question_c_bad.dart │ ├── Question4_8 │ │ └── question.dart │ └── Question4_9 │ │ └── question.dart ├── Chapter5 │ ├── Question5_1 │ │ └── question.dart │ ├── Question5_2 │ │ └── question.dart │ ├── Question5_3 │ │ └── question.dart │ ├── Question5_5 │ │ └── question.dart │ ├── Question5_6 │ │ └── question.dart │ ├── Question5_7 │ │ └── question.dart │ └── Question5_8 │ │ └── question.dart ├── Chapter7 │ ├── Introduction │ │ ├── prime_numbers.dart │ │ └── sieve_of_eratosthenes.dart │ ├── Question7_3 │ │ └── question.dart │ ├── Question7_4 │ │ └── question.dart │ ├── Question7_5 │ │ └── question.dart │ ├── Question7_6 │ │ └── question.dart │ └── Question7_7 │ │ ├── questionA.dart │ │ └── questionB.dart ├── Chapter8 │ └── Question8_1 │ │ ├── black_jack_card.dart │ │ ├── black_jack_game_automator.dart │ │ ├── black_jack_hand.dart │ │ ├── card.dart │ │ ├── deck.dart │ │ ├── hand.dart │ │ ├── question.dart │ │ └── suit.dart ├── Chapter9 │ ├── Introduction │ │ ├── fibonacci.dart │ │ └── fibonacci_fb.dart │ ├── Question9_1 │ │ └── question.dart │ ├── Question9_10 │ │ └── question.dart │ ├── Question9_11 │ │ └── question.dart │ ├── Question9_2 │ │ ├── questionDP.dart │ │ └── questionR.dart │ ├── Question9_3 │ │ ├── question.dart │ │ └── questionB.dart │ ├── Question9_4 │ │ └── question.dart │ ├── Question9_5 │ │ └── question.dart │ ├── Question9_6 │ │ ├── questionA.dart │ │ └── questionB.dart │ ├── Question9_7 │ │ └── question.dart │ ├── Question9_8 │ │ └── question.dart │ └── Question9_9 │ │ └── question.dart ├── README.md └── utils │ ├── assorted_methods.dart │ ├── btree_printer.dart │ ├── drandom.dart │ ├── linked_list_node.dart │ ├── tree_node.dart │ └── trie.dart ├── go ├── README.md ├── chapter01 │ ├── question1.1 │ │ └── question1_1.go │ ├── question1.3 │ │ └── question1_3.go │ ├── question1.4 │ │ └── question1_4.go │ ├── question1.5 │ │ └── question1_5.go │ ├── question1.6 │ │ └── question1_6.go │ ├── question1.7 │ │ └── question1_7.go │ └── question1.8 │ │ └── question1_8.go ├── chapter02 │ ├── list │ │ └── list.go │ ├── question2.1 │ │ ├── question2_1.go │ │ └── question2_1b.go │ ├── question2.2 │ │ └── question2_2.go │ ├── question2.3 │ │ └── question2_3.go │ ├── question2.4 │ │ └── question2_4.go │ ├── question2.5 │ │ └── question2_5.go │ ├── question2.6 │ │ └── question2_6.go │ ├── question2.7 │ │ └── question2_7.go │ └── stack │ │ └── stack.go └── chapter04 │ ├── binarytree │ └── binarytree.go │ ├── question4.1 │ ├── question4_1.go │ └── question4_1b.go │ ├── question4.2 │ └── question4_2.go │ ├── question4.3 │ └── question4_3.go │ ├── question4.4 │ ├── question4_4.go │ └── question4_4b.go │ ├── question4.5 │ └── question4_5.go │ ├── question4.6 │ └── question4_6.go │ ├── question4.7 │ └── question4_7.go │ ├── question4.8 │ └── question4_8.go │ ├── question4.9 │ └── question4_9.go │ ├── queue │ └── queue.go │ └── tree │ └── tree.go ├── java ├── Chapter 1 │ ├── Question1_1 │ │ └── Question.java │ ├── Question1_3 │ │ ├── Question.java │ │ └── QuestionB.java │ ├── Question1_4 │ │ └── Question.java │ ├── Question1_5 │ │ └── Question.java │ ├── Question1_6 │ │ └── Question.java │ ├── Question1_7 │ │ └── Question.java │ └── Question1_8 │ │ └── Question.java ├── Chapter 10 │ ├── Question10_2 │ │ ├── Machine.java │ │ ├── Person.java │ │ └── Server.java │ ├── Question10_3 │ │ ├── Question.java │ │ ├── QuestionB.java │ │ └── input_file_q10_3.txt │ ├── Question10_4 │ │ ├── BitSet.java │ │ └── Question.java │ └── Question10_7 │ │ ├── Cache.java │ │ ├── Node.java │ │ └── Question.java ├── Chapter 11 │ ├── Introduction │ │ ├── BinarySearch.java │ │ ├── MergeSort.java │ │ └── Quicksort.java │ ├── Question11_1 │ │ └── Question.java │ ├── Question11_2 │ │ ├── AnagramComparator.java │ │ ├── Question.java │ │ └── QuestionB.java │ ├── Question11_3 │ │ └── Question.java │ ├── Question11_5 │ │ └── Question.java │ ├── Question11_6 │ │ ├── .DS_Store │ │ ├── Coordinate.java │ │ ├── QuestionA.java │ │ └── QuestionB.java │ ├── Question11_7 │ │ ├── HtWt.java │ │ └── Question.java │ └── Question11_8 │ │ ├── IntComparable.java │ │ ├── Question.java │ │ └── RankNode.java ├── Chapter 14 │ ├── Introduction │ │ ├── Ambiguous.java │ │ ├── Circle.java │ │ ├── Introduction.java │ │ ├── IntroductionCollections.java │ │ ├── IntroductionOverriding.java │ │ ├── Shape.java │ │ └── Square.java │ ├── Question14_1 │ │ └── Question.java │ ├── Question14_5 │ │ ├── Question.java │ │ └── Rectangle.java │ └── Question14_6 │ │ ├── CircularArray.java │ │ └── Question.java ├── Chapter 16 │ ├── IntroductionA │ │ ├── ExampleA.java │ │ └── RunnableThreadExample.java │ ├── IntroductionB │ │ ├── ExampleB.java │ │ └── ThreadExample.java │ ├── IntroductionLocks │ │ ├── Intro.java │ │ ├── LockedATM.java │ │ ├── MyClass.java │ │ └── NoLockATM.java │ ├── IntroductionSynchronization │ │ ├── Intro.java │ │ ├── MyClass.java │ │ └── MyObject.java │ ├── IntroductionSynchronizedBlocks │ │ ├── Intro.java │ │ ├── MyClass.java │ │ └── MyObject.java │ ├── IntroductionWaitNotify │ │ ├── Intro.java │ │ ├── MyClass.java │ │ └── MyObject.java │ ├── Question16_3 │ │ ├── Chopstick.java │ │ ├── Philosopher.java │ │ └── Question.java │ ├── Question16_4 │ │ ├── LockFactory.java │ │ ├── LockNode.java │ │ └── Question.java │ ├── Question16_5 │ │ ├── Foo.java │ │ ├── FooBad.java │ │ ├── MyThread.java │ │ └── Question.java │ └── Question16_6 │ │ ├── Foo.java │ │ ├── MyThread.java │ │ └── Question.java ├── Chapter 17 │ ├── Question17_1 │ │ └── Question.java │ ├── Question17_10 │ │ ├── Attribute.java │ │ ├── Element.java │ │ ├── QuestionOO.java │ │ └── QuestionString.java │ ├── Question17_11 │ │ ├── Question.java │ │ └── QuestionB.java │ ├── Question17_12 │ │ └── Question.java │ ├── Question17_13 │ │ ├── BiNode.java │ │ ├── QuestionA.java │ │ ├── QuestionB.java │ │ └── QuestionC.java │ ├── Question17_14 │ │ ├── Question.java │ │ └── Result.java │ ├── Question17_2 │ │ ├── Question.java │ │ └── QuestionB.java │ ├── Question17_3 │ │ ├── QuestionA.java │ │ └── QuestionB.java │ ├── Question17_4 │ │ └── Question.java │ ├── Question17_5 │ │ └── Question.java │ ├── Question17_6 │ │ └── Question.java │ ├── Question17_7 │ │ └── Question.java │ ├── Question17_8 │ │ └── Question.java │ └── Question17_9 │ │ └── Question.java ├── Chapter 18 │ ├── Question18_1 │ │ └── Question.java │ ├── Question18_10 │ │ └── Question.java │ ├── Question18_11 │ │ ├── Question.java │ │ ├── QuestionEff.java │ │ ├── SquareCell.java │ │ └── Subsquare.java │ ├── Question18_12 │ │ ├── QuestionB.java │ │ └── QuestionC.java │ ├── Question18_13 │ │ ├── Question.java │ │ ├── Rectangle.java │ │ └── WordGroup.java │ ├── Question18_2 │ │ └── Question.java │ ├── Question18_3 │ │ ├── Question.java │ │ └── QuestionAlternate.java │ ├── Question18_4 │ │ ├── Question.java │ │ └── QuestionBrute.java │ ├── Question18_5 │ │ └── Question.java │ ├── Question18_6 │ │ ├── Parts.java │ │ └── QuestionC.java │ ├── Question18_7 │ │ ├── LengthComparator.java │ │ └── Question.java │ ├── Question18_8 │ │ ├── Question.java │ │ ├── SuffixTree.java │ │ └── SuffixTreeNode.java │ └── Question18_9 │ │ ├── MaxHeapComparator.java │ │ ├── MinHeapComparator.java │ │ └── Question.java ├── Chapter 2 │ ├── Question2_1 │ │ └── Question.java │ ├── Question2_2 │ │ ├── Cpp Link │ │ ├── IntWrapper.java │ │ ├── Question.java │ │ └── Result.java │ ├── Question2_3 │ │ └── Question.java │ ├── Question2_4 │ │ ├── Question.java │ │ ├── QuestionB.java │ │ └── QuestionC.java │ ├── Question2_5 │ │ ├── PartialSum.java │ │ ├── QuestionA.java │ │ └── QuestionB.java │ ├── Question2_6 │ │ └── Question.java │ └── Question2_7 │ │ ├── Question.java │ │ └── QuestionB.java ├── Chapter 3 │ ├── Question3_1 │ │ ├── FullStackException.java │ │ ├── Question.java │ │ ├── QuestionB.java │ │ └── StackData.java │ ├── Question3_2 │ │ ├── NodeWithMin.java │ │ ├── Question.java │ │ ├── StackWithMin.java │ │ └── StackWithMin2.java │ ├── Question3_3 │ │ ├── Node.java │ │ ├── Question.java │ │ ├── SetOfStacks.java │ │ └── Stack.java │ ├── Question3_4 │ │ ├── Question.java │ │ └── Tower.java │ ├── Question3_5 │ │ ├── MyQueue.java │ │ └── Question.java │ ├── Question3_6 │ │ └── Question.java │ └── Question3_7 │ │ ├── Animal.java │ │ ├── AnimalQueue.java │ │ ├── Cat.java │ │ ├── Dog.java │ │ └── Question.java ├── Chapter 4 │ ├── Question4_1 │ │ ├── QuestionBrute.java │ │ └── QuestionImproved.java │ ├── Question4_2 │ │ ├── Graph.java │ │ ├── Node.java │ │ └── Question.java │ ├── Question4_3 │ │ └── Question.java │ ├── Question4_4 │ │ ├── QuestionBFS.java │ │ └── QuestionDFS.java │ ├── Question4_5 │ │ ├── IntWrapper.java │ │ ├── Question.java │ │ └── QuestionB.java │ ├── Question4_6 │ │ └── Question.java │ ├── Question4_7 │ │ ├── Question.java │ │ ├── QuestionB.java │ │ ├── QuestionC.java │ │ └── QuestionCBad.java │ ├── Question4_8 │ │ └── Question.java │ └── Question4_9 │ │ └── Question.java ├── Chapter 5 │ ├── Question5_1 │ │ └── Question.java │ ├── Question5_2 │ │ └── Question.java │ ├── Question5_3 │ │ └── Question.java │ ├── Question5_5 │ │ └── Question.java │ ├── Question5_6 │ │ └── Question.java │ ├── Question5_7.zip │ ├── Question5_7 │ │ ├── BitInteger.java │ │ └── Question.java │ ├── Question5_8 │ │ └── Question.java │ └── Sample_Code │ │ └── Sample_Code.java ├── Chapter 7 │ ├── Introduction │ │ ├── PrimeNumbers.java │ │ └── SieveOfEratosthenes.java │ ├── Question7_3 │ │ ├── Line.java │ │ └── Question.java │ ├── Question7_4 │ │ └── Question.java │ ├── Question7_5 │ │ ├── Line.java │ │ ├── Point.java │ │ ├── Question.java │ │ ├── Square Cut Tester - Chapter 10, Problem 5.xlsx │ │ └── Square.java │ ├── Question7_6 │ │ ├── GraphPoint.java │ │ ├── Line.java │ │ └── Question.java │ └── Question7_7 │ │ ├── QuestionA.java │ │ └── QuestionB.java ├── Chapter 8 │ ├── Question8_1 │ │ ├── BlackJackCard.java │ │ ├── BlackJackGameAutomator.java │ │ ├── BlackJackHand.java │ │ ├── Card.java │ │ ├── Deck.java │ │ ├── Hand.java │ │ ├── Question.java │ │ └── Suit.java │ ├── Question8_10 │ │ ├── Cell.java │ │ ├── Dummy.java │ │ ├── Hash.java │ │ └── Question.java │ ├── Question8_2 │ │ ├── Call.java │ │ ├── CallHandler.java │ │ ├── Caller.java │ │ ├── Director.java │ │ ├── Employee.java │ │ ├── Manager.java │ │ ├── Rank.java │ │ ├── Respondent.java │ │ └── Test.java │ ├── Question8_3 │ │ ├── CD.java │ │ ├── CDPlayer.java │ │ ├── JukeBox.java │ │ ├── Playlist.java │ │ ├── Song.java │ │ ├── SongSelector.java │ │ └── User.java │ ├── Question8_4 │ │ ├── Bus.java │ │ ├── Car.java │ │ ├── Level.java │ │ ├── Motorcycle.java │ │ ├── ParkingLot.java │ │ ├── ParkingSpot.java │ │ ├── Question.java │ │ ├── Vehicle.java │ │ └── VehicleSize.java │ ├── Question8_5 │ │ ├── Book.java │ │ ├── Display.java │ │ ├── Library.java │ │ ├── OnlineReaderSystem.java │ │ ├── User.java │ │ └── UserManager.java │ ├── Question8_7 │ │ ├── AddRequest.java │ │ ├── Conversation.java │ │ ├── GroupChat.java │ │ ├── Message.java │ │ ├── PrivateChat.java │ │ ├── RequestStatus.java │ │ ├── System.java │ │ ├── User.java │ │ ├── UserManager.java │ │ ├── UserStatus.java │ │ └── UserStatusType.java │ ├── Question8_8 │ │ ├── Automator.java │ │ ├── Board.java │ │ ├── Color.java │ │ ├── Direction.java │ │ ├── Game.java │ │ ├── Location.java │ │ ├── Piece.java │ │ ├── Player.java │ │ └── Question.java │ └── Question8_9 │ │ ├── Directory.java │ │ ├── Entry.java │ │ ├── File.java │ │ └── Question.java ├── Chapter 9 │ ├── Introduction │ │ ├── Fibonacci.java │ │ └── FibonacciFB.java │ ├── Question9_1 │ │ └── Question.java │ ├── Question9_10 │ │ ├── Box.java │ │ └── Question.java │ ├── Question9_11 │ │ └── Question.java │ ├── Question9_2 │ │ ├── QuestionDP.java │ │ └── QuestionR.java │ ├── Question9_3 │ │ ├── Question.java │ │ └── QuestionB.java │ ├── Question9_4 │ │ └── Question.java │ ├── Question9_5 │ │ └── Question.java │ ├── Question9_6 │ │ ├── QuestionA.java │ │ └── QuestionB.java │ ├── Question9_7 │ │ └── Question.java │ ├── Question9_8 │ │ └── Question.java │ └── Question9_9 │ │ └── Question.java ├── CtCILibrary │ └── CtCILibrary │ │ ├── AssortedMethods.java │ │ ├── BTreePrinter.java │ │ ├── BitVector.java │ │ ├── LinkedListNode.java │ │ ├── TreeNode.java │ │ ├── Trie.java │ │ └── TrieNode.java └── Introduction │ ├── CompareBinaryToHex │ └── CompareBinaryToHex.java │ └── SwapMinMax │ └── SwapMinMax.java ├── javascript ├── README.md ├── lib │ ├── data-structures │ │ ├── chapter-1 │ │ │ ├── 1_1.js │ │ │ ├── 1_2.js │ │ │ ├── 1_3.js │ │ │ └── 1_8.js │ │ ├── chapter-2 │ │ │ ├── 2_1.js │ │ │ ├── 2_2.js │ │ │ └── 2_3.js │ │ ├── chapter-3 │ │ │ └── 3_5.js │ │ ├── chapter-9 │ │ │ └── 9_1.js │ │ └── linked-list │ │ │ ├── doublyLinkedList.js │ │ │ ├── node.js │ │ │ └── singlyLinkedList.js │ └── index.js ├── package.json └── test │ ├── data-structures │ ├── chapter-1 │ │ ├── 1_1_Spec.js │ │ ├── 1_2_Spec.js │ │ ├── 1_3_Spec.js │ │ └── 1_8_Spec.js │ ├── chapter-2 │ │ ├── 2_1_Spec.js │ │ ├── 2_2_Spec.js │ │ └── 2_3_Spec.js │ ├── chapter-3 │ │ └── 3_5_Spec.js │ ├── chapter-9 │ │ └── 9_1_Spec.js │ └── linked-list │ │ ├── doublyLinkedListSpec.js │ │ ├── nodeSpec.js │ │ └── singlyLinkedListSpec.js │ └── test_helper.js ├── objective c ├── Chapter1 │ ├── Question1-5 │ │ ├── Question1-5.xcodeproj │ │ │ ├── project.pbxproj │ │ │ ├── project.xcworkspace │ │ │ │ ├── contents.xcworkspacedata │ │ │ │ └── xcshareddata │ │ │ │ │ └── Question1-5.xccheckout │ │ │ └── xcuserdata │ │ │ │ └── rmoniz.xcuserdatad │ │ │ │ └── xcdebugger │ │ │ │ └── Breakpoints_v2.xcbkptlist │ │ └── Question1-5 │ │ │ ├── Question1-5-Prefix.pch │ │ │ └── main.m │ ├── Question1-6 │ │ ├── Question1-6.xcodeproj │ │ │ ├── project.pbxproj │ │ │ └── project.xcworkspace │ │ │ │ ├── contents.xcworkspacedata │ │ │ │ └── xcshareddata │ │ │ │ └── Question1-6.xccheckout │ │ └── Question1-6 │ │ │ ├── Question1-6-Prefix.pch │ │ │ └── main.m │ ├── Question1_1 │ │ ├── Question1_1.xcodeproj │ │ │ ├── project.pbxproj │ │ │ ├── project.xcworkspace │ │ │ │ ├── contents.xcworkspacedata │ │ │ │ └── xcshareddata │ │ │ │ │ └── Question1_1.xccheckout │ │ │ └── xcuserdata │ │ │ │ └── rmoniz.xcuserdatad │ │ │ │ └── xcdebugger │ │ │ │ └── Breakpoints_v2.xcbkptlist │ │ └── Question1_1 │ │ │ ├── Question1_1-Prefix.pch │ │ │ ├── Question1_1.1 │ │ │ └── main.m │ ├── Question1_3 │ │ ├── Question1_3.xcodeproj │ │ │ ├── project.pbxproj │ │ │ ├── project.xcworkspace │ │ │ │ ├── contents.xcworkspacedata │ │ │ │ └── xcshareddata │ │ │ │ │ └── Question1_3.xccheckout │ │ │ └── xcuserdata │ │ │ │ └── rmoniz.xcuserdatad │ │ │ │ └── xcdebugger │ │ │ │ └── Breakpoints_v2.xcbkptlist │ │ └── Question1_3 │ │ │ ├── Question1_3-Prefix.pch │ │ │ └── main.m │ └── Question1_4 │ │ ├── Question1_4.xcodeproj │ │ ├── project.pbxproj │ │ ├── project.xcworkspace │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcshareddata │ │ │ │ └── Question1_4.xccheckout │ │ └── xcuserdata │ │ │ └── rmoniz.xcuserdatad │ │ │ └── xcdebugger │ │ │ └── Breakpoints_v2.xcbkptlist │ │ └── Question1_4 │ │ ├── Question1_4-Prefix.pch │ │ └── main.m ├── CtCILibrary │ └── CtCILibrary │ │ ├── AssortedMethods.h │ │ └── AssortedMethods.m ├── Introduction │ ├── CompareBinaryToHex │ │ ├── CompareBinaryToHex.xcodeproj │ │ │ ├── project.pbxproj │ │ │ └── project.xcworkspace │ │ │ │ ├── contents.xcworkspacedata │ │ │ │ └── xcshareddata │ │ │ │ └── CompareBinaryToHex.xccheckout │ │ └── CompareBinaryToHex │ │ │ ├── CompareBinaryToHex-Prefix.pch │ │ │ ├── CompareBinaryToHex.1 │ │ │ ├── CompareBinaryToHex.h │ │ │ ├── CompareBinaryToHex.m │ │ │ └── main.m │ └── SwapMinMax │ │ ├── SwapMinMax.xcodeproj │ │ ├── project.pbxproj │ │ ├── project.xcworkspace │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcshareddata │ │ │ │ └── SwapMinMax.xccheckout │ │ └── xcuserdata │ │ │ └── rmoniz.xcuserdatad │ │ │ └── xcdebugger │ │ │ └── Breakpoints_v2.xcbkptlist │ │ └── SwapMinMax │ │ ├── SwapMinMax-Prefix.pch │ │ ├── SwapMinMax.1 │ │ └── main.m └── README.txt ├── python ├── Chapter 1 │ ├── Question1_1 │ │ ├── 1-unique.py │ │ ├── ChapQ1.1.py │ │ ├── alluniq.py │ │ └── testalluniq.py │ ├── Question1_2 │ │ ├── ChapQ1.2.py │ │ ├── revstr.py │ │ └── testrevstr.py │ ├── Question1_3 │ │ ├── ChapQ1.3.py │ │ ├── anagram.py │ │ └── testanagram.py │ ├── Question1_4 │ │ ├── ChapQ1.4.py │ │ ├── Q1_4.py │ │ ├── replace.py │ │ └── testreplace.py │ ├── Question1_5 │ │ ├── ChapQ1.5.py │ │ ├── compress.py │ │ └── testcompress.py │ ├── Question1_6 │ │ ├── ChapQ1.6.py │ │ ├── rotateimg.py │ │ └── testrotate.py │ ├── Question1_7 │ │ └── ChapQ1.7.py │ └── Question1_8 │ │ └── ChapQ1.8.py ├── Chapter 2 │ ├── Question2_1.py │ ├── Question2_2.py │ ├── Question2_3.py │ ├── Question2_4.py │ ├── Question2_5.py │ ├── Question2_6.py │ ├── Question2_7.py │ └── classes │ │ ├── LinkedList.py │ │ ├── LinkedList.pyc │ │ ├── __init__.py │ │ └── __init__.pyc ├── Chapter 3 │ ├── Question3_1 │ │ └── Q3_1.py │ ├── Question3_2 │ │ └── ChapQ3.2.py │ ├── Question3_3 │ │ └── Q3_3.py │ ├── Question3_4 │ │ └── Q3_4.py │ ├── Question3_5 │ │ ├── 3_5.py │ │ └── ChapQ3.5.py │ ├── Question3_6 │ │ └── ChapQ3.6.py │ └── Question3_7 │ │ └── ChapQ3.7.py ├── Chapter 4 │ ├── Question4_1 │ │ └── ChapQ4.1.py │ ├── Question4_2 │ │ └── ChapQ4.2.py │ ├── Question4_3 │ │ └── ChapQ4.3.py │ ├── Question4_4 │ │ └── ChapQ4.4.py │ ├── Question4_5 │ │ └── ChapQ4.5.py │ ├── Question4_6 │ │ └── ChapQ4.6.py │ ├── Question4_7 │ │ ├── BinaryTreeNode.py │ │ └── Q4_7.py │ ├── Question4_8 │ │ └── ChapQ4.8.py │ └── Question4_9 │ │ ├── BinaryTreeNode.py │ │ └── Q4_9.py └── Chapter 9 │ ├── Question9_01 │ └── staircase.py │ ├── Question9_02 │ └── robot_paths.py │ ├── Question9_03 │ ├── magic_index.py │ └── magic_index_followup.py │ ├── Question9_04 │ └── subsets.py │ ├── Question9_05 │ └── permutations.py │ ├── Question9_06 │ └── parentheses.py │ ├── Question9_07 │ └── paint_fill.py │ ├── Question9_08 │ └── change_making.py │ ├── Question9_09 │ └── queens_problem.py │ ├── Question9_10 │ └── tallest_stack.py │ └── Question9_11 │ └── parenthesizing.py ├── ruby ├── Gemfile ├── Gemfile.lock ├── lib │ └── data-structures │ │ ├── chapter-1 │ │ ├── 1_1.rb │ │ ├── 1_5.rb │ │ └── 1_8.rb │ │ ├── chapter-2 │ │ ├── 2_1.rb │ │ ├── 2_3.rb │ │ ├── 2_4.rb │ │ └── 2_6.rb │ │ ├── hash-table │ │ └── hash_table.rb │ │ └── linked-list │ │ ├── doubly_linked_list.rb │ │ ├── node.rb │ │ └── singly_linked_list.rb └── spec │ ├── data-structures │ ├── chapter-1 │ │ ├── 1_1_spec.rb │ │ ├── 1_5_spec.rb │ │ └── 1_8_spec.rb │ ├── chapter-2 │ │ ├── 2_1_spec.rb │ │ ├── 2_4_spec.rb │ │ └── 2_6_spec.rb │ ├── hash-table │ │ └── hash_table_spec.rb │ └── linked-list │ │ ├── doubly_linked_list_spec.rb │ │ ├── node_spec.rb │ │ └── singly_linked_list_spec.rb │ └── spec_helper.rb └── scala ├── build.sbt └── src ├── main └── scala │ ├── chapter1 │ └── Chapter1Solution.scala │ ├── chapter2 │ └── Chapter2Solution.scala │ ├── chapter3 │ └── Chapter3Solution.scala │ └── chapter4 │ └── Chapter4Solution.scala └── test └── scala ├── chapter1 └── chapter1Test.scala └── chapter2 └── chapter2Test.scala /Go/Chapter 1/Question1_1/Question.go: -------------------------------------------------------------------------------- 1 | package Question1_1 2 | 3 | // using a bitvector 4 | func isUniqueChars(str string) bool { 5 | if len(str) > 128 { 6 | return false 7 | } 8 | var checker uint = 0; // use this int as a bit vector 9 | for _, char := range str { 10 | val := uint(char) - uint('a') 11 | if ((checker & (1 << val)) > 0) { 12 | return false 13 | } 14 | checker |= (1 << val) 15 | } 16 | return true 17 | } 18 | 19 | // using a boolean array 20 | func isUniqueChars2(str string) bool { 21 | if len(str) > 128 { 22 | return false 23 | } 24 | var char_set [128]bool // every bool represents if a character was seen 25 | for _, val := range str { 26 | if char_set[val] { 27 | return false 28 | } 29 | char_set[val] = true 30 | } 31 | return true 32 | } 33 | -------------------------------------------------------------------------------- /Go/Chapter 1/Question1_1/Question_test.go: -------------------------------------------------------------------------------- 1 | package Question1_1 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestIsUniqueChars(t *testing.T) { 8 | cases := []struct { 9 | input string 10 | expect bool 11 | }{ 12 | {"abcd", true}, 13 | {"", true}, 14 | {`_\/,"'.;`, true}, 15 | {"abca", false}, 16 | {"aaaa", false}, 17 | } 18 | 19 | for _, thisCase := range cases { 20 | result := isUniqueChars(thisCase.input) 21 | if result != thisCase.expect { 22 | t.Errorf("isUniqueChars: input %q, expect %v, but got %v\n", thisCase.input, thisCase.expect, result) 23 | } 24 | result2 := isUniqueChars2(thisCase.input) 25 | if result2 != thisCase.expect { 26 | t.Errorf("isUniqueChars2: input %q, expect %v, but got %v\n", thisCase.input, thisCase.expect, result2) 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Go/Chapter 1/Question1_2/Question.go: -------------------------------------------------------------------------------- 1 | package Question1_2 2 | 3 | // function to reverse a C style string, by returning a new reversed string 4 | func reverse(str string) string { 5 | length := len(str) 6 | revArr := []byte(str) 7 | for i := length / 2; i >= 0; i-- { 8 | revArr[i], revArr[length-i-1] = revArr[length-i-1], revArr[i] 9 | } 10 | return string(revArr) 11 | } 12 | -------------------------------------------------------------------------------- /Go/Chapter 1/Question1_2/Question_test.go: -------------------------------------------------------------------------------- 1 | package Question1_2 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestReverse(t *testing.T) { 8 | cases := []struct { 9 | input string 10 | expect string 11 | }{ 12 | {"abcd", "dcba"}, 13 | {"abcde", "edcba"}, 14 | } 15 | 16 | for _, thisCase := range cases { 17 | result := reverse(thisCase.input) 18 | if result != thisCase.expect { 19 | t.Errorf("reverse: input %q, expect %q, but got %q\n", thisCase.input, thisCase.expect, result) 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Go/Chapter 1/Question1_3/Question.go: -------------------------------------------------------------------------------- 1 | package Question1_3 2 | import "sort" 3 | 4 | type sortRunes []rune 5 | 6 | // have to define the three methods for native sort to work 7 | func (s sortRunes) Less(i, j int) bool { 8 | return s[i] < s[j] 9 | } 10 | 11 | func (s sortRunes) Swap(i, j int) { 12 | s[i], s[j] = s[j], s[i] 13 | } 14 | 15 | func (s sortRunes) Len() int { 16 | return len(s) 17 | } 18 | 19 | func SortString(s string) string { 20 | r := []rune(s) 21 | sort.Sort(sortRunes(r)) 22 | return string(r) 23 | } 24 | 25 | /* Given two strings, decide if one is a permutation of the other */ 26 | func permutation(str1, str2 string) bool { 27 | // if they are anagrams, they will have the same characters 28 | // hence comparing if their sorted version is equal gives the result 29 | return SortString(str1) == SortString(str2) 30 | } 31 | -------------------------------------------------------------------------------- /Go/Chapter 1/Question1_3/QuestionB.go: -------------------------------------------------------------------------------- 1 | package Question1_3 2 | 3 | /* Given two strings, decide if one is a permutation of the other */ 4 | func permutation (str1, str2 string) bool { 5 | if len(str1) != len(str2) { 6 | return false 7 | } 8 | count1 := make([]int) //declare a map of rune to int 9 | // For each character in input1 string, increment count 10 | for _ , v := range str1 { 11 | count1[rune(v)]++ 12 | } 13 | // For each character in input2 string, decrement count in the count1 map 14 | // the count becomes less than 0, if there is more count in second string or 15 | // if that character was not present in string1 16 | for _ , v := range str2 { 17 | c := rune(v) 18 | count1[c]-- 19 | if count1[c] < 0 { 20 | return false 21 | } 22 | } 23 | return true 24 | } 25 | -------------------------------------------------------------------------------- /Go/Chapter 1/Question1_3/Question_test.go: -------------------------------------------------------------------------------- 1 | package Question1_3 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestPermutation(t *testing.T) { 8 | cases := []struct { 9 | input1 string 10 | input2 string 11 | expect bool 12 | }{ 13 | {"apple", "papel", true}, 14 | {"carrot", "tarroc", true}, 15 | {"hello", "llloh", false}, 16 | } 17 | for _, thisCase := range cases { 18 | result := permutation(thisCase.input1, thisCase.input2) 19 | if result != thisCase.expect { 20 | t.Errorf("reverse: input (%q, %q), expected %v, but got %v\n", 21 | thisCase.input1, thisCase.input2, thisCase.expect, result) 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Go/Chapter 1/Question1_4/Question.go: -------------------------------------------------------------------------------- 1 | package Question1_4 2 | 3 | // method to replace all spaces in a string with ‘%20’ 4 | // assuming that the string has sufficient space at the end 5 | func ReplaceSpace(charsArr []rune, originalLen int) { 6 | countSpaces := 0 7 | for i := 0; i < originalLen; i++ { 8 | if charsArr[i] == rune(' ') { 9 | countSpaces++ 10 | } 11 | } 12 | index := len(charsArr) 13 | for i := originalLen-1; i >= 0; i-- { 14 | if charsArr[i] == rune(' ') { 15 | charsArr[index-1] = '0'; 16 | charsArr[index-2] = '2'; 17 | charsArr[index-3] = '%'; 18 | index = index-3; 19 | } else { 20 | charsArr[index-1] = charsArr[i] 21 | index-- 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Go/Chapter 1/Question1_5/Question_test.go: -------------------------------------------------------------------------------- 1 | package Question1_5 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestCompress(t *testing.T) { 8 | cases := []struct { 9 | input string 10 | expect string 11 | }{ 12 | {"aabcccccaaa", `a2b1c5a3`}, 13 | {"zxy", `zxy`}, 14 | } 15 | for _, thisCase := range cases { 16 | result := compress(thisCase.input) 17 | if result != thisCase.expect { 18 | t.Errorf("Compress: input %q, expected %q, but got %q\n", 19 | thisCase.input, thisCase.expect, result) 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Go/Chapter 1/Question1_6/Question_test.go: -------------------------------------------------------------------------------- 1 | package Question1_6 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestRotate90(t *testing.T) { 8 | cases := []struct { 9 | input matrixNN 10 | expect matrixNN 11 | }{ 12 | { matrixNN{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} , 13 | matrixNN{{7, 4, 1}, {8, 5, 2}, {9, 6, 3}} }, 14 | { matrixNN{ {1, 2, 3, 4}, { 5, 6, 7, 8}, { 9, 10, 11, 12 }, {13, 14, 15, 16} }, 15 | matrixNN{ {13, 9, 5, 1}, {14, 10, 6, 2}, {15, 11, 7, 3}, {16, 12, 8, 4} } }, 16 | } 17 | 18 | for _, thisCase := range cases { 19 | input := thisCase.input 20 | thisCase.input.rotate90() 21 | result := thisCase.input 22 | if (!result.compare( thisCase.expect )) { 23 | t.Errorf("\n__________\nRotate90: \ninput %v \nexpected %v\n but got %v \n______________", input, thisCase.expect, result) 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Go/Chapter 1/Question1_7/Question_test.go: -------------------------------------------------------------------------------- 1 | package Question1_7 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestSetZeroes(t *testing.T) { 8 | cases := []struct { 9 | input matrixMN 10 | expect matrixMN 11 | }{ 12 | { matrixMN{{1, 2, 3}, {4, 0, 6}, {7, 8, 9}} , 13 | matrixMN{{1, 0, 3}, {0, 0, 0}, {7, 0, 9}} }, 14 | { matrixMN{ {1, 2, 3, 0}, { 5, 6, 7, 8}, { 9, 10, 11, 12 } }, 15 | matrixMN{ {0, 0, 0, 0}, {5, 6, 7, 0}, {9, 10, 11, 0} } }, 16 | } 17 | 18 | for _, thisCase := range cases { 19 | input := thisCase.input 20 | thisCase.input.setZeroes() 21 | result := thisCase.input 22 | if (!result.compare( thisCase.expect )) { 23 | t.Errorf("\n__________\nRotate90: \ninput %v \nexpected %v\n but got %v \n______________", input, thisCase.expect, result) 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Go/Chapter 1/Question1_8/Question.go: -------------------------------------------------------------------------------- 1 | package Question1_8 2 | 3 | /* 4 | * Assume you have a method isSubstring which checks if one word is a 5 | * substring of another. Given two strings, s1 and s2, write code to check 6 | * if s2 is a rotation of s1 using only one call to isSubstring 7 | * (e.g., "waterbottle" is a rotation of "erbottlewat"). 8 | */ 9 | 10 | import ( 11 | "strings" 12 | ) 13 | 14 | func isRotation(s1, s2 string) bool { 15 | length1 := len(s1) 16 | if(length1 == len(s2) && length1 > 0) { 17 | /* Double the original string and check whether the rotated is a substring of it*/ 18 | s1s1 := s1+s1 19 | if strings.Contains(s1s1, s2){ 20 | return true 21 | } 22 | } 23 | return false 24 | } 25 | -------------------------------------------------------------------------------- /Go/Chapter 1/Question1_8/Question_test.go: -------------------------------------------------------------------------------- 1 | package Question1_8 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestIsRotation(t *testing.T) { 8 | cases := []struct { 9 | input []string 10 | expect bool 11 | }{ 12 | { []string{"apple", "pleap"} , true }, 13 | { []string{"waterbottle", "erbottlewat"}, true }, 14 | { []string{"camera", "macera"}, false }, 15 | { []string{"santhosh", "@santhosh"}, false}, 16 | } 17 | 18 | for _, thisCase := range cases { 19 | input := thisCase.input 20 | result := isRotation(input[0], input[1]) 21 | if (result != thisCase.expect) { 22 | t.Errorf("IsRotation: input %q expected %v but got %v", input, thisCase.expect, result) 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Go/Chapter 2/list/list_test.go: -------------------------------------------------------------------------------- 1 | package list 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestLength(t *testing.T) { 8 | for i := 1; i < 10; i++ { 9 | l := RandomLinkedList(i, 1, 10) 10 | result := l.Len() 11 | if (result != i) { 12 | t.Errorf("Length: Got-%v Expected-%v\n", result, i) 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Go/Chapter 2/stack/stack.go: -------------------------------------------------------------------------------- 1 | package stack // simple LIFO stack 2 | 3 | type Stack struct { 4 | top *Element 5 | size int 6 | } 7 | 8 | type Element struct { 9 | value int // All types satisfy the empty interface, so we can store anything here. 10 | next *Element 11 | } 12 | 13 | // Return the stack's length 14 | func (s *Stack) Len() int { 15 | return s.size 16 | } 17 | 18 | // Push a new element onto the stack 19 | func (s *Stack) Push(value int) { 20 | s.top = &Element{value, s.top} 21 | s.size++ 22 | } 23 | 24 | // Remove the top element from the stack and return it's value 25 | // If the stack is empty, return nil 26 | func (s *Stack) Pop() (value int) { 27 | if s.size > 0 { 28 | value, s.top = s.top.value, s.top.next 29 | s.size-- 30 | return value 31 | } 32 | return -1 33 | } 34 | -------------------------------------------------------------------------------- /Go/Chapter 3/list/list_test.go: -------------------------------------------------------------------------------- 1 | package list 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestLength(t *testing.T) { 8 | for i := 1; i < 10; i++ { 9 | l := RandomLinkedList(i, 1, 10) 10 | result := l.Len() 11 | if (result != i) { 12 | t.Errorf("Length: Got-%v Expected-%v\n", result, i) 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ctci 2 | ==== 3 | 4 | Solutions for "Cracking the Coding Interview v5" 5 | 6 | Adding equivalent solutions in Objective-C 7 | Adding my own solutions 8 | -------------------------------------------------------------------------------- /README.md.orig: -------------------------------------------------------------------------------- 1 | ctci 2 | Solutions for "Cracking the Coding Interview v5" 3 | 4 | Due to copyrights , the questions themselves are not published -------------------------------------------------------------------------------- /Swift/Chapter 1/Chapter 1.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Swift/Chapter 1/Chapter 1.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Swift/Chapter 1/Question 6/README.md: -------------------------------------------------------------------------------- 1 | ## Question 2 | ``` 3 | Given an image represented by an NxN matrix, where each pixel in the image is 4 4 | bytes, write a method to rotate the image by 90 degrees. Can you do this in place? 5 | ``` 6 | ## Algorithm: 7 | ``` 8 | 1) Get the transpose of the input 9 | 2) swap first and Nth column, second and N-1th column until u reach the N/2th column 10 | ``` -------------------------------------------------------------------------------- /Swift/Chapter 18/Question-1/Question.swift: -------------------------------------------------------------------------------- 1 | 2 | // Author: Prakash Natarajan (c) 2015 3 | // Email: nprakashece@gmail.com | pn33@buffalo.edu 4 | // License: GNU GPLv3 5 | 6 | 7 | import UIKit 8 | 9 | // 18.1 10 | /* 11 | Write a function that adds two numbers. You should not use + or any arithmetic op- erators. 12 | */ 13 | /* algorithm: 14 | 1) calculate the sum part and carry part 15 | 2) add the parts individually 16 | */ 17 | 18 | func sum(var a:Int, var b:Int) -> Int { 19 | var sum = 0; 20 | var carry = 0; 21 | while(b != 0) { 22 | sum = a ^ b; 23 | carry = (a & b) << 1; 24 | (a, b) = (sum, carry) 25 | } 26 | return a 27 | } 28 | 29 | 30 | //play ground samples 31 | sum(-1,1) 32 | sum(2,3) -------------------------------------------------------------------------------- /Swift/Chapter 18/Question-1/README.md: -------------------------------------------------------------------------------- 1 | ## Question 18.1 2 | ``` 3 | Write a function that adds two numbers. You should not use + or any arithmetic op- erators. 4 | ``` -------------------------------------------------------------------------------- /Swift/Chapter 2/Chapter 2.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Swift/Chapter 2/Chapter 2.playground/timeline.xctimeline: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Swift/Chapter 5/Question-2/Question.swift: -------------------------------------------------------------------------------- 1 | 2 | // Author: Prakash Natarajan (c) 2014 3 | // Email: nprakashece@gmail.com | pn33@buffalo.edu 4 | // License: GNU GPLv3 5 | 6 | import UIKit 7 | 8 | class Question5_2 { 9 | func binary2(var num:Double) -> String { 10 | if(num <= 0 || num >= 1) 11 | { return "ERROR" } 12 | var binary:String = "." 13 | while (num > 0.0) { 14 | if(binary.utf16Count > 32) { return "ERROR" } 15 | 16 | var r = num * 2 17 | if(r >= 1) { 18 | binary += "1" 19 | num = r - 1 20 | } 21 | else { 22 | binary += "0" 23 | num = r 24 | } 25 | } 26 | return binary 27 | } 28 | 29 | } 30 | 31 | var pgm = Question5_2() 32 | pgm.binary2(0.125) 33 | 34 | -------------------------------------------------------------------------------- /Swift/Chapter 5/Question-2/README.md: -------------------------------------------------------------------------------- 1 | ## Question 5_2 2 | ``` 3 | Youaregiven two 32-bit numbers,N andM, andtwobitpositions, i andj. Write a method to insert Minto Nsuch that Mstarts at bit j and ends at bit i. Youcan assume that the bits j through i have enough space to fit all ofM. That is,ifM= 10011, you can assume that there are at least 5 bits between j and i. You would not, for example,havej-3 andi=2,becauseMcouldnotfully fitbetweenbit3andbit2. 4 | 5 | EXAMPLE: 6 | Input:N=16000000000, M=10011, i =2, j =6 Output: N = 10001001100 7 | 8 | ``` 9 | 10 | 11 | -------------------------------------------------------------------------------- /Swift/Chapter 5/Question-2/untitled: -------------------------------------------------------------------------------- 1 | 2 | // Author: Prakash Natarajan (c) 2014 3 | // Email: nprakashece@gmail.com | pn33@buffalo.edu 4 | // License: GNU GPLv3 5 | 6 | import UIKit 7 | 8 | class Question5_2 { 9 | func binary2(var num:Double) -> String { 10 | if(num <= 0 || num >= 1) 11 | { return "ERROR" } 12 | var binary:String = "." 13 | while (num > 0.0) { 14 | if(binary.utf16Count > 32) { return "ERROR" } 15 | 16 | var r = num * 2 17 | if(r >= 1) { 18 | binary += "1" 19 | num = r - 1 20 | } 21 | else { 22 | binary += "0" 23 | num = r 24 | } 25 | } 26 | return binary 27 | } 28 | 29 | } 30 | 31 | var pgm = Question5_2() 32 | pgm.binary2(0.125) 33 | 34 | -------------------------------------------------------------------------------- /Swift/Chapter 5/Question-3/README.md: -------------------------------------------------------------------------------- 1 | ## Question 5_3 2 | ``` 3 | Given a positive integer, print the next smallest and the next largest number that have the same number of 1 bits in their binary representation. 4 | 5 | ``` 6 | 7 | ###Algorithm: 8 | Step by step illustration: 9 | ``` 10 | 10011100 11 | 00011100 - right most string of 1's in x 12 | 00000011 - right shifted pattern except left most bit ------> [A] 13 | 00010000 - isolated left most bit of right most 1's pattern 14 | 00100000 - shiftleft-ed the isolated bit by one position ------> [B] 15 | 10000000 - left part of x, excluding right most 1's pattern ------> [C] 16 | 10100000 - add B and C (OR operation) ------> [D] 17 | 10100011 - add A and D which is required number 163 18 | ``` 19 | 20 | ### Reference: 21 | 22 | [GeeksforGeeks c solution](http://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/) -------------------------------------------------------------------------------- /Swift/Chapter 5/Question-4/ReadMe.md: -------------------------------------------------------------------------------- 1 | ## ((n & (n-1)) == 0) 2 | 3 | ### Explanation: 4 | [Example code which is already Implemented](https://github.com/AlgorithmCrackers/Interview-Questions/blob/master/Bit-Hacks/NextPowerof2/NextPowerOf2.swift) 5 | 6 | ```` 7 | Any power of 2 minus 1 is all ones: (2 N - 1 = 111....b) 8 | 9 | 2 = 2^1. 2-1 = 1 (1b) 10 | 4 = 2^2. 4-1 = 3 (11b) 11 | 8 = 2^3. 8-1 = 7 (111b) 12 | Take 8 for example. 1000 & 0111 = 0000 13 | 14 | So that expression tests if a number is NOT a power of 2. 15 | 16 | ```` 17 | 18 | Reference: 19 | [Stack overflow](http://stackoverflow.com/questions/1053582/how-does-this-bitwise-operation-check-for-a-power-of-2) -------------------------------------------------------------------------------- /Swift/Chapter 5/Question-5/Question.swift: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function to determine the number of bits required to convert integer A to integer B 3 | Input: 31, 14 Output: 2 4 | */ 5 | 6 | import Cocoa 7 | /* 8 | @param: a:Int Input first 9 | @param: b:Int Input Two 10 | @return Int Number of bit changes required 11 | */ 12 | 13 | func bitsRequiredToConvertAtoB(a:Int, b:Int) -> Int { //O(number of resulting bits in a ^ b) 14 | return numberOf1(a ^ b) 15 | } 16 | 17 | /* 18 | @param: c:Int Input Number 19 | @return: returns the number of 1's present in the binary representation of the number 20 | */ 21 | func numberOf1(var c:Int) -> Int { //O(number of bits in c) 22 | var count = 0 23 | while(c != 0) { 24 | if ((c & 1) == 1 ) { 25 | count++ 26 | } 27 | c = c >> 1 28 | } 29 | return count 30 | } 31 | 32 | //tested in Playground 33 | //bitsRequiredToConvertAtoB(31, 30) 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Swift/Chapter 5/Question-5/README.md: -------------------------------------------------------------------------------- 1 | ## Question 5_5 2 | ``` 3 | Write a function to determine the number of bits required to convert integer A to integer B 4 | Input: 31, 14 Output: 2 5 | 6 | ``` 7 | 8 | ###Algorithm: 9 | Step 1: 10 | ``` 11 | XOR the two inputs and get the result 12 | ``` 13 | 14 | Step 2: 15 | ``` 16 | Count the number of 1's in the number. This is the result 17 | ``` 18 | -------------------------------------------------------------------------------- /Swift/Chapter 5/Question-6/Question.swift: -------------------------------------------------------------------------------- 1 | 2 | 3 | // Author: Prakash Natarajan (c) 2014 4 | // Email: nprakashece@gmail.com | pn33@buffalo.edu 5 | // License: GNU GPLv3 6 | 7 | import UIKit 8 | 9 | class Question5_6 { 10 | func swapOddEvenBits(var x:Int) -> Int { 11 | // 0x55555555 = 1431655765 for even place masking 12 | // 0xaaaaaaaa = 2863311530 for odd place masking 13 | return ( ((x & 2863311530) >> 1) | ((x & 1431655765) << 1) ) 14 | } 15 | } 16 | 17 | var pgm = Question5_6() 18 | String(103217, radix:2) 19 | var res = pgm.swapOddEvenBits(103217) 20 | String(res, radix:2) 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Swift/Chapter 5/Question-6/README.md: -------------------------------------------------------------------------------- 1 | ## Question 5_6 2 | ``` 3 | Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit! are swapped, bit 2 and bit 3 are swapped, and soon) 4 | 5 | ``` 6 | 7 | 8 | -------------------------------------------------------------------------------- /Swift/README.md: -------------------------------------------------------------------------------- 1 | ## INTRODUCTION 2 | ------------ 3 | 4 | Cracking the Coding Interview with Apple Swift. 5 | Buy the book and support the author. [Cracking the Coding Interview](http://www.amazon.com/dp/098478280X/) 6 | 7 | ## Respect the stack 8 | If you want to contribute, respect these rules : 9 | - One folder for each chapter called `Chapter X`. 10 | - Create One playground file calle `Chapter X`. 11 | - Implement each question under a `// MARK: ` 12 | - Use extension for each question when this is possible 13 | - Implement a simple exemple below each question 14 | 15 | ## TODO 16 | ---- 17 | - Chapter 2 - WIP 18 | - Chapter 3 19 | - Chapter 4 20 | - Chapter 6 21 | - Chapter 7 22 | - Chapter 8 23 | - Chapter 9 24 | - Chapter 10 25 | - Chapter 11 26 | - Chapter 12 27 | - Chapter 13 28 | - Chapter 14 29 | - Chapter 15 30 | - Chapter 16 31 | - Chapter 17 32 | - Chapter 18 - WIP 33 | 34 | 35 | -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_1/Question1_1.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_1_h__ 2 | #define __Question_1_1_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question1_1 9 | { 10 | public: 11 | int run(); 12 | bool isUniqueChars(const string& str); 13 | bool isUniqueChars2(const string& str); 14 | string result(bool value); 15 | }; 16 | 17 | #endif // __Question_1_1_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_2/Question1_2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Question1_2.h" 3 | 4 | using std::cout; 5 | using std::endl; 6 | 7 | void Question1_2::reverse(char* str) 8 | { 9 | char *ptrEnd = str; 10 | char temp; 11 | 12 | if (str) 13 | { 14 | while (*ptrEnd) 15 | { 16 | ptrEnd++; 17 | } 18 | ptrEnd--; 19 | 20 | while (str < ptrEnd) 21 | { 22 | temp = *str; 23 | *str++ = *ptrEnd; 24 | *ptrEnd-- = temp; 25 | } 26 | } 27 | } 28 | 29 | int Question1_2::run() 30 | { 31 | char input[][10] = { "abcde", "cat" }; 32 | 33 | for (int i = 0; i < 2; i++) 34 | { 35 | cout << "reversing the string: " << input[i] << endl; 36 | reverse(input[i]); 37 | cout << "reverse of input string is " << input[i] << endl; 38 | } 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_2/Question1_2.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_2_h__ 2 | #define __Question_1_2_h__ 3 | 4 | class Question1_2 5 | { 6 | public: 7 | int run(); 8 | void reverse(char* str); 9 | }; 10 | 11 | #endif // __Question_1_2_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_3/Question1_3.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_3_h__ 2 | #define __Question_1_3_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question1_3 9 | { 10 | public: 11 | int run(); 12 | bool permutation(const string& a, const string& b); 13 | string result(bool value); 14 | }; 15 | 16 | 17 | 18 | #endif // __Question_1_3_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_3/Question1_3_B.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_3_B_h__ 2 | #define __Question_1_3_B_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question1_3_B 9 | { 10 | public: 11 | int run(); 12 | bool permutation(const string& a, const string& b); 13 | string result(bool value); 14 | }; 15 | 16 | 17 | 18 | #endif // __Question_1_3_B_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_4/Question1_4.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_4_h__ 2 | #define __Question_1_4_h__ 3 | #include 4 | 5 | class Question1_4 6 | { 7 | public: 8 | int run(); 9 | void replaceSpaces(std::unique_ptr&, int length); 10 | }; 11 | 12 | #endif // __Question_1_4_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_5/Question1_5.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_5_h__ 2 | #define __Question_1_5_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question1_5 9 | { 10 | public: 11 | int run(); 12 | int stringToInt(const string& value); 13 | string intToString(int value); 14 | int countCompression(const string& str); 15 | 16 | /// C++ std::string is efficient and no need to use a "StringBuffer"-like structure. 17 | string compressBetter(const string& str); 18 | }; 19 | 20 | 21 | 22 | #endif // __Question_1_5_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_6/Question1_6.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_6_h__ 2 | #define __Question_1_6_h__ 3 | 4 | class Question1_6 5 | { 6 | public: 7 | /** 8 | * Since we can't provide variable matrix size in C++, we will do it "the c way" and will provide a 1-dimensional 9 | * array 10 | */ 11 | void rotate(int* matrix, int n); 12 | void printMatrix(int* matrix, int m, int n); 13 | int run(); 14 | }; 15 | 16 | #endif // __Question_1_6_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_7/Question1_7.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_7_h__ 2 | #define __Question_1_7_h__ 3 | 4 | class Question1_7 5 | { 6 | public: 7 | /** 8 | * Since we can't provide variable matrix size in C++, we will do it "the c way" and will provide a 1-dimensional 9 | * array 10 | */ 11 | void setZeros(int* matrix, int m, int n); 12 | void printMatrix(int* matrix, int m, int n); 13 | int run(); 14 | }; 15 | 16 | #endif // __Question_1_7_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question1_8/Question1_8.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_1_8_h__ 2 | #define __Question_1_8_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question1_8 9 | { 10 | public: 11 | string result(bool value); 12 | bool isRotation(const string& s1, const string& s2); 13 | int run(); 14 | }; 15 | 16 | #endif // __Question_1_8_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question2_1.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_2_1_h__ 2 | #define __Question_2_1_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question2_1 9 | { 10 | public: 11 | int run(); 12 | }; 13 | 14 | #endif // __Question_2_1_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question2_2.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_2_2_h__ 2 | #define __Question_2_2_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question2_2 9 | { 10 | public: 11 | int run(); 12 | }; 13 | 14 | #endif // __Question_2_2_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question2_3.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_2_3_h__ 2 | #define __Question_2_3_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question2_3 9 | { 10 | public: 11 | int run(); 12 | }; 13 | 14 | #endif // __Question_2_3_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question2_4.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_2_4_h__ 2 | #define __Question_2_4_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question2_4 9 | { 10 | public: 11 | int run(); 12 | }; 13 | 14 | #endif // __Question_2_4_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question2_5.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_2_5_h__ 2 | #define __Question_2_5_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question2_5 9 | { 10 | public: 11 | int run(); 12 | }; 13 | 14 | #endif // __Question_2_5_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question2_6.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_2_6_h__ 2 | #define __Question_2_6_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question2_6 9 | { 10 | public: 11 | int run(); 12 | }; 13 | 14 | #endif // __Question_2_6_h__ -------------------------------------------------------------------------------- /c++/Chapter 1/Question2_7.h: -------------------------------------------------------------------------------- 1 | #ifndef __Question_2_7_h__ 2 | #define __Question_2_7_h__ 3 | 4 | #include 5 | 6 | using std::string; 7 | 8 | class Question2_7 9 | { 10 | public: 11 | int run(); 12 | }; 13 | 14 | #endif // __Question_2_7_h__ -------------------------------------------------------------------------------- /c++/Chapter 11/Chapter11_1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void merge(int a[], int lastA, int b[], int lastB) { 5 | int index = lastB + lastA + 1; 6 | while(index >= 0) { 7 | if (a[lastA] > b[lastB]) { 8 | a[index] = a[lastA]; 9 | lastA--; 10 | } 11 | else { 12 | a[index] = b[lastB]; 13 | lastB--; 14 | } 15 | index--; 16 | } 17 | } 18 | 19 | int main(){ 20 | 21 | int a[13] = {0, 4, 14, 23, 29, 30, 31}; 22 | int b[] = {6, 7, 29, 31, 100, 200}; 23 | merge(a, 6, b, 5); 24 | for (int i = 0; i < 13; ++i) { 25 | cout< 2 | #include "Chapter11.h" 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | typedef map > mvs; 8 | 9 | void sortAnagramWise(string arr[], int n){ 10 | mvs Map; 11 | for(int i=0; i tmp = iter->second; 20 | for (int i = 0; i < tmp.size(); ++i) { 21 | arr[ind]=tmp[i]; 22 | ind++; 23 | } 24 | } 25 | } 26 | 27 | int main(){ 28 | string arr[] = {"abc", "bca", "aaaa", "abccde", "edbcac", "cbed", "cdeb"}; 29 | sortAnagramWise(arr, 7); 30 | for (int i = 0; i < 7; ++i) 31 | cout< 2 | using namespace std; 3 | 4 | int search(string arr[], int low, int high, string str){ 5 | int mid = (low+high)/2; 6 | if(arr[mid]==str) 7 | return mid; 8 | if(low >= high) 9 | return -1; 10 | if(arr[mid] == ""){ 11 | int i=1; 12 | while(mid-i >= low || mid+i <= high){ 13 | if(mid-i >= low && arr[mid-i] != "" && arr[mid-i] >= str) 14 | return search(arr, low, mid-i, str); 15 | if(mid+i <= high && arr[mid+i] != "" && arr[mid+i] <= str) 16 | return search(arr, mid+i, high, str); 17 | i++; 18 | } 19 | } 20 | else { 21 | if (arr[mid] < str) 22 | return search(arr, mid+1, high, str); 23 | else 24 | return search(arr, low, mid-1, str); 25 | } 26 | return -1; 27 | } 28 | 29 | int main(){ 30 | string arr[] = {"abc", "", "", "", "ball", "cat", "", "dog", "elephant", "fox", "", "", "", "goat"}; 31 | cout< 2 | using namespace std; 3 | 4 | struct node { 5 | int data; 6 | node* right; 7 | node* left; 8 | int leftSize; 9 | }; 10 | 11 | void track(int k, node* &root){ 12 | if (root == NULL) { 13 | root = new node; 14 | root->data = k; 15 | root->right = root->left = NULL; 16 | root->leftSize = 0; 17 | } 18 | else { 19 | if (root->data > k) { 20 | root->leftSize++; 21 | track(k, root->left); 22 | } 23 | else 24 | track(k, root->right); 25 | } 26 | } 27 | 28 | int getRank(int x, node* root) { 29 | int data = root->data; 30 | if (data == x) 31 | return root->leftSize; 32 | if (data > x) 33 | return getRank(x, root->left); 34 | else { 35 | return root->leftSize + 1 + getRank(x, root->right); 36 | } 37 | } 38 | 39 | int main(){ 40 | node *root = NULL; 41 | int arr[] = {12, 15, 12, 11, 10, 10, 11, 10}; 42 | for (int i = 0; i < 8; ++i) { 43 | track(arr[i], root); 44 | } 45 | cout< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class stackWithMin{ 7 | private: 8 | stack s1, s2; 9 | 10 | public: 11 | void push(int x){ 12 | s1.push(x); 13 | if(min()>=x){ 14 | s2.push(x); 15 | } 16 | } 17 | void pop(){ 18 | if(min()==s1.top()){ 19 | s2.pop(); 20 | } 21 | s1.pop(); 22 | } 23 | int min(){ 24 | if(s2.empty()){ 25 | return INT_MAX; 26 | } 27 | return s2.top(); 28 | } 29 | bool empty(){ 30 | return s1.empty(); 31 | } 32 | int top(){ 33 | return s1.top(); 34 | } 35 | }; 36 | 37 | int main(){ 38 | stackWithMin myStack; 39 | int arr[] = {6, 3, 5, 2, 2, 9, 2, 8, 1, 1}; 40 | for(int i=0; i<10; i++){ 41 | myStack.push(arr[i]); 42 | cout< 2 | #include 3 | using namespace std; 4 | 5 | void towerOfHanoi(stack *a, stack *buff, stack *dest, int n){ 6 | if(n==0){ 7 | return; 8 | } 9 | towerOfHanoi(a, dest, buff, n-1); 10 | (*dest).push((*a).top()); 11 | (*a).pop(); 12 | towerOfHanoi(buff, a, dest, n-1); 13 | } 14 | 15 | int main(){ 16 | stack primary, buffer, destination; 17 | int n = 10; 18 | for(int i=n; i>0; i--) 19 | primary.push(i); 20 | towerOfHanoi(&primary, &buffer, &destination, 10); 21 | while(!destination.empty()){ 22 | cout< 2 | #include 3 | using namespace std; 4 | 5 | void sortStack(stack *st){ 6 | stack sorted; //top contains smallest element 7 | while(!(*st).empty()){ 8 | int tmp = (*st).top(); 9 | (*st).pop(); 10 | while(!sorted.empty() && tmp>sorted.top()){ 11 | (*st).push(sorted.top()); 12 | sorted.pop(); 13 | } 14 | sorted.push(tmp); 15 | } 16 | while(!sorted.empty()){ 17 | (*st).push(sorted.top()); 18 | sorted.pop(); 19 | } 20 | } 21 | 22 | int main(){ 23 | stack my; 24 | int arr[] = {6, 4, 8, 9, 10, 99, 7, 1, 0}; 25 | for(int i=0; i 2 | using namespace std; 3 | 4 | struct node{ 5 | int data; 6 | node *right, *left; 7 | }; 8 | 9 | void createBst(node* &root, int arr[], int start, int end){ 10 | if(start>end) 11 | return; 12 | if(root==NULL){ 13 | node *ptr = new node; 14 | int ind = start + (end-start)/2; 15 | ptr->data = arr[ind]; 16 | ptr->left = NULL; 17 | ptr->right = NULL; 18 | root = ptr; 19 | createBst(root->left, arr, start, ind-1); 20 | createBst(root->right, arr, ind+1, end); 21 | } 22 | } 23 | 24 | int main(){ 25 | int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 26 | node* root; 27 | root = NULL; 28 | createBst(root, arr, 0, 8); 29 | cout<left->data<<" "<data<<" "<right->data<<'\n'; 30 | } 31 | -------------------------------------------------------------------------------- /c++/Chapter 5/Question5_2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | string decimalToBinary(double a){ 6 | if(a<0 || a>= 1) 7 | return "ERROR!"; 8 | string res=""; 9 | res = res + "0."; 10 | while(a>0){ 11 | if(res.length()>32){ 12 | return "ERROR!"; 13 | } 14 | a *=2; 15 | if(a>=1){ 16 | res =res+"1"; 17 | a -=1.0; 18 | } 19 | else{ 20 | res = res+"0"; 21 | } 22 | } 23 | return res; 24 | } 25 | 26 | int main(){ 27 | 28 | double a = 0.125; 29 | cout< 2 | #include 3 | using namespace std; 4 | 5 | int noOfBits(int a, int b){ 6 | int len = 32; 7 | int count=0; 8 | while(len--){ 9 | if((a&1) != (b&1)) 10 | count++; 11 | a >>=1; 12 | b >>=1; 13 | } 14 | return count; 15 | } 16 | 17 | int noOfBits1(int a, int b){ 18 | int count = 0; 19 | for(int i=a^b; i != 0; i >>=1){ 20 | count += (i&1); 21 | } 22 | return count; 23 | } 24 | 25 | int main(){ 26 | int a = 9456; 27 | int b = 12000; 28 | cout< 2 | using namespace std; 3 | 4 | void printBinary(int n){ 5 | int arr[32]; 6 | int len = 8*sizeof(n); 7 | int mask = 1; 8 | int index = 0; 9 | while(len--){ 10 | if(n&mask) 11 | arr[index] = 1; 12 | else 13 | arr[index] = 0; 14 | index++; 15 | mask <<= 1; 16 | } 17 | for(int i=31; i>=0; i--){ 18 | cout<>=1; 29 | evenBits <<=1; //Swaping possitions 30 | return (oddBits|evenBits); 31 | } 32 | 33 | int main(){ 34 | int a = 0xaaaaaaa; 35 | printBinary(a); 36 | printBinary(swapOddEven(a)); 37 | } -------------------------------------------------------------------------------- /c++/Chapter 5/Question5_7.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int fetchBit(int bit, int no){ 5 | no >>=bit; 6 | return (no&1); 7 | } 8 | 9 | int findMissingUtils(int A[], int n, int col){ 10 | if(n <2){ 11 | return 0; 12 | } 13 | int b0[(n/2)+1], b1[(n/2)+1]; 14 | int count0 = 0; 15 | int count1 = 0; 16 | for(int i=0; i 2 | using namespace std; 3 | 4 | 5 | 6 | int main(){ 7 | 8 | return 0; 9 | } -------------------------------------------------------------------------------- /c++/Chapter 9/Question9_1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int noOfSteps(int n, int arr[]){ 5 | if(arr[n]) 6 | return arr[n]; 7 | if(n<4){ 8 | if(n==1) 9 | arr[n] = 1; 10 | else if(n==2){ 11 | arr[2] = 2; 12 | } 13 | else if(n==3){ 14 | arr[3] = 4; 15 | } 16 | } 17 | else 18 | arr[n] = noOfSteps(n-1, arr) + noOfSteps(n-2, arr) + noOfSteps(n-3, arr); 19 | return arr[n]; 20 | } 21 | 22 | int main(){ 23 | int n = 36; 24 | int arr[n+1] = {-1}; 25 | cout< 2 | #include 3 | using namespace std; 4 | 5 | void printSubset(vector > &subset, int arr[], int n){ 6 | if(n<0) 7 | return; 8 | printSubset(subset, arr, n-1); 9 | int m = subset.size(); 10 | for (int i=0; i < m; i++){ 11 | vector v; 12 | for (int j = 0; j < subset[i].size(); j++){ 13 | v.push_back(subset[i][j]); 14 | } 15 | v.push_back(arr[n]); 16 | subset.push_back(v); 17 | } 18 | vector v; 19 | v.push_back(arr[n]); 20 | subset.push_back(v); 21 | } 22 | int main(){ 23 | int arr[] = {1, 2, 3, 6}; 24 | vector > subset; 25 | printSubset(subset, arr, 3); 26 | for (int i=0; i < subset.size(); i++){ 27 | for (int j = 0; j < subset[i].size(); j++){ 28 | cout< 2 | #include 3 | using namespace std; 4 | 5 | typedef vector vStr; 6 | 7 | vStr printPermutation(string str){ 8 | vStr v, vs; 9 | if(str.length()==0){ 10 | vs.push_back(""); 11 | return vs; 12 | } 13 | string a = str.substr(0, 1); 14 | string b; 15 | v = printPermutation(str.substr(1)); 16 | for (int i= 0; i < v.size(); ++i){ 17 | for (int j = 0; j <= v[i].length(); ++j) { 18 | b = v[i].substr(0, j) + a + v[i].substr(j); 19 | vs.push_back(b); 20 | } 21 | } 22 | return vs; 23 | } 24 | 25 | 26 | int main(){ 27 | string str = "abcd"; 28 | vStr res; 29 | res = printPermutation(str); 30 | for (int i = 0; i < res.size(); ++i) { 31 | cout< 2 | #include 3 | using namespace std; 4 | 5 | typedef vector vStr; 6 | 7 | void generateParen(string str, int left, int right){ 8 | if (left == 0 && right == 0) { 9 | //It can be stored into some variable here 10 | cout<> 1) | ((x & 0x55555555) << 1)); 13 | } 14 | 15 | public void Run() 16 | { 17 | var a = 103217; 18 | Console.WriteLine(a + ": " + AssortedMethods.ToFullBinarystring(a)); 19 | var b = SwapOddEvenBits(a); 20 | Console.WriteLine(b + ": " + AssortedMethods.ToFullBinarystring(b)); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /c-sharp/Chapter18/Q18_11.cs: -------------------------------------------------------------------------------- 1 |  2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | using ctci.Contracts; 7 | using ctci.Library; 8 | 9 | namespace Chapter18 10 | { 11 | public class Q18_11 : IQuestion 12 | { 13 | public void Run() 14 | {} 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /c-sharp/Chapter18/Q18_2.cs: -------------------------------------------------------------------------------- 1 |  2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | using ctci.Contracts; 7 | using ctci.Library; 8 | 9 | namespace Chapter18 10 | { 11 | public class Q18_2 : IQuestion 12 | { 13 | public void Run() 14 | {} 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /c-sharp/Chapter18/Q18_9.cs: -------------------------------------------------------------------------------- 1 |  2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | using ctci.Contracts; 7 | using ctci.Library; 8 | using System.Collections; 9 | 10 | namespace Chapter18 11 | { 12 | public class Q18_9 : IQuestion 13 | { 14 | public void Run() 15 | {} 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /c-sharp/ctci.Contracts/IQuestion.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ctci.Contracts 3 | { 4 | public interface IQuestion 5 | { 6 | void Run(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /clojure/chapter01/01_02.clj: -------------------------------------------------------------------------------- 1 | ; Clojure solution to question 1.2 from Cracking the Coding Interview, 5th Edition. 2 | ; Nitin Punjabi 3 | ; github.com/nitinpunjabi 4 | ; nitin@patternhatch.com 5 | (ns chapter01.01-02 6 | (:require [clojure.test :as t])) 7 | 8 | (defn core-reverse-str 9 | "Reverse using Clojure's core function." 10 | [s] 11 | (apply str (reverse s))) 12 | 13 | (defn lib-reverse-str 14 | "Reverse using clojure.string's reverse function which uses StringBuilder's reverse function internally." 15 | [s] 16 | (clojure.string/reverse s)) 17 | 18 | (t/deftest core-reverse-test 19 | (t/is (= (core-reverse-str "") "")) 20 | (t/is (= (core-reverse-str "a") "a")) 21 | (t/is (= (core-reverse-str "ab") "ba")) 22 | (t/is (= (core-reverse-str "ab ") " ba"))) 23 | 24 | (t/deftest lib-reverse-test 25 | (t/is (= (lib-reverse-str "") "")) 26 | (t/is (= (lib-reverse-str "a") "a")) 27 | (t/is (= (lib-reverse-str "ab") "ba")) 28 | (t/is (= (lib-reverse-str "ab ") " ba"))) -------------------------------------------------------------------------------- /clojure/chapter01/01_05.clj: -------------------------------------------------------------------------------- 1 | ; Clojure solution to question 1.5 from Cracking the Coding Interview, 5th Edition. 2 | ; Nitin Punjabi 3 | ; github.com/nitinpunjabi 4 | ; nitin@patternhatch.com 5 | (ns chapter01.01-05 6 | (:require [clojure.test :as t])) 7 | 8 | (defn compress [s] 9 | (let [parts (partition-by identity s) 10 | compressed-str (clojure.string/join (reduce #(conj % (first %2) (count %2)) [] parts))] 11 | (if (<= (count s) (count compressed-str)) 12 | s 13 | compressed-str))) 14 | 15 | (t/deftest compression-results 16 | (t/is (= (compress "aabcccccaaa") "a2b1c5a3")) 17 | (t/is (= (compress "aabc aaa") "a2b1c1 4a3")) 18 | (t/is (= (compress "abc") "abc")) 19 | (t/is (= (compress "a") "a")) 20 | (t/is (= (compress "") ""))) -------------------------------------------------------------------------------- /dart/Chapter1/Question1_2/question.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * Implement a function void reverse(char* str) in C or C++ 3 | * which reverses a null-terminated string 4 | */ 5 | 6 | /* This is a classic interview question. 7 | * The only "gotcha" is to try to do it inplace, 8 | * and be careful for the null character. 9 | */ 10 | /* 11 | void reverse(char *str) { 12 | char* end = str; 13 | char tmp; 14 | if (str) { 15 | while (*end) { /* find end of the string */ 16 | ++end; 17 | } 18 | 19 | --end; /* set one char back, since last char is null */ 20 | 21 | /* 22 | * swap characters from start of string with the end of 23 | * the string, until the pointers meet in the middle. 24 | */ 25 | while (str < end) { 26 | tmp = *str; 27 | *str++ = *end; 28 | *end-- = tmp; 29 | } 30 | } 31 | } 32 | */ -------------------------------------------------------------------------------- /dart/Chapter11/Question11_2/question.dart: -------------------------------------------------------------------------------- 1 | class AnagramComparator { 2 | static String sortChars(String s) { 3 | List content = s.split(''); 4 | content.sort(); 5 | return content.join(''); 6 | } 7 | 8 | static int compare(String s1, String s2) { 9 | return sortChars(s1).compareTo(sortChars(s2)); 10 | } 11 | } 12 | 13 | void main() { 14 | List array = ["apple", "banana", "carrot", "ele", "duck", "papel", "tarroc", "cudk", "eel", "lee"]; 15 | print(array); 16 | array.sort(AnagramComparator.compare); 17 | print(array); 18 | } -------------------------------------------------------------------------------- /dart/Chapter11/Question11_6/question.dart: -------------------------------------------------------------------------------- 1 | import '../../utils/assorted_methods.dart'; 2 | bool findElement(List> matrix, int elem) { 3 | int row = 0; 4 | int col = matrix[0].length - 1; 5 | while (row < matrix.length && col >= 0) { 6 | if (matrix[row][col] == elem) { 7 | return true; 8 | } else if (matrix[row][col] > elem) { 9 | col--; 10 | } else { 11 | row++; 12 | } 13 | } 14 | 15 | return false; 16 | } 17 | 18 | void main() { 19 | 20 | int M = 10; 21 | int N = 5; 22 | List> matrix = new List>(M); 23 | for (int i = 0; i < M; i++) { 24 | matrix[i] = new List(N); 25 | for (int j = 0; j < N; j++) { 26 | matrix[i][j] = 10 * i + j; 27 | } 28 | } 29 | 30 | printIntMatrix(matrix); 31 | 32 | for (int i = 0; i < M; i++) { 33 | for (int j = 0; j < M; j++) { 34 | int v = 10 * i + j; 35 | print("$v: ${findElement(matrix, v)}"); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /dart/Chapter17/Question17_1/question.dart: -------------------------------------------------------------------------------- 1 | 2 | void swap(int a, int b) { 3 | // Example for a = 9, b = 4 4 | a = a - b; // a = 9 - 4 = 5 5 | b = a + b; // b = 5 + 4 = 9 6 | a = b - a; // a = 9 - 5 7 | 8 | print("a: $a"); 9 | print("b: $b"); 10 | } 11 | 12 | void swap_opt(int a, int b) { 13 | a = a^b; 14 | b = a^b; 15 | a = a^b; 16 | 17 | print("a: $a"); 18 | print("b: $b"); 19 | } 20 | 21 | void main() { 22 | int a = 1672; 23 | int b = 9332; 24 | 25 | print("a: $a"); 26 | print("b: $b"); 27 | 28 | //swap(a, b); 29 | swap_opt(a, b); 30 | } 31 | 32 | -------------------------------------------------------------------------------- /dart/Chapter17/Question17_11/question.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | Random random = new Random(); 4 | 5 | int rand7() { 6 | while(true) { 7 | int n = 5 * rand5() + rand5(); 8 | if (n < 21) { 9 | return n % 7; 10 | } 11 | } 12 | } 13 | 14 | int rand5() { 15 | return ((random.nextDouble() * 100) % 5).toInt(); 16 | } 17 | 18 | void main() { 19 | /* 20 | * Test: call rand7 many times and inspect the results; 21 | */ 22 | List arr = new List.fixedLength(7, fill: 0); 23 | 24 | int test_size = 1000000; 25 | for (int k = 0; k < test_size; k++) { 26 | arr[rand7()]++; 27 | } 28 | 29 | for (int i = 0; i < 7; i++) { 30 | double percent = 100.0 * arr[i] / test_size; 31 | print ("$i appeared $percent% of the time."); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /dart/Chapter17/Question17_12/question.dart: -------------------------------------------------------------------------------- 1 | 2 | void printPairSums(List array, int sum) { 3 | array.sort(); 4 | 5 | int first = 0; 6 | int last = array.length - 1; 7 | while (first < last) { 8 | int s = array[first] + array[last]; 9 | if (s == sum) { 10 | print("${array[first]} ${array[last]}"); 11 | ++first; 12 | --last; 13 | } else { 14 | if (s < sum) { 15 | ++first; 16 | } else { 17 | --last; 18 | } 19 | } 20 | } 21 | } 22 | 23 | void main() { 24 | List test = [9, 3, 6, 5, 7, -1, 13, 14, -2, 12, 0]; 25 | printPairSums(test, 12); 26 | } 27 | 28 | -------------------------------------------------------------------------------- /dart/Chapter17/Question17_13/bi_node.dart: -------------------------------------------------------------------------------- 1 | library binode; 2 | 3 | class BiNode { 4 | BiNode node1; 5 | BiNode node2; 6 | int data; 7 | BiNode(this.data); 8 | } 9 | 10 | -------------------------------------------------------------------------------- /dart/Chapter17/Question17_2/question.dart: -------------------------------------------------------------------------------- 1 | int convertBoardToInt(List> board) { 2 | int factor = 1; 3 | int sum = 0; 4 | for (int i = 0; i < board.length; i++) { 5 | for (int j = 0; j < board[i].length; j++) { 6 | int v = 0; 7 | if (board[i][j] == 'x') { 8 | v = 1; 9 | } else if (board[i][j] == 'o') { 10 | v = 2; 11 | } 12 | 13 | sum += v * factor; 14 | factor *= 3; 15 | } 16 | } 17 | 18 | return sum; 19 | } 20 | 21 | void main() { 22 | List> board = [ 23 | ['x', 'x', 'o'], 24 | [' ', 'x', ' '], 25 | [' ', ' ', 'x'] 26 | ]; 27 | int v = convertBoardToInt(board); 28 | print(v); 29 | } -------------------------------------------------------------------------------- /dart/Chapter17/Question17_3/questionA.dart: -------------------------------------------------------------------------------- 1 | 2 | int factorsOf5(int i) { 3 | int count = 0; 4 | while (i % 5 == 0) { 5 | count++; 6 | i ~/= 5; 7 | } 8 | return count; 9 | } 10 | 11 | int countFactZeros(int n) { 12 | int count = 0; 13 | for (int i = 2; i <= n; i++) { 14 | count += factorsOf5(i); 15 | } 16 | 17 | return count; 18 | } 19 | 20 | int factorial(int n) { 21 | if (n == 1) { 22 | return 1; 23 | } else if (n > 1) { 24 | return n * factorial(n - 1); 25 | } else { 26 | return -1; // Error; 27 | } 28 | } 29 | 30 | void main() { 31 | for (int i = 1; i < 12; i++) { 32 | print("$i! (or ${factorial(i)}) has ${countFactZeros(i)} zeros"); 33 | } 34 | } -------------------------------------------------------------------------------- /dart/Chapter17/Question17_3/questionB.dart: -------------------------------------------------------------------------------- 1 | 2 | int countFactZeros(int n) { 3 | int count = 0; 4 | if (n < 0) { 5 | print("Factorial is not defined for negative numbers"); 6 | return 0; 7 | } 8 | 9 | for (int i = 5; n ~/ i > 0; i *= 5) { 10 | count += n ~/ i; 11 | } 12 | 13 | return count; 14 | } 15 | 16 | int factorial(int n) { 17 | if (n == 1) { 18 | return 1; 19 | } else if (n > 1) { 20 | return n * factorial(n - 1); 21 | } else { 22 | return -1; // Error; 23 | } 24 | } 25 | 26 | void main() { 27 | for (int i = 0; i < 12; i++) { 28 | print("$i! (or ${factorial(i)}) has ${countFactZeros(i)} zeros"); 29 | } 30 | } -------------------------------------------------------------------------------- /dart/Chapter17/Question17_8/question.dart: -------------------------------------------------------------------------------- 1 | 2 | int getMaxSum(List a) { 3 | int maxSum = 0; 4 | int runningSum = 0; 5 | for (int i = 0; i < a.length; i++) { 6 | runningSum += a[i]; 7 | if (maxSum < runningSum) { 8 | maxSum = runningSum; 9 | } else if (runningSum < 0) { 10 | runningSum = 0; 11 | } 12 | } 13 | 14 | return maxSum; 15 | } 16 | 17 | void main() { 18 | List a = [2, -8, 3, -2, 4, -10]; 19 | print(getMaxSum(a)); 20 | } 21 | 22 | -------------------------------------------------------------------------------- /dart/Chapter18/Question18_1/question.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | Random random = new Random(); 4 | 5 | int add(int a, int b) { 6 | if (b == 0) return a; 7 | 8 | int sum = a ^ b; // Add without carrying 9 | int carry = (a & b) << 1; // carry, but don't add 10 | return add(sum, carry); 11 | } 12 | 13 | int randomInt(int n) { 14 | return (random.nextDouble() * n).toInt(); 15 | } 16 | 17 | void main() { 18 | for (int i = 0; i < 100; i++) { 19 | int a = randomInt(10); 20 | int b = randomInt(10); 21 | int sum = add(a, b); 22 | print("$a + $b = $sum"); 23 | assert(sum == a + b); 24 | } 25 | } -------------------------------------------------------------------------------- /dart/Chapter18/Question18_11/square_cell.dart: -------------------------------------------------------------------------------- 1 | library SquareCell; 2 | 3 | class SquareCell { 4 | int zerosRight = 0; 5 | int zerosBelow = 0; 6 | SquareCell(this.zerosRight, this.zerosBelow); 7 | } 8 | 9 | -------------------------------------------------------------------------------- /dart/Chapter18/Question18_11/subsquare.dart: -------------------------------------------------------------------------------- 1 | library Subsquare; 2 | 3 | class Subsquare { 4 | int row, column, size; 5 | Subsquare(this.row, this.column, this.size); 6 | String toString() => "($row, $column, $size)"; 7 | } 8 | 9 | -------------------------------------------------------------------------------- /dart/Chapter18/Question18_2/question.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | Random random = new Random(); 4 | 5 | void shuffleArray(List cards) { 6 | int temp; 7 | int index; 8 | for (int i = 0; i < cards.length; i++) { 9 | index = (random.nextDouble() * (cards.length - i)).toInt() + i; 10 | temp = cards[i]; 11 | cards[i] = cards[index]; 12 | cards[index] = temp; 13 | } 14 | } 15 | 16 | void main() { 17 | List cards = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; 18 | print(cards); 19 | shuffleArray(cards); 20 | print(cards); 21 | } -------------------------------------------------------------------------------- /dart/Chapter18/Question18_3/question.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | Random random = new Random(); 4 | 5 | /* Random number between lower and higher, inclusive */ 6 | int rand(int lower, int higher) { 7 | return lower + (random.nextDouble() * (higher - lower + 1)).toInt(); 8 | } 9 | 10 | /* 11 | * pick M elements from original array. Clone original array so that 12 | * we don't destory the input. 13 | */ 14 | List pickMRandomly(List original, int m) { 15 | List subset = new List(m); 16 | List array = new List.from(original); 17 | 18 | for (int j = 0; j < m; j++) { 19 | int index = rand(j, array.length - 1); 20 | subset[j] = array[index]; 21 | array[index] = array[j]; // array[j] is now "Dead" 22 | } 23 | 24 | return subset; 25 | } 26 | 27 | void main() { 28 | List cards = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; 29 | print(cards); 30 | List s = pickMRandomly(cards, 4); 31 | print(s); 32 | } 33 | -------------------------------------------------------------------------------- /dart/Chapter18/Question18_4/questionBrute.dart: -------------------------------------------------------------------------------- 1 | 2 | int numberOf2s(int n) { 3 | int count = 0; 4 | while (n > 0) { 5 | if (n % 10 == 2) { 6 | count++; 7 | } 8 | 9 | n = n ~/ 10; 10 | } 11 | 12 | return count; 13 | } 14 | 15 | int numberOf2sInRange(int n) { 16 | int count = 0; 17 | for (int i = 2; i <= n; i++) { // Might as well start at 2; 18 | count += numberOf2s(i); 19 | } 20 | 21 | return count; 22 | } 23 | 24 | void main() { 25 | for (int i = 0; i < 1000; i++) { 26 | int v = numberOf2sInRange(i); 27 | print("Between 0 and $i: $v"); 28 | } 29 | } -------------------------------------------------------------------------------- /dart/Chapter2/Question2_3/question.dart: -------------------------------------------------------------------------------- 1 | /* 2 | * Implement an algorithm to delete a node in the middle of a 3 | * singly linked list, given only access to that node. 4 | * EXAMPLE 5 | * Input: the node c from the linked list a->b->c->d->e 6 | * Result: nothing is returned, but the new linked list looks like 7 | * a->b->d->e 8 | */ 9 | import '../../utils/linked_list_node.dart'; 10 | import '../../utils/assorted_methods.dart'; 11 | 12 | bool deleteNode(LinkedListNode n) { 13 | if (n == null || n.next == null) { 14 | return false; // Failure 15 | } 16 | 17 | LinkedListNode next = n.next; 18 | n.data = next.data; 19 | n.next = next.next; 20 | return true; 21 | } 22 | 23 | void main() { 24 | LinkedListNode head = randomLinkedList(10, 0, 10); 25 | print(head.printFoward()); 26 | deleteNode(head.next.next.next.next); 27 | print(head.printFoward()); 28 | } -------------------------------------------------------------------------------- /dart/Chapter3/Question3_6/question.dart: -------------------------------------------------------------------------------- 1 | 2 | List sort(List s) { 3 | List r = new List(); 4 | while (!s.isEmpty) { 5 | int tmp = s.removeLast(); 6 | while (!r.isEmpty && r.last > tmp) { 7 | s.add(r.removeLast()); 8 | } 9 | r.add(tmp); 10 | } 11 | 12 | return r; 13 | } 14 | 15 | void main() { 16 | 17 | List s = new List(); 18 | s.add(3); 19 | s.add(2); 20 | s.add(24); 21 | s.add(34); 22 | s.add(19); 23 | s.add(3); 24 | s.add(4); 25 | s = sort(s); 26 | while(!s.isEmpty) { 27 | print(s.removeLast()); 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /dart/Chapter4/Question4_3/question.dart: -------------------------------------------------------------------------------- 1 | import '../../utils/tree_node.dart'; 2 | 3 | void main() { 4 | List array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 5 | 6 | // We needed this code for other files, so check out the code in the library. 7 | TreeNode root = TreeNode.createMinimalBST(array); 8 | print("Root? ${root.data}"); 9 | print("Created BST? ${root.isBST()}"); 10 | print("Height: ${root.height()}"); 11 | } -------------------------------------------------------------------------------- /dart/Chapter4/Question4_5/question.dart: -------------------------------------------------------------------------------- 1 | import '../../utils/tree_node.dart'; 2 | 3 | int last_printed = 0; // minimum value our ints can have. 4 | 5 | bool checkBST(TreeNode n) { 6 | if (n == null) { 7 | return true; 8 | } 9 | 10 | // Check / recurse left 11 | if (!checkBST(n.left)) { 12 | return false; 13 | } 14 | 15 | // Check current 16 | if (n.data < last_printed) { 17 | return false; 18 | } 19 | 20 | last_printed = n.data; 21 | 22 | // Check /recurse right 23 | if (!checkBST(n.right)) { 24 | return false; 25 | } 26 | 27 | return true; 28 | } 29 | 30 | void main() { 31 | List array = [3, 5, 7, 10, 13, 15, 20]; 32 | TreeNode node = TreeNode.createMinimalBST(array); 33 | //node.left.right.data = 3; 34 | print(checkBST(node)); 35 | } -------------------------------------------------------------------------------- /dart/Chapter5/Question5_5/question.dart: -------------------------------------------------------------------------------- 1 | 2 | int bitSwapRequired(int a, int b) { 3 | int count = 0; 4 | for (int c = a ^ b; c != 0; c = c >> 1) { 5 | count += c & 1; 6 | } 7 | 8 | return count; 9 | } 10 | 11 | int bitSwapRequired2(int a, int b) { 12 | int count = 0; 13 | for (int c = a ^ b; c != 0; c = c & (c - 1)) { 14 | count++; 15 | } 16 | 17 | return count; 18 | } 19 | 20 | void main() { 21 | int a = 23432; 22 | int b = 512132; 23 | print("$a: ${a.toRadixString(2)}"); 24 | print("$b: ${b.toRadixString(2)}"); 25 | int nbits = bitSwapRequired(a, b); 26 | int nbits2 = bitSwapRequired2(a, b); 27 | print("Required number of bits: $nbits $nbits2"); 28 | } -------------------------------------------------------------------------------- /dart/Chapter5/Question5_6/question.dart: -------------------------------------------------------------------------------- 1 | int swapOddEvenBits(int x) { 2 | return (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1)); 3 | } 4 | 5 | void main() { 6 | int a = 103217; 7 | print ("$a: ${a.toRadixString(2)}"); 8 | int b = swapOddEvenBits(a); 9 | print("$b: ${b.toRadixString(2)}"); 10 | } -------------------------------------------------------------------------------- /dart/Chapter7/Introduction/prime_numbers.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | bool primeNaive(int n) { 4 | for (int i = 2; i < n; i++) { 5 | if (n % i == 0) { 6 | return false; 7 | } 8 | } 9 | return true; 10 | } 11 | 12 | bool primeSlightlyBetter(int n) { 13 | int s = sqrt(n).toInt(); 14 | for (int i = 2; i <= s; i++) { 15 | if (n % i == 0) { 16 | return false; 17 | } 18 | } 19 | 20 | return true; 21 | } 22 | 23 | void main() { 24 | for (int i = 2; i < 100; i++) { 25 | if (primeSlightlyBetter(i)) { 26 | print(i); 27 | } 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /dart/Chapter7/Question7_3/question.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | class Line { 4 | static double epsilon = 0.000001; 5 | double slope; 6 | double yintercept; 7 | Line(this.slope, this.yintercept); 8 | String print_line() => "y = ${slope}x + $yintercept"; 9 | bool intersect(Line line2) => (slope - line2.slope).abs() > epsilon || (yintercept - line2.yintercept).abs() < epsilon; 10 | } 11 | 12 | int randomInt(int n) => (new Random().nextDouble() * n).toInt(); 13 | 14 | void main() { 15 | for (int i = 0; i < 10; i++) { 16 | Line line1 = new Line(randomInt(5).toDouble(), randomInt(1).toDouble()); 17 | Line line2 = new Line(randomInt(5).toDouble(), randomInt(2).toDouble()); 18 | print("${line1.print_line()}, ${line2.print_line()} ${line1.intersect(line2) ? 'YES' : 'NO' }"); 19 | } 20 | } -------------------------------------------------------------------------------- /dart/Chapter7/Question7_7/questionA.dart: -------------------------------------------------------------------------------- 1 | import 'dart:collection'; 2 | 3 | int removeMin(Queue q) { 4 | int min = q.first; 5 | for (int v in q) { 6 | if (min > v) { 7 | min = v; 8 | } 9 | } 10 | while (q.contains(min)) { 11 | q.removeFirst(); 12 | } 13 | 14 | return min; 15 | } 16 | 17 | void addProducts(Queue q, int v) { 18 | q.add(v * 3); 19 | q.add(v * 5); 20 | q.add(v * 7); 21 | } 22 | 23 | int getKthMagicNumber(int k) { 24 | if (k < 0) { 25 | return 0; 26 | } 27 | 28 | int val = 1; 29 | Queue q = new Queue(); 30 | addProducts(q, 1); 31 | for (int i = 0; i < k; i++) { // Start at 1 since we've already done one iteration 32 | val = removeMin(q); 33 | addProducts(q, val); 34 | } 35 | return val; 36 | } 37 | 38 | void main() { 39 | 40 | for(int i = 0; i < 14; i++) { 41 | print("$i : ${getKthMagicNumber(i)}"); 42 | } 43 | } -------------------------------------------------------------------------------- /dart/Chapter8/Question8_1/black_jack_card.dart: -------------------------------------------------------------------------------- 1 | part of main; 2 | 3 | class BlackJackCard extends Card { 4 | BlackJackCard(int c, Suit s) : super(c, s); 5 | 6 | int value() { 7 | if (isAce()) { // Ace 8 | return 1; 9 | } else if (faceValue >= 11 && faceValue <= 13) { // Face card 10 | return 10; 11 | } else { // Number card 12 | return faceValue; 13 | } 14 | } 15 | 16 | int minValue() { 17 | if (isAce()) { // Ace 18 | return 1; 19 | } else { 20 | return value(); 21 | } 22 | } 23 | 24 | int maxValue() { 25 | if (isAce()) { // Ace 26 | return 11; 27 | } else { 28 | return value(); 29 | } 30 | } 31 | 32 | bool isAce() { 33 | return faceValue == 1; 34 | } 35 | 36 | bool isFaceCard() { 37 | return faceValue >= 11 && faceValue <= 13; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /dart/Chapter8/Question8_1/hand.dart: -------------------------------------------------------------------------------- 1 | part of main; 2 | 3 | class Hand { 4 | 5 | List cards = new List(); 6 | 7 | int score() { 8 | int score = 0; 9 | for (T card in cards) { 10 | score += card.value(); 11 | } 12 | return score; 13 | } 14 | 15 | void addCard(T card) { 16 | cards.add(card); 17 | } 18 | 19 | void print_cards() { 20 | for (Card card in cards) { 21 | card.print_card(); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /dart/Chapter8/Question8_1/suit.dart: -------------------------------------------------------------------------------- 1 | part of main; 2 | 3 | class Suit { 4 | static const Club = 0; 5 | static const Diamond = 1; 6 | static const Heart = 2; 7 | static const Spade = 3; 8 | 9 | int _value; 10 | Suit(this._value); 11 | 12 | int get value => _value; 13 | 14 | static Suit getSuitFromValue(int value) { 15 | switch(value) { 16 | case 0: 17 | return new Suit(Suit.Club); 18 | case 1: 19 | return new Suit(Suit.Diamond); 20 | case 2: 21 | return new Suit(Suit.Heart); 22 | case 3: 23 | return new Suit(Suit.Spade); 24 | default: 25 | return null; 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /dart/Chapter9/Introduction/fibonacci.dart: -------------------------------------------------------------------------------- 1 | int fibonacci(int i) { 2 | if (i == 0) { 3 | return 0; 4 | } 5 | 6 | if (i == 1) { 7 | return 1; 8 | } 9 | 10 | return fibonacci(i - 1) + fibonacci(i - 2); 11 | } 12 | 13 | void main() { 14 | int max = 35; // WARNING: If you make this above 40ish, your computer may serious slow down 15 | int trials = 10; // Run code multiple times to compute average time. 16 | List times = new List(max); 17 | for (int i = 0; i < times.length; i++) { 18 | times[i]=0; 19 | } 20 | Stopwatch sw = new Stopwatch(); 21 | 22 | for (int j = 0; j < trials; j++) { // Run this 10 times to compute 23 | for (int i = 0; i < max; i++) { 24 | sw.start(); 25 | fibonacci(i); 26 | sw.stop(); 27 | times[i] += sw.elapsedMilliseconds; 28 | } 29 | } 30 | 31 | for (int j = 0; j < max; j++) { 32 | print("$j: ${times[j]/trials}ms"); 33 | } 34 | } -------------------------------------------------------------------------------- /dart/Chapter9/Question9_8/question.dart: -------------------------------------------------------------------------------- 1 | 2 | int makeChange(int n, [int denom = 25]) { 3 | //print("$n $denom"); 4 | 5 | int next_denom = 0; 6 | switch(denom) { 7 | case 25: 8 | next_denom = 10; 9 | break; 10 | case 10: 11 | next_denom = 5; 12 | break; 13 | case 5: 14 | next_denom = 1; 15 | break; 16 | case 1: 17 | return 1; 18 | } 19 | 20 | int ways = 0; 21 | for (int i = 0; i * denom <= n; i++) { 22 | ways += makeChange(n - i * denom, next_denom); 23 | } 24 | 25 | return ways; 26 | } 27 | 28 | void main() { 29 | for (int i = 100; i >= 1; i--) { 30 | print("makeChange($i) = ${makeChange(i)}"); 31 | } 32 | } -------------------------------------------------------------------------------- /dart/README.md: -------------------------------------------------------------------------------- 1 | INTRODUCTION 2 | ------------ 3 | 4 | Cracking the Coding Interview with Dart. The collection of dart code contains 5 | the solutions to ctci. This was a quick port of some of the solutions found in 6 | the java solution manual. Going forward these solutions will be dartified. Buy 7 | the book and support the author. [Cracking the Coding Interview](http://www.amazon.com/dp/098478280X/) 8 | 9 | TODO 10 | ---- 11 | 12 | Chapter 8 is not finished. 13 | Chapter 10 is not finished. 14 | 15 | -------------------------------------------------------------------------------- /go/README.md: -------------------------------------------------------------------------------- 1 | Cracking The Coding Interview 2 | ============================= 3 | 4 | This repository contains the solutions for 'Cracking The Coding Interview' book problems in GO 5 | 6 | ###Contributor 7 | 8 | * Dinesh Appavoo ([@DineshAppavoo](https://twitter.com/DineshAppavoo)) 9 | -------------------------------------------------------------------------------- /go/chapter01/question1.1/question1_1.go: -------------------------------------------------------------------------------- 1 | // Author: Dinesh Appavoo (dineshappavoo) 2 | 3 | /* 4 | Algorithm IS_DUPLICATE_EXIST(str): 5 | 1.Get the input string 6 | 2.Create a map of [string]boolean 7 | 4.For i from 1 to n iterate through the characters ch of the string 8 | if ch present in the map then return false 9 | else put ch to the map --> map[ch]=true 10 | 5.return true 11 | */ 12 | package main 13 | 14 | import ( 15 | "fmt" 16 | ) 17 | 18 | var sMap map[string]bool 19 | 20 | func main() { 21 | 22 | words:=[]string{"abcde", "hello", "apple", "kite", "padle"}; 23 | for _,value:=range words { 24 | fmt.Println("Input : ",value," Is Unique? ",isUnique(value)) 25 | } 26 | } 27 | 28 | func isUnique(str string) bool { 29 | 30 | sMap = make(map[string]bool) 31 | var ch string 32 | for i := 0; i < len(str); i++ { 33 | ch = string([]rune(str)[i]) 34 | if sMap[ch] { 35 | return false 36 | } else { 37 | sMap[ch] = true 38 | } 39 | } 40 | return true 41 | } 42 | -------------------------------------------------------------------------------- /go/chapter02/question2.3/question2_3.go: -------------------------------------------------------------------------------- 1 | // Author: Dinesh Appavoo (dineshappavoo) 2 | 3 | /* 4 | Algorithm DELETE_NODE(node): 5 | 1.Get the pointer to the node 6 | 2.if node==nil || node.next == nil then return 7 | 3.node.Value = node.next.Value 8 | 4.node.next = node.next.next 9 | */ 10 | 11 | package main 12 | 13 | import ( 14 | "fmt" 15 | "go/chapter02/list" 16 | ) 17 | 18 | func main() { 19 | m := list.New() 20 | m.PushFront(4) 21 | m.PushFront(5) 22 | e4 := m.PushFront(7) 23 | m.PushFront(6) 24 | m.PushBack(9) 25 | 26 | //removeInPlace function is the tweak in the original list. newly appened function in the list package "go/chapter02-linkedlists/list" 27 | 28 | m.RemoveInPlace(e4) 29 | fmt.Println("In Place ") 30 | for f := m.Front(); f != nil; f = f.Next() { 31 | fmt.Println(f.Value.(int)) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /go/chapter04/question4.3/question4_3.go: -------------------------------------------------------------------------------- 1 | // Author: Dinesh Appavoo (dineshappavoo) 2 | 3 | /*Algorithm BST_MINIMAL_HEIGHT(arr, low, high): 4 | 1.Get the input array arr 5 | 2.find the mid element using low and high . mid =(low+high)/2 6 | 3.t.Value = arr[mid] 7 | 4.t.Left=BST_MINIMAL_HEIGHT(arr, low, mid) 8 | 5.t.Right=BST_MINIMAL_HEIGHT(arr, mid+1, high) 9 | 6.return t 10 | */ 11 | package main 12 | 13 | import ( 14 | "fmt" 15 | "go/chapter04/binarytree" 16 | ) 17 | 18 | func main() { 19 | 20 | inArr := []int{4, 5, 7, 8, 9} 21 | t1 := getMinimalBST(inArr, 0, len(inArr)-1) 22 | binarytree.InOrderTraverse(t1) 23 | fmt.Println("") 24 | } 25 | 26 | func getMinimalBST(arr []int, low int, high int) *binarytree.Tree { 27 | if high < low { 28 | return nil 29 | } 30 | mid := (low + high) / 2 31 | t1 := binarytree.NewTree() 32 | t1.Value = arr[mid] 33 | t1.Left = getMinimalBST(arr, low, mid-1) 34 | t1.Right = getMinimalBST(arr, mid+1, high) 35 | return t1 36 | } 37 | -------------------------------------------------------------------------------- /java/Chapter 1/Question1_3/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 1/Question1_3/Question.java -------------------------------------------------------------------------------- /java/Chapter 10/Question10_2/Machine.java: -------------------------------------------------------------------------------- 1 | package Question10_2; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Machine { 6 | public HashMap persons = new HashMap(); 7 | public int machineID; 8 | 9 | public Person getPersonWithID(int personID) { 10 | return persons.get(personID); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /java/Chapter 10/Question10_2/Person.java: -------------------------------------------------------------------------------- 1 | package Question10_2; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Person { 6 | private ArrayList friends; 7 | private int personID; 8 | private String info; 9 | 10 | public String getInfo() { return info; } 11 | public void setInfo(String info) { 12 | this.info = info; 13 | } 14 | 15 | public int[] getFriends() { 16 | int[] temp = new int[friends.size()]; 17 | for (int i = 0; i < temp.length; i++) { 18 | temp[i] = friends.get(i); 19 | } 20 | return temp; 21 | } 22 | public int getID() { return personID; } 23 | public void addFriend(int id) { friends.add(id); } 24 | 25 | public Person(int id) { 26 | this.personID = id; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java/Chapter 10/Question10_2/Server.java: -------------------------------------------------------------------------------- 1 | package Question10_2; 2 | 3 | import java.util.HashMap; 4 | 5 | public class Server { 6 | HashMap machines = new HashMap(); 7 | HashMap personToMachineMap = new HashMap(); 8 | 9 | public Machine getMachineWithId(int machineID) { 10 | return machines.get(machineID); 11 | } 12 | 13 | public int getMachineIDForUser(int personID) { 14 | Integer machineID = personToMachineMap.get(personID); 15 | return machineID == null ? -1 : machineID; 16 | } 17 | 18 | public Person getPersonWithID(int personID) { 19 | Integer machineID = personToMachineMap.get(personID); 20 | if (machineID == null) { 21 | return null; 22 | } 23 | Machine machine = getMachineWithId(machineID); 24 | if (machine == null) { 25 | return null; 26 | } 27 | return machine.getPersonWithID(personID); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /java/Chapter 10/Question10_3/QuestionB.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 10/Question10_3/QuestionB.java -------------------------------------------------------------------------------- /java/Chapter 10/Question10_4/BitSet.java: -------------------------------------------------------------------------------- 1 | package Question10_4; 2 | 3 | class BitSet { 4 | int[] bitset; 5 | 6 | public BitSet(int size) { 7 | bitset = new int[(size >> 5) + 1]; // divide by 32 8 | } 9 | 10 | boolean get(int pos) { 11 | int wordNumber = (pos >> 5); // divide by 32 12 | int bitNumber = (pos & 0x1F); // mod 32 13 | return (bitset[wordNumber] & (1 << bitNumber)) != 0; 14 | } 15 | 16 | void set(int pos) { 17 | int wordNumber = (pos >> 5); // divide by 32 18 | int bitNumber = (pos & 0x1F); // mod 32 19 | bitset[wordNumber] |= 1 << bitNumber; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/Chapter 10/Question10_4/Question.java: -------------------------------------------------------------------------------- 1 | package Question10_4; 2 | 3 | import CtCILibrary.AssortedMethods; 4 | 5 | public class Question { 6 | 7 | public static void checkDuplicates(int[] array) { 8 | BitSet bs = new BitSet(32000); 9 | for (int i = 0; i < array.length; i++) { 10 | int num = array[i]; 11 | int num0 = num - 1; // bitset starts at 0, numbers start at 1 12 | if (bs.get(num0)) { 13 | System.out.println(num); 14 | } else { 15 | bs.set(num0); 16 | } 17 | } 18 | } 19 | 20 | public static void main(String[] args) { 21 | int[] array = AssortedMethods.randomArray(30, 1, 30); 22 | System.out.println(AssortedMethods.arrayToString(array)); 23 | checkDuplicates(array); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /java/Chapter 10/Question10_7/Node.java: -------------------------------------------------------------------------------- 1 | package Question10_7; 2 | 3 | public class Node { 4 | public Node prev; 5 | public Node next; 6 | public String[] results; 7 | public String query; 8 | 9 | public Node(String q, String[] res) { 10 | results = res; 11 | query = q; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/Chapter 11/Question11_2/AnagramComparator.java: -------------------------------------------------------------------------------- 1 | package Question11_2; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | 6 | public class AnagramComparator implements Comparator { 7 | public String sortChars(String s) { 8 | char[] content = s.toCharArray(); 9 | Arrays.sort(content); 10 | return new String(content); 11 | } 12 | 13 | public int compare(String s1, String s2) { 14 | return sortChars(s1).compareTo(sortChars(s2)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/Chapter 11/Question11_2/Question.java: -------------------------------------------------------------------------------- 1 | package Question11_2; 2 | 3 | import java.util.Arrays; 4 | 5 | import CtCILibrary.AssortedMethods; 6 | 7 | public class Question { 8 | public static void main(String[] args) { 9 | String[] array = {"apple", "banana", "carrot", "ele", "duck", "papel", "tarroc", "cudk", "eel", "lee"}; 10 | System.out.println(AssortedMethods.stringArrayToString(array)); 11 | Arrays.sort(array, new AnagramComparator()); 12 | System.out.println(AssortedMethods.stringArrayToString(array)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/Chapter 11/Question11_6/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 11/Question11_6/.DS_Store -------------------------------------------------------------------------------- /java/Chapter 11/Question11_6/Coordinate.java: -------------------------------------------------------------------------------- 1 | package Question11_6; 2 | 3 | public class Coordinate implements Cloneable { 4 | public int row; 5 | public int column; 6 | public Coordinate(int r, int c) { 7 | row = r; 8 | column = c; 9 | } 10 | 11 | public boolean inbounds(int[][] matrix) { 12 | return row >= 0 && 13 | column >= 0 && 14 | row < matrix.length && 15 | column < matrix[0].length; 16 | } 17 | 18 | public boolean isBefore(Coordinate p) { 19 | return row <= p.row && column <= p.column; 20 | } 21 | 22 | public Object clone() { 23 | return new Coordinate(row, column); 24 | } 25 | 26 | public void moveDownRight() { 27 | row++; 28 | column++; 29 | } 30 | 31 | public void setToAverage(Coordinate min, Coordinate max) { 32 | row = (min.row + max.row) / 2; 33 | column = (min.column + max.column) / 2; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /java/Chapter 11/Question11_7/HtWt.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 11/Question11_7/HtWt.java -------------------------------------------------------------------------------- /java/Chapter 11/Question11_8/IntComparable.java: -------------------------------------------------------------------------------- 1 | package Question11_8; 2 | 3 | import java.util.Comparator; 4 | 5 | public class IntComparable implements Comparator{ 6 | 7 | @Override 8 | public int compare(Integer o1, Integer o2) { 9 | return o1.compareTo(o2); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/Chapter 14/Introduction/Ambiguous.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class Ambiguous extends Shape { 4 | private double area = 10; 5 | 6 | public double computeArea() { 7 | return area; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /java/Chapter 14/Introduction/Circle.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class Circle extends Shape { 4 | private double rad = 5; 5 | public void printMe() { 6 | System.out.println("I am a circle."); 7 | } 8 | 9 | public double computeArea() { 10 | return rad * rad * 3.15; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /java/Chapter 14/Introduction/Introduction.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class Introduction { 4 | public static String lem() { 5 | System.out.println("lem"); 6 | return "return from lem"; 7 | } 8 | 9 | public static String foo() { 10 | int x = 0; 11 | int y = 5; 12 | try 13 | { 14 | System.out.println("start try"); 15 | int b = y / x; 16 | System.out.println("end try"); 17 | return "returned from try"; 18 | } catch (Exception ex) { 19 | System.out.println("catch"); 20 | return lem() + " | returned from catch"; 21 | } finally { 22 | System.out.println("finally"); 23 | } 24 | } 25 | 26 | public static void bar() { 27 | System.out.println("start bar"); 28 | String v = foo(); 29 | System.out.println(v); 30 | System.out.println("end bar"); 31 | } 32 | 33 | public static void main(String[] args) { 34 | bar(); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /java/Chapter 14/Introduction/IntroductionOverriding.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class IntroductionOverriding { 4 | 5 | public static void printArea(Circle c) { 6 | System.out.println("The circle is " + c.computeArea()); 7 | } 8 | 9 | public static void printArea(Square s) { 10 | System.out.println("The square is " + s.computeArea()); 11 | } 12 | 13 | public static void printArea(Ambiguous s) { 14 | System.out.println("The ambiguous is undefined"); 15 | } 16 | 17 | public static void main(String[] args) { 18 | Shape[] shapes = new Shape[2]; 19 | Circle circle = new Circle(); 20 | Ambiguous ambiguous = new Ambiguous(); 21 | 22 | shapes[0] = circle; 23 | shapes[1] = ambiguous; 24 | 25 | for (Shape s : shapes) { 26 | s.printMe(); 27 | System.out.println(s.computeArea()); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/Chapter 14/Introduction/Shape.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public abstract class Shape { 4 | public void printMe() { 5 | System.out.println("I am a shape."); 6 | } 7 | 8 | public abstract double computeArea(); 9 | } 10 | -------------------------------------------------------------------------------- /java/Chapter 14/Introduction/Square.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class Square extends Shape { 4 | private double len = 5; 5 | public void printMe() { 6 | System.out.println("I am a square."); 7 | } 8 | 9 | public double computeArea() { 10 | return len * len; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /java/Chapter 14/Question14_1/Question.java: -------------------------------------------------------------------------------- 1 | package Question14_1; 2 | 3 | public class Question { 4 | private Question() { 5 | System.out.println("Q"); 6 | } 7 | 8 | static class A { 9 | private A() { 10 | } 11 | } 12 | 13 | static class B extends A { 14 | public B() { 15 | } 16 | } 17 | 18 | public static void main(String[] args) { 19 | new B(); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 14/Question14_5/Rectangle.java: -------------------------------------------------------------------------------- 1 | package Question14_5; 2 | 3 | public class Rectangle { 4 | private double width; 5 | private double height; 6 | public Rectangle(double w, double h) { 7 | width = w; 8 | height = h; 9 | } 10 | 11 | public double area() { 12 | return width * height; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/Chapter 14/Question14_6/Question.java: -------------------------------------------------------------------------------- 1 | package Question14_6; 2 | 3 | public class Question { 4 | 5 | /** 6 | * @param args 7 | */ 8 | public static void main(String[] args) { 9 | int size = 10; 10 | CircularArray array = new CircularArray(size); 11 | for (int i = 0; i < size; i++) { 12 | array.set(i, String.valueOf(i)); 13 | } 14 | 15 | array.rotate(3); 16 | for (int i = 0; i < size; i++) { 17 | System.out.println(array.get(i)); 18 | } 19 | 20 | System.out.println(""); 21 | 22 | array.rotate(2); 23 | for (String s : array) { 24 | System.out.println(s); 25 | } 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionA/ExampleA.java: -------------------------------------------------------------------------------- 1 | package IntroductionA; 2 | 3 | public class ExampleA { 4 | 5 | public static void main(String[] args) { 6 | RunnableThreadExample instance = new RunnableThreadExample(); 7 | Thread thread = new Thread(instance); 8 | thread.start(); 9 | 10 | /* waits until earlier thread counts to 5 (slowly) */ 11 | while (instance.count != 5) { 12 | try { 13 | Thread.sleep(250); 14 | } catch (InterruptedException exc) { 15 | exc.printStackTrace(); 16 | } 17 | } 18 | 19 | System.out.println("Program Terminating."); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionA/RunnableThreadExample.java: -------------------------------------------------------------------------------- 1 | package IntroductionA; 2 | 3 | public class RunnableThreadExample implements Runnable { 4 | public int count = 0; 5 | 6 | public void run() { 7 | System.out.println("RunnableThread starting."); 8 | try { 9 | while (count < 5) { 10 | Thread.sleep(500); 11 | System.out.println("RunnableThread count: " + count); 12 | count++; 13 | } 14 | } catch (InterruptedException exc) { 15 | System.out.println("RunnableThread interrupted."); 16 | } 17 | System.out.println("RunnableThread terminating."); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionB/ExampleB.java: -------------------------------------------------------------------------------- 1 | package IntroductionB; 2 | 3 | public class ExampleB { 4 | public static void main(String args[]) { 5 | ThreadExample instance = new ThreadExample(); 6 | instance.start(); 7 | 8 | while (instance.count != 5) { 9 | try { 10 | Thread.sleep(250); 11 | } catch (InterruptedException exc) { 12 | exc.printStackTrace(); 13 | } 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionB/ThreadExample.java: -------------------------------------------------------------------------------- 1 | package IntroductionB; 2 | 3 | public class ThreadExample extends Thread { 4 | int count = 0; 5 | 6 | public void run() { 7 | System.out.println("Thread starting."); 8 | try { 9 | while (count < 5) { 10 | Thread.sleep(500); 11 | System.out.println("In Thread, count is " + count); 12 | count++; 13 | } 14 | } catch (InterruptedException exc) { 15 | System.out.println("Thread interrupted."); 16 | } 17 | System.out.println("Thread terminating."); 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionLocks/Intro.java: -------------------------------------------------------------------------------- 1 | package IntroductionLocks; 2 | 3 | public class Intro { 4 | 5 | public static void main(String[] args) { 6 | NoLockATM noLockATM = new NoLockATM(); 7 | LockedATM lockedATM = new LockedATM(); 8 | MyClass thread1 = new MyClass(noLockATM, lockedATM); 9 | MyClass thread2 = new MyClass(noLockATM, lockedATM); 10 | 11 | thread1.start(); 12 | thread2.start(); 13 | 14 | try { 15 | Thread.sleep(1000); 16 | } catch (InterruptedException e) { 17 | // TODO Auto-generated catch block 18 | e.printStackTrace(); 19 | } 20 | thread1.waitUntilDone(); 21 | thread2.waitUntilDone(); 22 | 23 | System.out.println("NoLock ATM: " + noLockATM.getBalance()); 24 | System.out.println("Locked ATM: " + lockedATM.getBalance()); 25 | int v = thread1.delta + thread2.delta + 100; 26 | System.out.println("Should Be: " + v); 27 | System.out.println("Program terminating."); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionLocks/NoLockATM.java: -------------------------------------------------------------------------------- 1 | package IntroductionLocks; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class NoLockATM { 7 | private int balance = 100; 8 | 9 | public NoLockATM() { 10 | } 11 | 12 | public int withdraw(int value) { 13 | int temp = balance; 14 | try { 15 | Thread.sleep(300); 16 | temp = temp - value; 17 | Thread.sleep(300); 18 | balance = temp; 19 | } catch (InterruptedException e) { } 20 | return temp; 21 | } 22 | 23 | public int deposit(int value) { 24 | int temp = balance; 25 | try { 26 | Thread.sleep(300); 27 | temp = temp + value; 28 | Thread.sleep(300); 29 | balance = temp; 30 | } catch (InterruptedException e) { } 31 | return temp; 32 | } 33 | 34 | public int getBalance() { 35 | return balance; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionSynchronization/Intro.java: -------------------------------------------------------------------------------- 1 | package IntroductionSynchronization; 2 | 3 | public class Intro { 4 | 5 | public static void main(String[] args) { 6 | try { 7 | MyObject obj1 = new MyObject(); 8 | MyObject obj2 = new MyObject(); 9 | MyClass thread1 = new MyClass(obj1, "1"); 10 | MyClass thread2 = new MyClass(obj2, "2"); 11 | 12 | thread1.start(); 13 | thread2.start(); 14 | 15 | Thread.sleep(3000 * 3); 16 | } catch (InterruptedException exc) { 17 | System.out.println("Program Interrupted."); 18 | } 19 | System.out.println("Program terminating."); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionSynchronization/MyClass.java: -------------------------------------------------------------------------------- 1 | package IntroductionSynchronization; 2 | 3 | public class MyClass extends Thread { 4 | private String name; 5 | private MyObject myObj; 6 | 7 | public MyClass(MyObject obj, String n) { 8 | name = n; 9 | myObj = obj; 10 | } 11 | 12 | public void run() { 13 | if (name.equals("1")) { 14 | MyObject.foo(name); 15 | } else if (name.equals("2")) { 16 | MyObject.bar(name); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionSynchronization/MyObject.java: -------------------------------------------------------------------------------- 1 | package IntroductionSynchronization; 2 | 3 | public class MyObject { 4 | public static synchronized void foo(String name) { 5 | try { 6 | System.out.println("Thread " + name + ".foo(): starting"); 7 | Thread.sleep(3000); 8 | System.out.println("Thread " + name + ".foo(): ending"); 9 | } catch (InterruptedException exc) { 10 | System.out.println("Thread " + name + ": interrupted."); 11 | } 12 | } 13 | 14 | public static synchronized void bar(String name) { 15 | try { 16 | System.out.println("Thread " + name + ".bar(): starting"); 17 | Thread.sleep(3000); 18 | System.out.println("Thread " + name + ".bar(): ending"); 19 | } catch (InterruptedException exc) { 20 | System.out.println("Thread " + name + ": interrupted."); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionSynchronizedBlocks/Intro.java: -------------------------------------------------------------------------------- 1 | package IntroductionSynchronizedBlocks; 2 | 3 | public class Intro { 4 | 5 | public static void main(String[] args) { 6 | try { 7 | MyObject obj1 = new MyObject(); 8 | MyObject obj2 = new MyObject(); 9 | 10 | MyClass thread1 = new MyClass(obj1, "1"); 11 | MyClass thread2 = new MyClass(obj1, "2"); 12 | 13 | thread1.start(); 14 | thread2.start(); 15 | 16 | Thread.sleep(3000 * 3); 17 | } catch (InterruptedException exc) { 18 | System.out.println("Program Interrupted."); 19 | } 20 | System.out.println("Program terminating."); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionSynchronizedBlocks/MyClass.java: -------------------------------------------------------------------------------- 1 | package IntroductionSynchronizedBlocks; 2 | 3 | public class MyClass extends Thread { 4 | private String name; 5 | private MyObject myObj; 6 | 7 | public MyClass(MyObject obj, String n) { 8 | name = n; 9 | myObj = obj; 10 | } 11 | 12 | public void run() { 13 | myObj.foo(name); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionSynchronizedBlocks/MyObject.java: -------------------------------------------------------------------------------- 1 | package IntroductionSynchronizedBlocks; 2 | 3 | public class MyObject { 4 | public void foo(String name) { 5 | synchronized(this) { 6 | try { 7 | System.out.println("Thread " + name + ".foo(): starting"); 8 | Thread.sleep(3000); 9 | System.out.println("Thread " + name + ".foo(): ending"); 10 | } catch (InterruptedException exc) { 11 | System.out.println("Thread " + name + ": interrupted."); 12 | } 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionWaitNotify/Intro.java: -------------------------------------------------------------------------------- 1 | package IntroductionWaitNotify; 2 | 3 | public class Intro { 4 | 5 | public static void main(String[] args) { 6 | try { 7 | MyObject obj1 = new MyObject(); 8 | MyObject obj2 = new MyObject(); 9 | MyClass thread1 = new MyClass(obj1, "1"); 10 | MyClass thread2 = new MyClass(obj1, "2"); 11 | 12 | thread1.start(); 13 | thread2.start(); 14 | 15 | Thread.sleep(3000 * 3); 16 | } catch (InterruptedException exc) { 17 | System.out.println("Program Interrupted."); 18 | } 19 | System.out.println("Program terminating."); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionWaitNotify/MyClass.java: -------------------------------------------------------------------------------- 1 | package IntroductionWaitNotify; 2 | 3 | public class MyClass extends Thread { 4 | private String name; 5 | private MyObject myObj; 6 | 7 | public MyClass(MyObject obj, String n) { 8 | name = n; 9 | myObj = obj; 10 | } 11 | 12 | public void run() { 13 | try { 14 | myObj.wait(1000); 15 | myObj.foo(name); 16 | myObj.notify(); 17 | } catch (InterruptedException e) { 18 | e.printStackTrace(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/Chapter 16/IntroductionWaitNotify/MyObject.java: -------------------------------------------------------------------------------- 1 | package IntroductionWaitNotify; 2 | 3 | public class MyObject { 4 | public void foo(String name) { 5 | try { 6 | System.out.println("Thread " + name + ".foo(): starting"); 7 | Thread.sleep(3000); 8 | System.out.println("Thread " + name + ".foo(): ending"); 9 | } catch (InterruptedException exc) { 10 | System.out.println("Thread " + name + ": interrupted."); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_3/Chopstick.java: -------------------------------------------------------------------------------- 1 | package Question16_3; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class Chopstick { 7 | private Lock lock; 8 | 9 | public Chopstick() { 10 | lock = new ReentrantLock(); 11 | } 12 | 13 | public boolean pickUp() { 14 | return lock.tryLock(); 15 | } 16 | 17 | public void putDown() { 18 | lock.unlock(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_3/Question.java: -------------------------------------------------------------------------------- 1 | package Question16_3; 2 | 3 | public class Question { 4 | public static int size = 3; 5 | 6 | public static int leftOf(int i) { 7 | return i; 8 | } 9 | 10 | public static int rightOf(int i) { 11 | return (i + 1) % size; 12 | } 13 | 14 | public static void main(String[] args) { 15 | Chopstick[] chopsticks = new Chopstick[size + 1]; 16 | for (int i = 0; i < size + 1; i++) { 17 | chopsticks[i] = new Chopstick(); 18 | } 19 | 20 | Philosopher[] philosophers = new Philosopher[size]; 21 | for (int i = 0; i < size; i++) { 22 | Chopstick left = chopsticks[leftOf(i)]; 23 | Chopstick right = chopsticks[rightOf(i)]; 24 | philosophers[i] = new Philosopher(i, left, right); 25 | } 26 | 27 | for (int i = 0; i < size; i++) { 28 | philosophers[i].start(); 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_4/Question.java: -------------------------------------------------------------------------------- 1 | package Question16_4; 2 | 3 | public class Question { 4 | 5 | public static void main(String[] args) { 6 | int[] res1 = {1, 2, 3, 4}; 7 | int[] res2 = {1, 5, 4, 1}; 8 | int[] res3 = {1, 4, 5}; 9 | 10 | LockFactory.initialize(10); 11 | 12 | LockFactory lf = LockFactory.getInstance(); 13 | System.out.println(lf.declare(1, res1)); 14 | System.out.println(lf.declare(2, res2)); 15 | System.out.println(lf.declare(3, res3)); 16 | 17 | System.out.println(lf.getLock(1, 1)); 18 | System.out.println(lf.getLock(1, 2)); 19 | System.out.println(lf.getLock(2, 4)); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_5/MyThread.java: -------------------------------------------------------------------------------- 1 | package Question16_5; 2 | 3 | public class MyThread extends Thread { 4 | private String method; 5 | private FooBad foo; 6 | 7 | public MyThread(FooBad foo, String method) { 8 | this.method = method; 9 | this.foo = foo; 10 | } 11 | 12 | public void run() { 13 | if (method == "first") { 14 | foo.first(); 15 | } else if (method == "second") { 16 | foo.second(); 17 | } else if (method == "third") { 18 | foo.third(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_5/Question.java: -------------------------------------------------------------------------------- 1 | package Question16_5; 2 | 3 | public class Question { 4 | public static void main(String[] args) { 5 | FooBad foo = new FooBad(); 6 | 7 | MyThread thread1 = new MyThread(foo, "first"); 8 | MyThread thread2 = new MyThread(foo, "second"); 9 | MyThread thread3 = new MyThread(foo, "third"); 10 | 11 | thread3.start(); 12 | thread2.start(); 13 | thread1.start(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_6/Foo.java: -------------------------------------------------------------------------------- 1 | package Question16_6; 2 | 3 | public class Foo { 4 | private String name; 5 | 6 | public Foo(String nm) { 7 | name = nm; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public void pause() { 15 | try { 16 | Thread.sleep(1000 * 3); 17 | } catch (InterruptedException e) { 18 | e.printStackTrace(); 19 | } 20 | } 21 | 22 | public synchronized void methodA(String threadName) { 23 | System.out.println("thread " + threadName + " starting: " + name + ".methodA()"); 24 | pause(); 25 | System.out.println("thread " + threadName + " ending: " + name + ".methodA()"); 26 | } 27 | 28 | public void methodB(String threadName) { 29 | System.out.println("thread " + threadName + " starting: " + name + ".methodB()"); 30 | pause(); 31 | System.out.println("thread " + threadName + " ending: " + name + ".methodB()"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /java/Chapter 16/Question16_6/MyThread.java: -------------------------------------------------------------------------------- 1 | package Question16_6; 2 | 3 | public class MyThread extends Thread { 4 | private Foo foo; 5 | public String name; 6 | public String firstMethod; 7 | public MyThread(Foo f, String nm, String fM) { 8 | foo = f; 9 | name = nm; 10 | firstMethod = fM; 11 | } 12 | 13 | public void run() { 14 | if (firstMethod.equals("A")) { 15 | foo.methodA(name); 16 | } else { 17 | foo.methodB(name); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_1/Question.java: -------------------------------------------------------------------------------- 1 | package Question17_1; 2 | 3 | public class Question { 4 | 5 | public static void swap(int a, int b) { 6 | // Example for a = 9, b = 4 7 | a = a - b; // a = 9 - 4 = 5 8 | b = a + b; // b = 5 + 4 = 9 9 | a = b - a; // a = 9 - 5 10 | 11 | System.out.println("a: " + a); 12 | System.out.println("b: " + b); 13 | } 14 | 15 | public static void swap_opt(int a, int b) { 16 | a = a^b; 17 | b = a^b; 18 | a = a^b; 19 | 20 | System.out.println("a: " + a); 21 | System.out.println("b: " + b); 22 | } 23 | 24 | public static void main(String[] args) { 25 | int a = 1672; 26 | int b = 9332; 27 | 28 | System.out.println("a: " + a); 29 | System.out.println("b: " + b); 30 | 31 | swap(a, b); 32 | swap_opt(a, b); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_10/Attribute.java: -------------------------------------------------------------------------------- 1 | package Question17_10; 2 | 3 | public class Attribute { 4 | public String tag; 5 | public String value; 6 | public Attribute(String t, String v) { 7 | tag = t; 8 | value = v; 9 | } 10 | 11 | public String getTagCode() { 12 | if (tag == "family") { 13 | return "1"; 14 | } else if (tag == "person") { 15 | return "2"; 16 | } else if (tag == "firstName") { 17 | return "3"; 18 | } else if (tag == "lastName") { 19 | return "4"; 20 | } else if (tag == "state") { 21 | return "5"; 22 | } 23 | return "--"; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_11/Question.java: -------------------------------------------------------------------------------- 1 | package Question17_11; 2 | 3 | public class Question { 4 | public static int rand7() { 5 | while (true) { 6 | int num = 5 * rand5() + rand5(); 7 | if (num < 21) { 8 | return num % 7; 9 | } 10 | } 11 | } 12 | 13 | public static int rand5() { 14 | return (int) (Math.random() * 100) % 5; 15 | } 16 | 17 | public static void main(String[] args) { 18 | /* Test: call rand7 many times and inspect the results. */ 19 | int[] arr = new int[7]; 20 | int test_size = 1000000; 21 | for(int k = 0; k < test_size; k++){ 22 | arr[rand7()]++; 23 | } 24 | 25 | for (int i = 0; i < 7; i++) { 26 | double percent = 100.0 * arr[i] / test_size; 27 | System.out.println(i + " appeared " + percent + "% of the time."); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_12/Question.java: -------------------------------------------------------------------------------- 1 | package Question17_12; 2 | 3 | import java.util.Arrays; 4 | 5 | public class Question { 6 | public static void printPairSums(int[] array, int sum) { 7 | Arrays.sort(array); 8 | int first = 0; 9 | int last = array.length - 1; 10 | while (first < last) { 11 | int s = array[first] + array[last]; 12 | if (s == sum) { 13 | System.out.println(array[first] + " " + array[last]); 14 | ++first; 15 | --last; 16 | } else { 17 | if (s < sum) { 18 | ++first; 19 | } else { 20 | --last; 21 | } 22 | } 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | int[] test = {9, 3, 6, 5, 7, -1, 13, 14, -2, 12, 0}; 28 | printPairSums(test, 12); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_13/BiNode.java: -------------------------------------------------------------------------------- 1 | package Question17_13; 2 | 3 | public class BiNode { 4 | public BiNode node1; 5 | public BiNode node2; 6 | public int data; 7 | public BiNode(int d) { 8 | data = d; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_14/Result.java: -------------------------------------------------------------------------------- 1 | package Question17_14; 2 | 3 | public class Result { 4 | public int invalid = Integer.MAX_VALUE; 5 | public String parsed = ""; 6 | public Result(int inv, String p) { 7 | invalid = inv; 8 | parsed = p; 9 | } 10 | 11 | public Result clone() { 12 | return new Result(this.invalid, this.parsed); 13 | } 14 | 15 | public static Result min(Result r1, Result r2) { 16 | if (r1 == null) { 17 | return r2; 18 | } else if (r2 == null) { 19 | return r1; 20 | } 21 | 22 | return r2.invalid < r1.invalid ? r2 : r1; 23 | } 24 | } -------------------------------------------------------------------------------- /java/Chapter 17/Question17_2/Question.java: -------------------------------------------------------------------------------- 1 | package Question17_2; 2 | 3 | public class Question { 4 | 5 | public static int convertBoardToInt(char[][] board) { 6 | int factor = 1; 7 | int sum = 0; 8 | for (int i = 0; i < board.length; i++) { 9 | for (int j = 0; j < board[i].length; j++) { 10 | int v = 0; 11 | if (board[i][j] == 'x') { 12 | v = 1; 13 | } else if (board[i][j] == 'o') { 14 | v = 2; 15 | } 16 | sum += v * factor; 17 | factor *= 3; 18 | } 19 | } 20 | return sum; 21 | } 22 | 23 | public static void main(String[] args) { 24 | char[][] board = { 25 | {'x', 'x', 'o'}, 26 | {' ', 'x', ' '}, 27 | {' ', ' ', 'x'}}; 28 | 29 | int v = convertBoardToInt(board); 30 | System.out.println(v); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_3/QuestionA.java: -------------------------------------------------------------------------------- 1 | package Question17_3; 2 | 3 | public class QuestionA { 4 | public static int factorsOf5(int i) { 5 | int count = 0; 6 | while (i % 5 == 0) { 7 | count++; 8 | i /= 5; 9 | } 10 | return count; 11 | } 12 | 13 | public static int countFactZeros(int num) { 14 | int count = 0; 15 | for (int i = 2; i <= num; i++) { 16 | count += factorsOf5(i); 17 | } 18 | return count; 19 | } 20 | 21 | public static int factorial(int num) { 22 | if (num == 1) { 23 | return 1; 24 | } else if (num > 1) { 25 | return num * factorial(num - 1); 26 | } else { 27 | return -1; // Error 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | for (int i = 1; i < 12; i++) { 33 | System.out.println(i + "! (or " + factorial(i) + ") has " + countFactZeros(i) + " zeros"); 34 | } 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_3/QuestionB.java: -------------------------------------------------------------------------------- 1 | package Question17_3; 2 | 3 | public class QuestionB { 4 | public static int countFactZeros(int num) { 5 | int count = 0; 6 | if (num < 0) { 7 | System.out.println("Factorial is not defined for negative numbers"); 8 | return 0; 9 | } 10 | for (int i = 5; num / i > 0; i *= 5) { 11 | count += num / i; 12 | } 13 | return count; 14 | } 15 | 16 | public static int factorial(int num) { 17 | if (num == 1) { 18 | return 1; 19 | } else if (num > 1) { 20 | return num * factorial(num - 1); 21 | } else { 22 | return -1; // Error 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | for (int i = 1; i < 12; i++) { 28 | System.out.println(i + "! (or " + factorial(i) + ") has " + countFactZeros(i) + " zeros"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /java/Chapter 17/Question17_8/Question.java: -------------------------------------------------------------------------------- 1 | package Question17_8; 2 | 3 | public class Question { 4 | 5 | public static int getMaxSum(int[] a) { 6 | int maxSum = 0; 7 | int runningSum = 0; 8 | for (int i = 0; i < a.length; i++) { 9 | runningSum += a[i]; 10 | if (maxSum < runningSum) { 11 | maxSum = runningSum; 12 | } else if (runningSum < 0) { 13 | runningSum = 0; 14 | } 15 | } 16 | return maxSum; 17 | } 18 | 19 | public static void main(String[] args) { 20 | int[] a = {2, -8, 3, -2, 4, -10}; 21 | System.out.println(getMaxSum(a)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_1/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 18/Question18_1/Question.java -------------------------------------------------------------------------------- /java/Chapter 18/Question18_11/SquareCell.java: -------------------------------------------------------------------------------- 1 | package Question18_11; 2 | 3 | public class SquareCell { 4 | public int zerosRight = 0; 5 | public int zerosBelow = 0; 6 | public SquareCell(int right, int below) { 7 | zerosRight = right; 8 | zerosBelow = below; 9 | } 10 | 11 | public void setZerosRight(int right) { 12 | zerosRight = right; 13 | } 14 | 15 | public void setZerosBelow(int below) { 16 | zerosBelow = below; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_11/Subsquare.java: -------------------------------------------------------------------------------- 1 | package Question18_11; 2 | 3 | public class Subsquare { 4 | public int row, column, size; 5 | public Subsquare(int r, int c, int sz) { 6 | row = r; 7 | column = c; 8 | size = sz; 9 | } 10 | 11 | public void print() { 12 | System.out.println("(" + row + ", " + column + ", " + size + ")"); 13 | } 14 | } -------------------------------------------------------------------------------- /java/Chapter 18/Question18_3/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 18/Question18_3/Question.java -------------------------------------------------------------------------------- /java/Chapter 18/Question18_4/QuestionBrute.java: -------------------------------------------------------------------------------- 1 | package Question18_4; 2 | 3 | public class QuestionBrute { 4 | 5 | public static int numberOf2s(int n) { 6 | int count = 0; 7 | while (n > 0) { 8 | if (n % 10 == 2) { 9 | count++; 10 | } 11 | n = n / 10; 12 | } 13 | return count; 14 | } 15 | 16 | public static int numberOf2sInRange(int n) { 17 | int count = 0; 18 | for (int i = 2; i <= n; i++) { // Might as well start at 2 19 | count += numberOf2s(i); 20 | } 21 | return count; 22 | } 23 | 24 | public static void main(String[] args) { 25 | for (int i = 0; i < 1000; i++) { 26 | int v = numberOf2sInRange(i); 27 | System.out.println("Between 0 and " + i + ": " + v); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_6/Parts.java: -------------------------------------------------------------------------------- 1 | package Question18_6; 2 | 3 | public class Parts { 4 | public int left; 5 | public int right; 6 | public Parts(int l, int r) { 7 | left = l; 8 | right = r; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_7/LengthComparator.java: -------------------------------------------------------------------------------- 1 | package Question18_7; 2 | 3 | import java.util.Comparator; 4 | 5 | public class LengthComparator implements Comparator { 6 | public int compare(String o1, String o2) { 7 | if (o1.length() < o2.length()) return 1; 8 | if (o1.length() > o2.length()) return -1; 9 | return 0; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_8/Question.java: -------------------------------------------------------------------------------- 1 | package Question18_8; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Question { 6 | public static void main(String[] args) { 7 | String testString = "mississippi"; 8 | String[] stringList = {"is", "sip", "hi", "sis"}; 9 | SuffixTree tree = new SuffixTree(testString); 10 | for (String s : stringList) { 11 | ArrayList list = tree.search(s); 12 | if (list != null) { 13 | System.out.println(s + ": " + list.toString()); 14 | } 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /java/Chapter 18/Question18_8/SuffixTree.java: -------------------------------------------------------------------------------- 1 | package Question18_8; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class SuffixTree { 6 | SuffixTreeNode root = new SuffixTreeNode(); 7 | 8 | public SuffixTree(String s) { 9 | for (int i = 0; i < s.length(); i++) { 10 | String suffix = s.substring(i); 11 | root.insertString(suffix, i); 12 | } 13 | } 14 | 15 | public ArrayList search(String s) { 16 | return root.search(s); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_9/MaxHeapComparator.java: -------------------------------------------------------------------------------- 1 | package Question18_9; 2 | 3 | import java.util.Comparator; 4 | 5 | public class MaxHeapComparator implements Comparator{ 6 | // Comparator that sorts integers from highest to lowest 7 | @Override 8 | public int compare(Integer o1, Integer o2) { 9 | // TODO Auto-generated method stub 10 | if (o1 < o2) return 1; 11 | else if (o1 == o2) return 0; 12 | else return -1; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_9/MinHeapComparator.java: -------------------------------------------------------------------------------- 1 | package Question18_9; 2 | 3 | import java.util.Comparator; 4 | 5 | public class MinHeapComparator implements Comparator{ 6 | // Comparator that sorts integers from lowest to highest 7 | @Override 8 | public int compare(Integer o1, Integer o2) { 9 | if (o1 > o2) return 1; 10 | else if (o1 == o2) return 0; 11 | else return -1; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/Chapter 18/Question18_9/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 18/Question18_9/Question.java -------------------------------------------------------------------------------- /java/Chapter 2/Question2_1/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 2/Question2_1/Question.java -------------------------------------------------------------------------------- /java/Chapter 2/Question2_2/Cpp Link: -------------------------------------------------------------------------------- 1 | http://ideone.com/CIzkJf -------------------------------------------------------------------------------- /java/Chapter 2/Question2_2/IntWrapper.java: -------------------------------------------------------------------------------- 1 | package Question2_2; 2 | 3 | public class IntWrapper { 4 | public int value = 0; 5 | } 6 | -------------------------------------------------------------------------------- /java/Chapter 2/Question2_2/Result.java: -------------------------------------------------------------------------------- 1 | package Question2_2; 2 | 3 | import CtCILibrary.*; 4 | 5 | public class Result { 6 | public LinkedListNode node; 7 | public int count; 8 | public Result(LinkedListNode n, int c) { 9 | node = n; 10 | count = c; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /java/Chapter 2/Question2_3/Question.java: -------------------------------------------------------------------------------- 1 | package Question2_3; 2 | 3 | import CtCILibrary.AssortedMethods; 4 | import CtCILibrary.LinkedListNode; 5 | 6 | public class Question { 7 | 8 | public static boolean deleteNode(LinkedListNode n) { 9 | if (n == null || n.next == null) { 10 | return false; // Failure 11 | } 12 | LinkedListNode next = n.next; 13 | n.data = next.data; 14 | n.next = next.next; 15 | return true; 16 | } 17 | 18 | public static void main(String[] args) { 19 | LinkedListNode head = AssortedMethods.randomLinkedList(10, 0, 10); 20 | System.out.println(head.printForward()); 21 | deleteNode(head.next.next.next.next); // delete node 4 22 | System.out.println(head.printForward()); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /java/Chapter 2/Question2_5/PartialSum.java: -------------------------------------------------------------------------------- 1 | package Question2_5; 2 | 3 | import CtCILibrary.LinkedListNode; 4 | 5 | public class PartialSum { 6 | public LinkedListNode sum = null; 7 | public int carry = 0; 8 | } 9 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_1/FullStackException.java: -------------------------------------------------------------------------------- 1 | package Question3_1; 2 | 3 | public class FullStackException extends Exception { 4 | private static final long serialVersionUID = 1L; 5 | 6 | public FullStackException(){ 7 | super(); 8 | } 9 | 10 | public FullStackException(String message){ 11 | super(message); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_1/StackData.java: -------------------------------------------------------------------------------- 1 | package Question3_1; 2 | 3 | public class StackData { 4 | public int start; 5 | public int pointer; 6 | public int size = 0; 7 | public int capacity; 8 | public StackData(int _start, int _capacity) { 9 | start = _start; 10 | pointer = _start - 1; 11 | capacity = _capacity; 12 | } 13 | 14 | public boolean isWithinStack(int index, int total_size) { 15 | // Note: if stack wraps, the head (right side) wraps around to the left. 16 | if (start <= index && index < start + capacity) { 17 | // non-wrapping, or "head" (right side) of wrapping case 18 | return true; 19 | } else if (start + capacity > total_size && 20 | index < (start + capacity) % total_size) { 21 | // tail (left side) of wrapping case 22 | return true; 23 | } 24 | return false; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_2/NodeWithMin.java: -------------------------------------------------------------------------------- 1 | package Question3_2; 2 | 3 | class NodeWithMin { 4 | public int value; 5 | public int min; 6 | public NodeWithMin(int v, int min){ 7 | value = v; 8 | this.min = min; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_2/Question.java: -------------------------------------------------------------------------------- 1 | package Question3_2; 2 | 3 | import CtCILibrary.AssortedMethods; 4 | 5 | public class Question { 6 | public static void main(String[] args) { 7 | StackWithMin stack = new StackWithMin(); 8 | StackWithMin2 stack2 = new StackWithMin2(); 9 | for (int i = 0; i < 15; i++) { 10 | int value = AssortedMethods.randomIntInRange(0, 100); 11 | stack.push(value); 12 | stack2.push(value); 13 | System.out.print(value + ", "); 14 | } 15 | System.out.println('\n'); 16 | for (int i = 0; i < 15; i++) { 17 | System.out.println("Popped " + stack.pop().value + ", " + stack2.pop()); 18 | System.out.println("New min is " + stack.min() + ", " + stack2.min()); 19 | } 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_2/StackWithMin.java: -------------------------------------------------------------------------------- 1 | package Question3_2; 2 | 3 | import java.util.Stack; 4 | 5 | public class StackWithMin extends Stack { 6 | public void push(int value) { 7 | int newMin = Math.min(value, min()); 8 | super.push(new NodeWithMin(value, newMin)); 9 | } 10 | 11 | public int min() { 12 | if (this.isEmpty()) { 13 | return Integer.MAX_VALUE; 14 | } else { 15 | return peek().min; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_2/StackWithMin2.java: -------------------------------------------------------------------------------- 1 | package Question3_2; 2 | 3 | import java.util.Stack; 4 | 5 | public class StackWithMin2 extends Stack { 6 | Stack s2; 7 | 8 | public StackWithMin2() { 9 | s2 = new Stack(); 10 | } 11 | 12 | public void push(int value){ 13 | if (value <= min()) { 14 | s2.push(value); 15 | } 16 | super.push(value); 17 | } 18 | 19 | public Integer pop() { 20 | int value = super.pop(); 21 | if (value == min()) { 22 | s2.pop(); 23 | } 24 | return value; 25 | } 26 | 27 | public int min() { 28 | if (s2.isEmpty()) { 29 | return Integer.MAX_VALUE; 30 | } else { 31 | return s2.peek(); 32 | } 33 | } 34 | } 35 | 36 | 37 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_3/Node.java: -------------------------------------------------------------------------------- 1 | package Question3_3; 2 | 3 | public class Node { 4 | public Node above; 5 | public Node below; 6 | public int value; 7 | public Node(int value) { 8 | this.value = value; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_3/Question.java: -------------------------------------------------------------------------------- 1 | package Question3_3; 2 | 3 | public class Question { 4 | public static void main(String[] args) { 5 | int capacity_per_substack = 5; 6 | SetOfStacks set = new SetOfStacks(capacity_per_substack); 7 | for (int i = 0; i < 34; i++) { 8 | set.push(i); 9 | } 10 | for (int i = 0; i < 34; i++) { 11 | System.out.println("Popped " + set.pop()); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_4/Question.java: -------------------------------------------------------------------------------- 1 | package Question3_4; 2 | 3 | public class Question { 4 | public static void main(String[] args) { 5 | // Set up code. 6 | int n = 5; 7 | Tower[] towers = new Tower[3]; 8 | for (int i = 0; i < 3; i++) { 9 | towers[i] = new Tower(i); 10 | } 11 | for (int i = n - 1; i >= 0; i--) { 12 | towers[0].add(i); 13 | } 14 | 15 | // Copy and paste output into a .XML file and open it with internet explorer. 16 | //towers[0].print(); 17 | towers[0].moveDisks(n, towers[2], towers[1]); 18 | //towers[2].print(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_7/Animal.java: -------------------------------------------------------------------------------- 1 | package Question3_7; 2 | 3 | public abstract class Animal { 4 | private int order; 5 | protected String name; 6 | public Animal(String n) { 7 | name = n; 8 | } 9 | 10 | public abstract String name(); 11 | 12 | public void setOrder(int ord) { 13 | order = ord; 14 | } 15 | 16 | public int getOrder() { 17 | return order; 18 | } 19 | 20 | public boolean isOlderThan(Animal a) { 21 | return this.order < a.getOrder(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_7/Cat.java: -------------------------------------------------------------------------------- 1 | package Question3_7; 2 | 3 | public class Cat extends Animal { 4 | public Cat(String n) { 5 | super(n); 6 | } 7 | 8 | public String name() { 9 | return "Cat: " + name; 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_7/Dog.java: -------------------------------------------------------------------------------- 1 | package Question3_7; 2 | 3 | public class Dog extends Animal { 4 | public Dog(String n) { 5 | super(n); 6 | } 7 | 8 | public String name() { 9 | return "Dog: " + name; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/Chapter 3/Question3_7/Question.java: -------------------------------------------------------------------------------- 1 | package Question3_7; 2 | 3 | public class Question { 4 | 5 | 6 | public static void main(String[] args) { 7 | AnimalQueue animals = new AnimalQueue(); 8 | animals.enqueue(new Cat("Callie")); 9 | animals.enqueue(new Cat("Kiki")); 10 | animals.enqueue(new Dog("Fido")); 11 | animals.enqueue(new Dog("Dora")); 12 | animals.enqueue(new Cat("Kari")); 13 | animals.enqueue(new Dog("Dexter")); 14 | animals.enqueue(new Dog("Dobo")); 15 | animals.enqueue(new Cat("Copa")); 16 | 17 | System.out.println(animals.dequeueAny().name()); 18 | System.out.println(animals.dequeueAny().name()); 19 | System.out.println(animals.dequeueAny().name()); 20 | 21 | animals.enqueue(new Dog("Dapa")); 22 | animals.enqueue(new Cat("Kilo")); 23 | 24 | while (animals.size() != 0) { 25 | System.out.println(animals.dequeueAny().name()); 26 | } 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /java/Chapter 4/Question4_2/Graph.java: -------------------------------------------------------------------------------- 1 | package Question4_2; 2 | 3 | public class Graph { 4 | private Node vertices[]; 5 | public int count; 6 | public Graph() { 7 | vertices = new Node[6]; 8 | count = 0; 9 | } 10 | 11 | public void addNode(Node x) { 12 | if (count < 30) { 13 | vertices[count] = x; 14 | count++; 15 | } else { 16 | System.out.print("Graph full"); 17 | } 18 | } 19 | 20 | public Node[] getNodes() { 21 | return vertices; 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /java/Chapter 4/Question4_2/Node.java: -------------------------------------------------------------------------------- 1 | package Question4_2; 2 | 3 | class Node { 4 | private Node adjacent[]; 5 | public int adjacentCount; 6 | private String vertex; 7 | public Question.State state; 8 | public Node(String vertex, int adjacentLength) { 9 | this.vertex = vertex; 10 | adjacentCount = 0; 11 | adjacent = new Node[adjacentLength]; 12 | } 13 | 14 | public void addAdjacent(Node x) { 15 | if (adjacentCount < 30) { 16 | this.adjacent[adjacentCount] = x; 17 | adjacentCount++; 18 | } else { 19 | System.out.print("No more adjacent can be added"); 20 | } 21 | } 22 | public Node[] getAdjacent() { 23 | return adjacent; 24 | } 25 | public String getVertex() { 26 | return vertex; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java/Chapter 4/Question4_3/Question.java: -------------------------------------------------------------------------------- 1 | package Question4_3; 2 | 3 | import CtCILibrary.TreeNode; 4 | 5 | public class Question { 6 | public static void main(String[] args) { 7 | int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 8 | 9 | // We needed this code for other files, so check out the code in the library 10 | TreeNode root = TreeNode.createMinimalBST(array); 11 | System.out.println("Root? " + root.data); 12 | System.out.println("Created BST? " + root.isBST()); 13 | System.out.println("Height: " + root.height()); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /java/Chapter 4/Question4_5/IntWrapper.java: -------------------------------------------------------------------------------- 1 | package Question4_5; 2 | 3 | public class IntWrapper { 4 | public IntWrapper(int m) { 5 | data = m; 6 | } 7 | public int data; 8 | } 9 | -------------------------------------------------------------------------------- /java/Chapter 4/Question4_6/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 4/Question4_6/Question.java -------------------------------------------------------------------------------- /java/Chapter 4/Question4_7/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 4/Question4_7/Question.java -------------------------------------------------------------------------------- /java/Chapter 4/Question4_7/QuestionC.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 4/Question4_7/QuestionC.java -------------------------------------------------------------------------------- /java/Chapter 4/Question4_8/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 4/Question4_8/Question.java -------------------------------------------------------------------------------- /java/Chapter 5/Question5_1/Question.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 5/Question5_1/Question.java -------------------------------------------------------------------------------- /java/Chapter 5/Question5_5/Question.java: -------------------------------------------------------------------------------- 1 | package Question5_5; 2 | 3 | import CtCILibrary.AssortedMethods; 4 | 5 | public class Question { 6 | public static int bitSwapRequired(int a, int b) { 7 | int count = 0; 8 | for (int c = a ^ b; c != 0; c = c >> 1) { 9 | count += c & 1; 10 | } 11 | return count; 12 | } 13 | 14 | public static int bitSwapRequired2(int a, int b){ 15 | int count = 0; 16 | for (int c = a ^ b; c != 0; c = c & (c-1)) { 17 | count++; 18 | } 19 | return count; 20 | } 21 | 22 | public static void main(String[] args) { 23 | int a = 23432; 24 | int b = 512132; 25 | System.out.println(a + ": " + AssortedMethods.toFullBinaryString(a)); 26 | System.out.println(b + ": " + AssortedMethods.toFullBinaryString(b)); 27 | int nbits = bitSwapRequired(a, b); 28 | int nbits2 = bitSwapRequired2(a, b); 29 | System.out.println("Required number of bits: " + nbits + " " + nbits2); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /java/Chapter 5/Question5_6/Question.java: -------------------------------------------------------------------------------- 1 | package Question5_6; 2 | 3 | import CtCILibrary.AssortedMethods; 4 | 5 | public class Question { 6 | 7 | public static int swapOddEvenBits(int x) { 8 | return ( ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1) ); 9 | } 10 | 11 | public static void main(String[] args) { 12 | int a = 103217; 13 | System.out.println(a + ": " + AssortedMethods.toFullBinaryString(a)); 14 | int b = swapOddEvenBits(a); 15 | System.out.println(b + ": " + AssortedMethods.toFullBinaryString(b)); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 5/Question5_7.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 5/Question5_7.zip -------------------------------------------------------------------------------- /java/Chapter 7/Introduction/PrimeNumbers.java: -------------------------------------------------------------------------------- 1 | package Introduction; 2 | 3 | public class PrimeNumbers { 4 | 5 | public static boolean primeNaive(int n) { 6 | for (int i = 2; i < n; i++) { 7 | if (n % i == 0) { 8 | return false; 9 | } 10 | } 11 | return true; 12 | } 13 | 14 | public static boolean primeSlightlyBetter(int n) { 15 | int sqrt = (int) Math.sqrt(n); 16 | for (int i = 2; i <= sqrt; i++) { 17 | if (n % i == 0) { 18 | return false; 19 | } 20 | } 21 | return true; 22 | } 23 | 24 | public static void main(String[] args) { 25 | for (int i = 2; i < 100; i++) { 26 | if (primeSlightlyBetter(i)) { 27 | System.out.println(i); 28 | } 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /java/Chapter 7/Question7_3/Line.java: -------------------------------------------------------------------------------- 1 | package Question7_3; 2 | 3 | 4 | public class Line { 5 | static double epsilon = 0.000001; 6 | public double slope; 7 | public double yintercept; 8 | 9 | public Line(double s, double y) { 10 | slope = s; 11 | yintercept = y; 12 | } 13 | 14 | public void print() { 15 | System.out.print("y = " + slope + "x + " + yintercept); 16 | } 17 | 18 | public boolean intersect(Line line2) { 19 | return Math.abs(slope - line2.slope) > epsilon || 20 | Math.abs(yintercept - line2.yintercept) < epsilon; 21 | } 22 | }; -------------------------------------------------------------------------------- /java/Chapter 7/Question7_3/Question.java: -------------------------------------------------------------------------------- 1 | package Question7_3; 2 | 3 | public class Question { 4 | public static int randomInt(int n) { 5 | return (int) (Math.random() * n); 6 | } 7 | 8 | public static void main(String[] args) { 9 | for (int i = 0; i < 10; i++) { 10 | Line line1 = new Line(randomInt(5), randomInt(1)); 11 | Line line2 = new Line(randomInt(5), randomInt(2)); 12 | line1.print(); 13 | System.out.print(", "); 14 | line2.print(); 15 | if (line1.intersect(line2)) { 16 | System.out.println(" YES"); 17 | } else { 18 | System.out.println(" NO"); 19 | } 20 | } 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /java/Chapter 7/Question7_5/Line.java: -------------------------------------------------------------------------------- 1 | package Question7_5; 2 | 3 | public class Line { 4 | public Point start; 5 | public Point end; 6 | public Line(Point start, Point end) { 7 | this.start = start; 8 | this.end = end; 9 | } 10 | 11 | public String toString() { 12 | return "Line from " + start.toString() + " to " + end.toString(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/Chapter 7/Question7_5/Point.java: -------------------------------------------------------------------------------- 1 | package Question7_5; 2 | 3 | public class Point { 4 | public double x; 5 | public double y; 6 | public Point(double x, double y) { 7 | this.x = x; 8 | this.y = y; 9 | } 10 | 11 | public boolean isEqual(Point p) { 12 | return (p.x == x && p.y == y); 13 | } 14 | 15 | public String toString() { 16 | return "(" + x + ", " + y + ")"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 7/Question7_5/Square Cut Tester - Chapter 10, Problem 5.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 7/Question7_5/Square Cut Tester - Chapter 10, Problem 5.xlsx -------------------------------------------------------------------------------- /java/Chapter 7/Question7_5/Square.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 7/Question7_5/Square.java -------------------------------------------------------------------------------- /java/Chapter 7/Question7_6/GraphPoint.java: -------------------------------------------------------------------------------- 1 | package Question7_6; 2 | 3 | public class GraphPoint { 4 | public double x; 5 | public double y; 6 | public GraphPoint(double x1, double y1) { 7 | x = x1; 8 | y = y1; 9 | } 10 | 11 | public String toString() { 12 | return "(" + x + ", " + y + ")"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /java/Chapter 7/Question7_6/Line.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 7/Question7_6/Line.java -------------------------------------------------------------------------------- /java/Chapter 8/Question8_1/BlackJackCard.java: -------------------------------------------------------------------------------- 1 | package Question8_1; 2 | 3 | public class BlackJackCard extends Card { 4 | public BlackJackCard(int c, Suit s) { 5 | super(c, s); 6 | } 7 | 8 | public int value() { 9 | if (isAce()) { // Ace 10 | return 1; 11 | } else if (faceValue >= 11 && faceValue <= 13) { // Face card 12 | return 10; 13 | } else { // Number card 14 | return faceValue; 15 | } 16 | } 17 | 18 | public int minValue() { 19 | if (isAce()) { // Ace 20 | return 1; 21 | } else { 22 | return value(); 23 | } 24 | } 25 | 26 | public int maxValue() { 27 | if (isAce()) { // Ace 28 | return 11; 29 | } else { 30 | return value(); 31 | } 32 | } 33 | 34 | public boolean isAce() { 35 | return faceValue == 1; 36 | } 37 | 38 | public boolean isFaceCard() { 39 | return faceValue >= 11 && faceValue <= 13; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_1/Hand.java: -------------------------------------------------------------------------------- 1 | package Question8_1; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Hand { 6 | protected ArrayList cards = new ArrayList(); 7 | 8 | public int score() { 9 | int score = 0; 10 | for (T card : cards) { 11 | score += card.value(); 12 | } 13 | return score; 14 | } 15 | 16 | public void addCard(T card) { 17 | cards.add(card); 18 | } 19 | 20 | public void print() { 21 | for (Card card : cards) { 22 | card.print(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_1/Suit.java: -------------------------------------------------------------------------------- 1 | package Question8_1; 2 | 3 | public enum Suit { 4 | Club (0), 5 | Diamond (1), 6 | Heart (2), 7 | Spade (3); 8 | 9 | private int value; 10 | private Suit(int v) { 11 | value = v; 12 | } 13 | 14 | public int getValue() { 15 | return value; 16 | } 17 | 18 | public static Suit getSuitFromValue(int value) { 19 | switch (value) { 20 | case 0: 21 | return Suit.Club; 22 | case 1: 23 | return Suit.Diamond; 24 | case 2: 25 | return Suit.Heart; 26 | case 3: 27 | return Suit.Spade; 28 | default: 29 | return null; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_10/Cell.java: -------------------------------------------------------------------------------- 1 | package Question8_10; 2 | 3 | public class Cell { 4 | private K key; 5 | private V value; 6 | public Cell(K k, V v) { 7 | key = k; 8 | value = v; 9 | } 10 | 11 | public boolean equivalent(Cell c) { 12 | return equivalent(c.getKey()); 13 | } 14 | 15 | public boolean equivalent(K k) { 16 | return key.equals(k); 17 | } 18 | 19 | @Override 20 | public String toString() { 21 | return "(" + key.toString() + ", " + value.toString() + ")"; 22 | } 23 | 24 | public K getKey() { 25 | return key; 26 | } 27 | 28 | public V getValue() { 29 | return value; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_10/Dummy.java: -------------------------------------------------------------------------------- 1 | package Question8_10; 2 | 3 | public class Dummy { 4 | private String name; 5 | private int age; 6 | public Dummy(String n, int a) { 7 | name = n; 8 | age = a; 9 | } 10 | 11 | @Override 12 | public String toString() { 13 | return "(" + name + ", " + age + ")"; 14 | } 15 | 16 | public int getAge() { 17 | return age; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/CallHandler.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 8/Question8_2/CallHandler.java -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/Caller.java: -------------------------------------------------------------------------------- 1 | package Question8_2; 2 | 3 | public class Caller { 4 | private String name; 5 | private int userId; 6 | public Caller(int id, String nm) { 7 | name = nm; 8 | userId = id; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/Director.java: -------------------------------------------------------------------------------- 1 | package Question8_2; 2 | 3 | class Director extends Employee { 4 | public Director() { 5 | rank = Rank.Director; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/Manager.java: -------------------------------------------------------------------------------- 1 | package Question8_2; 2 | 3 | class Manager extends Employee { 4 | public Manager() { 5 | rank = Rank.Manager; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/Rank.java: -------------------------------------------------------------------------------- 1 | package Question8_2; 2 | 3 | public enum Rank { 4 | Responder (0), 5 | Manager (1), 6 | Director (2); 7 | 8 | private int value; 9 | 10 | private Rank(int v) { 11 | value = v; 12 | } 13 | 14 | public int getValue() { 15 | return value; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/Respondent.java: -------------------------------------------------------------------------------- 1 | package Question8_2; 2 | 3 | class Respondent extends Employee { 4 | public Respondent() { 5 | rank = Rank.Responder; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_2/Test.java: -------------------------------------------------------------------------------- 1 | package Question8_2; 2 | 3 | public class Test { 4 | 5 | /** 6 | * @param args 7 | */ 8 | public static void main(String[] args) { 9 | CallHandler ch = CallHandler.getInstance(); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/CD.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | public class CD { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/CDPlayer.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | public class CDPlayer { 4 | private Playlist p; 5 | private CD c; 6 | 7 | public Playlist getPlaylist() { return p; } 8 | public void setPlaylist(Playlist p) { this.p = p; } 9 | public CD getCD() { return c; } 10 | public void setCD(CD c) { this.c = c; } 11 | 12 | public CDPlayer(Playlist p) { this.p = p; } 13 | public CDPlayer(CD c, Playlist p) { 14 | this.p = p; 15 | this.c = c; 16 | } 17 | 18 | public CDPlayer(CD c){ this.c = c; } 19 | public void playSong(Song s) { } 20 | } 21 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/JukeBox.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | import java.util.Set; 4 | 5 | public class JukeBox { 6 | private CDPlayer cdPlayer; 7 | private User user; 8 | private Set cdCollection; 9 | private SongSelector ts; 10 | 11 | public JukeBox(CDPlayer cdPlayer, User user, Set cdCollection, 12 | SongSelector ts) { 13 | super(); 14 | this.cdPlayer = cdPlayer; 15 | this.user = user; 16 | this.cdCollection = cdCollection; 17 | this.ts = ts; 18 | } 19 | 20 | public Song getCurrentSong() { return ts.getCurrentSong(); } 21 | public void setUser(User u) { this.user = u; } 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/Playlist.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | import java.util.Queue; 4 | 5 | public class Playlist { 6 | private Song song; 7 | private Queue queue; 8 | public Playlist(Song song, Queue queue) { 9 | super(); 10 | this.song = song; 11 | this.queue = queue; 12 | } 13 | 14 | public Song getNextSongToPlay(){ return queue.peek(); } 15 | public void queueUpSong(Song s){ queue.add(s); } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/Song.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | public class Song { 4 | private String songName; 5 | public String toString() { return songName; } 6 | } 7 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/SongSelector.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | 4 | public class SongSelector { 5 | private Song currentSong; 6 | public SongSelector(Song s) { currentSong=s; } 7 | public void setSong(Song s) { currentSong = s; } 8 | public Song getCurrentSong() { return currentSong; } 9 | } 10 | 11 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_3/User.java: -------------------------------------------------------------------------------- 1 | package Question8_3; 2 | 3 | public class User { 4 | private String name; 5 | public String getName() { return name; } 6 | public void setName(String name) { this.name = name; } 7 | public long getID() { return ID; } 8 | public void setID(long iD) { ID = iD; } 9 | private long ID; 10 | public User(String name, long iD) { 11 | this.name = name; 12 | ID = iD; 13 | } 14 | public User getUser() { return this; } 15 | public static User addUser(String name, long iD){ 16 | return new User(name, iD); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/Bus.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | public class Bus extends Vehicle { 4 | public Bus() { 5 | spotsNeeded = 5; 6 | size = VehicleSize.Large; 7 | } 8 | 9 | public boolean canFitInSpot(ParkingSpot spot) { 10 | return spot.getSize() == VehicleSize.Large; 11 | } 12 | 13 | public void print() { 14 | System.out.print("B"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/Car.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | public class Car extends Vehicle { 4 | public Car() { 5 | spotsNeeded = 1; 6 | size = VehicleSize.Compact; 7 | } 8 | 9 | public boolean canFitInSpot(ParkingSpot spot) { 10 | return spot.getSize() == VehicleSize.Large || spot.getSize() == VehicleSize.Compact; 11 | } 12 | 13 | public void print() { 14 | System.out.print("C"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/Motorcycle.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | public class Motorcycle extends Vehicle { 4 | public Motorcycle() { 5 | spotsNeeded = 1; 6 | size = VehicleSize.Motorcycle; 7 | } 8 | 9 | public boolean canFitInSpot(ParkingSpot spot) { 10 | return true; 11 | } 12 | 13 | public void print() { 14 | System.out.print("M"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/ParkingLot.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | public class ParkingLot { 4 | private Level[] levels; 5 | private final int NUM_LEVELS = 5; 6 | 7 | public ParkingLot() { 8 | levels = new Level[NUM_LEVELS]; 9 | for (int i = 0; i < NUM_LEVELS; i++) { 10 | levels[i] = new Level(i, 30); 11 | } 12 | } 13 | 14 | /* Park the vehicle in a spot (or multiple spots). Return false if failed. */ 15 | public boolean parkVehicle(Vehicle vehicle) { 16 | for (int i = 0; i < levels.length; i++) { 17 | if (levels[i].parkVehicle(vehicle)) { 18 | return true; 19 | } 20 | } 21 | return false; 22 | } 23 | 24 | public void print() { 25 | for (int i = 0; i < levels.length; i++) { 26 | System.out.print("Level" + i + ": "); 27 | levels[i].print(); 28 | System.out.println(""); 29 | } 30 | System.out.println(""); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/Question.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | import CtCILibrary.AssortedMethods; 4 | 5 | public class Question { 6 | 7 | /** 8 | * @param args 9 | */ 10 | public static void main(String[] args) { 11 | ParkingLot lot = new ParkingLot(); 12 | 13 | Vehicle v = null; 14 | while (v == null || lot.parkVehicle(v)) { 15 | lot.print(); 16 | int r = AssortedMethods.randomIntInRange(0, 10); 17 | if (r < 2) { 18 | v = new Bus(); 19 | } else if (r < 4) { 20 | v = new Motorcycle(); 21 | } else { 22 | v = new Car(); 23 | } 24 | System.out.print("\nParking a "); 25 | v.print(); 26 | System.out.println(""); 27 | } 28 | System.out.println("Parking Failed. Final state: "); 29 | lot.print(); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/Vehicle.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | import java.util.ArrayList; 4 | 5 | public abstract class Vehicle { 6 | protected ArrayList parkingSpots = new ArrayList(); 7 | protected String licensePlate; 8 | protected int spotsNeeded; 9 | protected VehicleSize size; 10 | 11 | public int getSpotsNeeded() { 12 | return spotsNeeded; 13 | } 14 | 15 | public VehicleSize getSize() { 16 | return size; 17 | } 18 | 19 | /* Park vehicle in this spot (among others, potentially) */ 20 | public void parkInSpot(ParkingSpot spot) { 21 | parkingSpots.add(spot); 22 | } 23 | 24 | /* Remove car from spot, and notify spot that it's gone */ 25 | public void clearSpots() { 26 | for (int i = 0; i < parkingSpots.size(); i++) { 27 | parkingSpots.get(i).removeVehicle(); 28 | } 29 | parkingSpots.clear(); 30 | } 31 | 32 | public abstract boolean canFitInSpot(ParkingSpot spot); 33 | public abstract void print(); 34 | } 35 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_4/VehicleSize.java: -------------------------------------------------------------------------------- 1 | package Question8_4; 2 | 3 | public enum VehicleSize { 4 | Motorcycle, 5 | Compact, 6 | Large, 7 | } 8 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_5/Book.java: -------------------------------------------------------------------------------- 1 | package Question8_5; 2 | 3 | public class Book { 4 | private int bookId; 5 | private String details; 6 | 7 | public Book(int id, String det) { 8 | bookId = id; 9 | details = det; 10 | } 11 | 12 | public void update() { } 13 | 14 | public int getID() { 15 | return bookId; 16 | } 17 | 18 | public void setID(int id) { 19 | bookId = id; 20 | } 21 | 22 | public String getDetails() { 23 | return details; 24 | } 25 | 26 | public void setDetails(String details) { 27 | this.details = details; 28 | } 29 | } -------------------------------------------------------------------------------- /java/Chapter 8/Question8_5/Library.java: -------------------------------------------------------------------------------- 1 | package Question8_5; 2 | 3 | import java.util.Hashtable; 4 | 5 | public class Library { 6 | 7 | private Hashtable books; 8 | 9 | public Book addBook(int id, String details) { 10 | if (books.containsKey(id)) { 11 | return null; 12 | } 13 | Book book = new Book(id, details); 14 | books.put(id, book); 15 | return book; 16 | } 17 | 18 | public boolean remove(Book b){ 19 | return remove(b.getID()); 20 | } 21 | 22 | public boolean remove(int id) { 23 | if (!books.containsKey(id)) { 24 | return false; 25 | } 26 | books.remove(id); 27 | return true; 28 | } 29 | 30 | public Book find(int id){ 31 | return books.get(id); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_5/User.java: -------------------------------------------------------------------------------- 1 | package Question8_5; 2 | 3 | public class User { 4 | private int userId; 5 | private String details; 6 | private int accountType; 7 | 8 | public void renewMembership() { } 9 | 10 | public User(int id, String details, int accountType) { 11 | userId = id; 12 | this.details = details; 13 | this.accountType = accountType; 14 | } 15 | 16 | /* getters and setters */ 17 | public int getID() { return userId; } 18 | public void setID(int id) { userId = id; } 19 | public String getDetails() { return details; } 20 | public void setDetails(String details) { this.details = details; } 21 | public int getAccountType() { return accountType; } 22 | public void setAccountType(int accountType) { 23 | this.accountType = accountType; 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_5/UserManager.java: -------------------------------------------------------------------------------- 1 | package Question8_5; 2 | 3 | import java.util.Hashtable; 4 | 5 | public class UserManager { 6 | private Hashtable users; 7 | 8 | public User addUser(int id, String details, int accountType) { 9 | if (users.containsKey(id)) { 10 | return null; 11 | } 12 | User user = new User(id, details, accountType); 13 | users.put(id, user); 14 | return user; 15 | } 16 | 17 | public boolean remove(User u) { 18 | return remove(u.getID()); 19 | } 20 | 21 | public boolean remove(int id) { 22 | if (!users.containsKey(id)) { 23 | return false; 24 | } 25 | users.remove(id); 26 | return true; 27 | } 28 | 29 | public User find(int id){ 30 | return users.get(id); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/AddRequest.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | import java.util.Date; 4 | 5 | public class AddRequest { 6 | private User fromUser; 7 | private User toUser; 8 | private Date date; 9 | RequestStatus status; 10 | 11 | public AddRequest(User from, User to, Date date) { 12 | fromUser = from; 13 | toUser = to; 14 | this.date = date; 15 | status = RequestStatus.Unread; 16 | } 17 | 18 | public RequestStatus getStatus() { 19 | return status; 20 | } 21 | 22 | public User getFromUser() { 23 | return fromUser; 24 | } 25 | 26 | public User getToUser() { 27 | return toUser; 28 | } 29 | 30 | public Date getDate() { 31 | return date; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/Conversation.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | import java.util.ArrayList; 4 | 5 | public abstract class Conversation { 6 | protected ArrayList participants = new ArrayList(); 7 | protected int id; 8 | protected ArrayList messages = new ArrayList(); 9 | 10 | public ArrayList getMessages() { 11 | return messages; 12 | } 13 | 14 | public boolean addMessage(Message m) { 15 | messages.add(m); 16 | return true; 17 | } 18 | 19 | public int getId() { 20 | return id; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/GroupChat.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | public class GroupChat extends Conversation { 4 | public void removeParticipant(User user) { 5 | participants.remove(user); 6 | } 7 | 8 | public void addParticipant(User user) { 9 | participants.add(user); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/Message.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | import java.util.Date; 4 | 5 | public class Message { 6 | private String content; 7 | private Date date; 8 | public Message(String content, Date date) { 9 | this.content = content; 10 | this.date = date; 11 | } 12 | 13 | public String getContent() { 14 | return content; 15 | } 16 | 17 | public Date getDate() { 18 | return date; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/PrivateChat.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | public class PrivateChat extends Conversation { 4 | public PrivateChat(User user1, User user2) { 5 | participants.add(user1); 6 | participants.add(user2); 7 | } 8 | 9 | public User getOtherParticipant(User primary) { 10 | if (participants.get(0) == primary) { 11 | return participants.get(1); 12 | } else if (participants.get(1) == primary) { 13 | return participants.get(0); 14 | } 15 | return null; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/RequestStatus.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | public enum RequestStatus { 4 | Unread, Read, Accepted, Rejected 5 | } 6 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/System.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | public class System { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/UserStatus.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | public class UserStatus { 4 | private String message; 5 | private UserStatusType type; 6 | public UserStatus(UserStatusType type, String message) { 7 | this.type = type; 8 | this.message = message; 9 | } 10 | 11 | public UserStatusType getStatusType() { 12 | return type; 13 | } 14 | 15 | public String getMessage() { 16 | return message; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_7/UserStatusType.java: -------------------------------------------------------------------------------- 1 | package Question8_7; 2 | 3 | public enum UserStatusType { 4 | Offline, Away, Idle, Available, Busy 5 | } 6 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Color.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | public enum Color { 4 | White, Black 5 | } 6 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Direction.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | public enum Direction { 4 | left, right, up, down 5 | } 6 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Game.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | public class Game { 4 | private Player[] players; 5 | private static Game instance; 6 | private Board board; 7 | private final int ROWS = 10; 8 | private final int COLUMNS = 10; 9 | 10 | private Game() { 11 | board = new Board(ROWS, COLUMNS); 12 | players = new Player[2]; 13 | players[0] = new Player(Color.Black); 14 | players[1] = new Player(Color.White); 15 | Automator.getInstance().initialize(players); // used for testing 16 | } 17 | 18 | public static Game getInstance() { 19 | if (instance == null) { 20 | instance = new Game(); 21 | } 22 | return instance; 23 | } 24 | 25 | public Board getBoard() { 26 | return board; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Location.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | public class Location { 4 | private int row; 5 | private int column; 6 | public Location(int r, int c) { 7 | row = r; 8 | column = c; 9 | } 10 | 11 | public boolean isSameAs(int r, int c) { 12 | return row == r && column == c; 13 | } 14 | 15 | public int getRow() { 16 | return row; 17 | } 18 | 19 | public int getColumn() { 20 | return column; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Piece.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | public class Piece { 4 | private Color color; 5 | 6 | public Piece(Color c) { 7 | color = c; 8 | } 9 | 10 | public void flip() { 11 | if (color == Color.Black) { 12 | color = Color.White; 13 | } else { 14 | color = Color.Black; 15 | } 16 | } 17 | 18 | public Color getColor() { 19 | return color; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Player.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | public class Player { 4 | private Color color; 5 | public Player(Color c) { 6 | color = c; 7 | } 8 | 9 | public int getScore() { 10 | return Game.getInstance().getBoard().getScoreForColor(color); 11 | } 12 | 13 | public boolean playPiece(int row, int column) { 14 | return Game.getInstance().getBoard().placeColor(row, column, color); 15 | } 16 | 17 | public Color getColor() { 18 | return color; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_8/Question.java: -------------------------------------------------------------------------------- 1 | package Question8_8; 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | import java.awt.Point; 6 | 7 | public class Question { 8 | 9 | public static void main(String[] args) { 10 | Game game = Game.getInstance(); 11 | game.getBoard().initialize(); 12 | game.getBoard().printBoard(); 13 | Automator automator = Automator.getInstance(); 14 | while (!automator.isOver() && automator.playRandom()) { 15 | } 16 | automator.printScores(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/Chapter 8/Question8_9/File.java: -------------------------------------------------------------------------------- 1 | package Question8_9; 2 | 3 | public class File extends Entry { 4 | private String content; 5 | private int size; 6 | 7 | public File(String n, Directory p, int sz) { 8 | super(n, p); 9 | size = sz; 10 | } 11 | 12 | public int size() { 13 | return size; 14 | } 15 | 16 | public String getContents() { 17 | return content; 18 | } 19 | 20 | public void setContents(String c) { 21 | content = c; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/Chapter 9/Question9_10/Box.java: -------------------------------------------------------------------------------- 1 | package Question9_10; 2 | 3 | public class Box { 4 | public int width; 5 | public int height; 6 | public int depth; 7 | public Box(int w, int h, int d) { 8 | width = w; 9 | height = h; 10 | depth = d; 11 | } 12 | 13 | public boolean canBeUnder(Box b) { 14 | if (width > b.width && height > b.height && depth > b.depth) { 15 | return true; 16 | } 17 | return false; 18 | } 19 | 20 | public boolean canBeAbove(Box b) { 21 | if (b == null) { 22 | return true; 23 | } 24 | if (width < b.width && height < b.height && depth < b.depth) { 25 | return true; 26 | } 27 | return false; 28 | } 29 | 30 | public String toString() { 31 | return "Box(" + width + "," + height + "," + depth + ")"; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /java/Chapter 9/Question9_6/QuestionB.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/Chapter 9/Question9_6/QuestionB.java -------------------------------------------------------------------------------- /java/CtCILibrary/CtCILibrary/AssortedMethods.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/java/CtCILibrary/CtCILibrary/AssortedMethods.java -------------------------------------------------------------------------------- /javascript/README.md: -------------------------------------------------------------------------------- 1 | #### Run the code and test 2 | This project uses Mocha and Chai for testing: 3 |
4 | ##### Install dependencies: 5 | 6 | ```bash 7 | npm install 8 | npm install -g mocha 9 | npm install -g chai 10 | 11 | ``` 12 | 13 | ##### Run tests: 14 | 15 | ```bash 16 | mocha --recursive 17 | ``` 18 | 19 | ##### Add new npm modules: 20 | 21 | ```bash 22 | npm install --save 23 | ``` 24 | -------------------------------------------------------------------------------- /javascript/lib/data-structures/chapter-1/1_1.js: -------------------------------------------------------------------------------- 1 | module.exports = Strings_1_1 = (function() { 2 | return { 3 | /* 4 | * Tests to see if string contains all unique chars. 5 | * @param {String} str - The string to be checked for uniqueness 6 | * @returns {Boolean} true if string has only unique chars. False if a duplicate exists 7 | */ 8 | isUnique: function(str) { 9 | var char_set = Array.apply(null, Array(256)).map(Boolean.prototype.valueOf, false); 10 | for (var i = 0; i < str.length; i++) { 11 | if (char_set[str[i].charCodeAt(0)]) { 12 | return false; 13 | } 14 | char_set[str[i].charCodeAt(0)] = true; 15 | } 16 | return true; 17 | } 18 | }; 19 | }()); 20 | -------------------------------------------------------------------------------- /javascript/lib/data-structures/chapter-1/1_2.js: -------------------------------------------------------------------------------- 1 | module.exports = Strings_1_2 = (function() { 2 | return { 3 | 4 | // NOT inline solution (left here to learn from) 5 | // reverseString: function(str) { 6 | // if (str.length === 0) { 7 | // return ''; 8 | // } 9 | // return str[str.length - 1] + arguments.callee(str.substr(0, str.length - 1)); 10 | // } 11 | // 12 | // 13 | 14 | /* 15 | * Reverses a string inline recursively 16 | * @param {String} str - The string to be reversed 17 | * @returns {String} The reversed string 18 | */ 19 | reverseString: function(str) { 20 | var len = str.length; 21 | if (len > 1) { 22 | return str[len - 1] + arguments.callee(str.substring(1, len - 1)) + str[0]; 23 | } 24 | return str; 25 | } 26 | }; 27 | }()); 28 | -------------------------------------------------------------------------------- /javascript/lib/data-structures/chapter-1/1_8.js: -------------------------------------------------------------------------------- 1 | module.exports = Strings_1_8 = (function() { 2 | var _isSubstring = function(str1, str2) { 3 | return str1.indexOf(str2) != -1 4 | } 5 | var _sameLengthAndNotBlank = function(str1, str2) { 6 | var len = str1.length; 7 | return len === str2.length && len > 0 8 | } 9 | return { 10 | isRotation: function(str1, str2) { 11 | if(!_sameLengthAndNotBlank(str1, str2)) return false; 12 | if(_isSubstring(str1+str1, str2)) return true; 13 | } 14 | } 15 | }()); 16 | -------------------------------------------------------------------------------- /javascript/lib/data-structures/chapter-2/2_3.js: -------------------------------------------------------------------------------- 1 | module.exports = LinkedList_2_3 = (function() { 2 | var deleteNode = function(node) { 3 | if(!node || !node.next) return; 4 | var next = node.next; 5 | node.data = next.data 6 | node.next = next.next; 7 | }; 8 | 9 | return { 10 | deleteNode: deleteNode 11 | } 12 | }()); 13 | -------------------------------------------------------------------------------- /javascript/lib/data-structures/chapter-3/3_5.js: -------------------------------------------------------------------------------- 1 | module.exports = MyQueue = (function(){ 2 | 3 | function MyQueue() { 4 | if (!(this instanceof MyQueue)) { 5 | return new MyQueue; 6 | } 7 | this.oldest = []; 8 | this.newest = []; 9 | }; 10 | 11 | function shiftStacks() { 12 | if(this.oldest.length == 0) { 13 | while(this.newest.length > 0) { 14 | this.oldest.push(this.newest.pop()); 15 | } 16 | } 17 | }; 18 | 19 | MyQueue.prototype.push = function(item) { 20 | this.newest.push(item); 21 | }; 22 | 23 | MyQueue.prototype.pop = function() { 24 | shiftStacks.call(this); 25 | return this.oldest.pop(); 26 | }; 27 | 28 | return MyQueue; 29 | })(); -------------------------------------------------------------------------------- /javascript/lib/data-structures/chapter-9/9_1.js: -------------------------------------------------------------------------------- 1 | module.exports = Staircase = (function(){ 2 | var memo = []; 3 | 4 | /* 5 | * Chapter 9 question 1 6 | * A child is running up a staircase with n steps, and can hop either 1 step, 7 | * 2 steps, or 3 steps at a time. Implement a method to count how many possible 8 | * ways the child can run up the stairs. 9 | */ 10 | var count = function(n) { 11 | return countWays(n, 0); 12 | }; 13 | 14 | var countWays = function(remaining){ 15 | if(remaining < 0) { 16 | return 0; 17 | } 18 | if(remaining == 0) { 19 | return 1; 20 | } 21 | if(memo[remaining]) { 22 | return memo[remaining]; 23 | } 24 | else { 25 | memo[remaining] = countWays(remaining-1) 26 | + countWays(remaining-2) 27 | + countWays(remaining-3); 28 | return memo[remaining]; 29 | } 30 | }; 31 | 32 | return { 33 | count: count 34 | }; 35 | })(); -------------------------------------------------------------------------------- /javascript/lib/data-structures/linked-list/node.js: -------------------------------------------------------------------------------- 1 | module.exports = Node = (function() { 2 | return function(data) { 3 | if(data === undefined) throw(new Error("data must be defined")) 4 | this.data = data; 5 | } 6 | }()); 7 | -------------------------------------------------------------------------------- /javascript/lib/index.js: -------------------------------------------------------------------------------- 1 | var requireDirectory = require('require-directory'); 2 | module.exports = requireDirectory(module); 3 | -------------------------------------------------------------------------------- /javascript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "CrackingJS", 3 | "version": "0.0.1", 4 | "description": "Data Structures and Algorithms in Javascript", 5 | "dependencies": { 6 | "mocha": "*", 7 | "chai": "*", 8 | "require-directory": "*", 9 | "sinon": "*" 10 | }, 11 | "devDependencies": { 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /javascript/test/data-structures/chapter-1/1_1_Spec.js: -------------------------------------------------------------------------------- 1 | require('../../test_helper'); 2 | describe(Strings_1_1, function () { 3 | describe('hasUniqueChars', function () { 4 | var str1, str2; 5 | beforeEach(function () { 6 | str1 = "abcdef"; 7 | str2 = "qwertyuiopasdfghjkl;'zxcvbnm,."; 8 | str3 = "abcdefa"; 9 | }); 10 | it('returns true if string is all unique chars', function () { 11 | expect(Strings_1_1.isUnique(str1)).to.be.true; 12 | }); 13 | it('returns false if string is all unique chars', function () { 14 | expect(Strings_1_1.isUnique(str2)).to.be.true; 15 | }); 16 | it('returns false if string contains duplicate chars', function () { 17 | expect(Strings_1_1.isUnique(str3)).to.be.false; 18 | }); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /javascript/test/data-structures/chapter-1/1_2_Spec.js: -------------------------------------------------------------------------------- 1 | require('../../test_helper'); 2 | describe(Strings_1_2, function () { 3 | describe('reverseString', function () { 4 | var str1, str2; 5 | beforeEach(function () { 6 | str1 = 'hello'; 7 | str2 = 'olleh'; 8 | str3 = 'abcdef'; 9 | str4 = 'aedcbb'; 10 | }); 11 | it('returns the reverse of hello', function () { 12 | expect(Strings_1_2.reverseString(str1)).to.equal(str2); 13 | }); 14 | it('returns the reverse of hello', function () { 15 | expect(Strings_1_2.reverseString(str3)).not.to.equal(str4); 16 | }); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /javascript/test/data-structures/chapter-1/1_3_Spec.js: -------------------------------------------------------------------------------- 1 | require('../../test_helper'); 2 | describe(Strings_1_3, function () { 3 | describe('isPermutation', function () { 4 | var str1, str2; 5 | beforeEach(function () { 6 | str1 = 'hello'; 7 | str2 = 'olleh'; 8 | str3 = 'abcdef'; 9 | }); 10 | it('knows reversed strings are permutations', function () { 11 | expect(Strings_1_3.isPermutation(str1, str2)).to.be.true; 12 | }); 13 | it('knows unrelated strings are not permutations', function () { 14 | expect(Strings_1_3.isPermutation(str1, str3)).to.be.false; 15 | }); 16 | }); 17 | }); 18 | -------------------------------------------------------------------------------- /javascript/test/data-structures/chapter-1/1_8_Spec.js: -------------------------------------------------------------------------------- 1 | require('../../test_helper'); 2 | describe(Strings_1_8, function () { 3 | describe('isRotation', function () { 4 | var str1, str2; 5 | beforeEach(function () { 6 | str1 = "waterbottle"; 7 | str2 = "erbottlewat"; 8 | }); 9 | it('returns false if strings are not same length', function () { 10 | expect(Strings_1_8.isRotation("hello", "")).to.be.false 11 | }); 12 | it('returns false if str1 is blank', function () { 13 | expect(Strings_1_8.isRotation("", "")).to.be.false 14 | }); 15 | it('returns true if str2 is rotation of str1', function () { 16 | expect(Strings_1_8.isRotation(str1, str2)).to.be.true 17 | }); 18 | }); 19 | }); 20 | -------------------------------------------------------------------------------- /javascript/test/data-structures/chapter-3/3_5_Spec.js: -------------------------------------------------------------------------------- 1 | require('../../test_helper'); 2 | describe('MyQueue', function () { 3 | describe('pop', function () { 4 | 5 | it('returns undefined in 0 length queue', function () { 6 | var q = new MyQueue(); 7 | var item = q.pop(); 8 | expect(item).to.be.undefined; 9 | }); 10 | 11 | it('returns 1st item in 1 length queue', function () { 12 | var q = new MyQueue(); 13 | q.push("foo"); 14 | var item = q.pop(); 15 | expect(item).to.be.equal("foo"); 16 | }); 17 | 18 | it('returns 2nd then 1st item in 2 length queue', function () { 19 | var q = new MyQueue(); 20 | q.push("foo"); 21 | q.push("bar"); 22 | var item = q.pop(); 23 | expect(item).to.be.equal("foo"); 24 | item = q.pop(); 25 | expect(item).to.be.equal("bar"); 26 | }); 27 | }); 28 | }); 29 | -------------------------------------------------------------------------------- /javascript/test/data-structures/chapter-9/9_1_Spec.js: -------------------------------------------------------------------------------- 1 | require('../../test_helper'); 2 | describe('Staircase', function () { 3 | describe('count', function () { 4 | 5 | it('returns 1 with 1 stair', function () { 6 | var count = Staircase.count(1); 7 | expect(count).to.equal(1); 8 | }); 9 | 10 | it('returns 2 with 2 stair', function () { 11 | var count = Staircase.count(2); 12 | expect(count).to.equal(2); 13 | }); 14 | it('returns 4 with 3 stair', function () { 15 | var count = Staircase.count(3); 16 | expect(count).to.equal(4); 17 | }); 18 | it('returns 7 with 4 stair', function () { 19 | var count = Staircase.count(4); 20 | expect(count).to.equal(7); 21 | }); 22 | 23 | it('returns 3831006429 with 37 stair', function () { 24 | var count = Staircase.count(37); 25 | expect(count).to.equal(3831006429); 26 | }); 27 | }); 28 | }); 29 | -------------------------------------------------------------------------------- /javascript/test/test_helper.js: -------------------------------------------------------------------------------- 1 | require('../lib'); 2 | module.exports = sinon = require("sinon"); 3 | module.exports = expect = require("chai").expect 4 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1-5/Question1-5.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1-5/Question1-5.xcodeproj/xcuserdata/rmoniz.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1-5/Question1-5/Question1-5-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header 3 | // 4 | // The contents of this file are implicitly included at the beginning of every source file. 5 | // 6 | 7 | #ifdef __OBJC__ 8 | #import 9 | #endif 10 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1-6/Question1-6.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1-6/Question1-6/Question1-6-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header 3 | // 4 | // The contents of this file are implicitly included at the beginning of every source file. 5 | // 6 | 7 | #ifdef __OBJC__ 8 | #import 9 | #endif 10 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1-6/Question1-6/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // Question1-6 4 | // 5 | // Created by Ryan Moniz on 11/29/2013. 6 | // Copyright (c) 2013 Ryan Moniz. All rights reserved. 7 | // 8 | //Given an image represented by an NxN matrix, where each pixel in the image is 9 | //4 bytes, write a method to rotate the image by 90 degrees. 10 | //Can you do this in place? 11 | // e.g. can you move the pixel value in 0,0 to its 90 degree destination in matrix 12 | // X Y Z A 1 X 13 | // 1 2 3 -> B 2 Y 14 | // A B C C 3 Z 15 | 16 | #import 17 | 18 | int main(int argc, const char * argv[]) 19 | { 20 | @autoreleasepool { 21 | 22 | 23 | } 24 | return 0; 25 | } 26 | 27 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1_1/Question1_1.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1_1/Question1_1.xcodeproj/xcuserdata/rmoniz.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1_1/Question1_1/Question1_1-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header 3 | // 4 | // The contents of this file are implicitly included at the beginning of every source file. 5 | // 6 | 7 | #ifdef __OBJC__ 8 | #import 9 | #endif 10 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1_3/Question1_3.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1_3/Question1_3.xcodeproj/xcuserdata/rmoniz.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1_3/Question1_3/Question1_3-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header 3 | // 4 | // The contents of this file are implicitly included at the beginning of every source file. 5 | // 6 | 7 | #ifdef __OBJC__ 8 | #import 9 | #endif 10 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1_4/Question1_4.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1_4/Question1_4.xcodeproj/xcuserdata/rmoniz.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /objective c/Chapter1/Question1_4/Question1_4/Question1_4-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header 3 | // 4 | // The contents of this file are implicitly included at the beginning of every source file. 5 | // 6 | 7 | #ifdef __OBJC__ 8 | #import 9 | #endif 10 | -------------------------------------------------------------------------------- /objective c/Introduction/CompareBinaryToHex/CompareBinaryToHex.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /objective c/Introduction/CompareBinaryToHex/CompareBinaryToHex/CompareBinaryToHex-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header 3 | // 4 | // The contents of this file are implicitly included at the beginning of every source file. 5 | // 6 | 7 | #ifdef __OBJC__ 8 | #import 9 | #endif 10 | -------------------------------------------------------------------------------- /objective c/Introduction/CompareBinaryToHex/CompareBinaryToHex/CompareBinaryToHex.h: -------------------------------------------------------------------------------- 1 | // 2 | // CompareBinaryToHex.h 3 | // CompareBinaryToHex 4 | // 5 | // Created by Ryan Moniz on 11/27/2013. 6 | // Copyright (c) 2013 Ryan Moniz. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface CompareBinaryToHex : NSObject 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /objective c/Introduction/CompareBinaryToHex/CompareBinaryToHex/CompareBinaryToHex.m: -------------------------------------------------------------------------------- 1 | // 2 | // CompareBinaryToHex.m 3 | // CompareBinaryToHex 4 | // 5 | // Created by Ryan Moniz on 11/27/2013. 6 | // Copyright (c) 2013 Ryan Moniz. All rights reserved. 7 | // 8 | 9 | #import "CompareBinaryToHex.h" 10 | 11 | @implementation CompareBinaryToHex 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /objective c/Introduction/SwapMinMax/SwapMinMax.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /objective c/Introduction/SwapMinMax/SwapMinMax.xcodeproj/xcuserdata/rmoniz.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /objective c/Introduction/SwapMinMax/SwapMinMax/SwapMinMax-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header 3 | // 4 | // The contents of this file are implicitly included at the beginning of every source file. 5 | // 6 | 7 | #ifdef __OBJC__ 8 | #import 9 | #endif 10 | -------------------------------------------------------------------------------- /objective c/README.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/objective c/README.txt -------------------------------------------------------------------------------- /python/Chapter 1/Question1_1/alluniq.py: -------------------------------------------------------------------------------- 1 | def allunique(s): 2 | charsTable = set() 3 | for c in s: 4 | if c in charsTable: 5 | return False 6 | charsTable.add(c) 7 | return True 8 | 9 | def pairs(seq): 10 | n = len(seq) 11 | for i in range(n): 12 | yield seq[i], seq[(i + 1) % n] 13 | 14 | def allunique2(s): 15 | srtStr = sorted(s) 16 | for (c1, c2) in pairs(srtStr): 17 | if c1 == c2: 18 | return False 19 | return True 20 | 21 | if __name__ == '__main__': 22 | words = ('mary', 'ariadni') 23 | for w in words: 24 | print('allunique({}): {}'.format(w, allunique(w))) 25 | print('allunique2({}): {}'.format(w, allunique2(w))) 26 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_2/ChapQ1.2.py: -------------------------------------------------------------------------------- 1 | #Implement a function that reverses a string 2 | 3 | #using recursion here to avoid recopying the string, as described in the discussion of "string buffer". 4 | 5 | def reverseStringRecursive(str1): 6 | if str1 != "": 7 | return str1[-1:] + reverseStringRecursive(str1[:-1]) 8 | else: 9 | return "" 10 | 11 | #testing 12 | 13 | palindrome = "abcdedcba" 14 | nonpalindrome = "hello!" 15 | 16 | #palindrome can be reversed and would still be equal to itself, by definition. 17 | if palindrome == reverseStringRecursive(palindrome): 18 | print "Test 1 passed" 19 | if nonpalindrome != reverseStringRecursive(nonpalindrome): 20 | print "Test 2 passed" 21 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_2/revstr.py: -------------------------------------------------------------------------------- 1 | def revStr(s): 2 | return s[::-1] 3 | 4 | if __name__ == '__main__': 5 | words = ('mary', 'anna', 'peter') 6 | for w in words: 7 | print('revStr({}): {}'.format(w, revStr(w))) 8 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_3/anagram.py: -------------------------------------------------------------------------------- 1 | def anagram(s1, s2): 2 | s1 = s1.lower() 3 | s2 = s2.lower() 4 | # sort, convert to str and strip 5 | s1 = ''.join(sorted(s1)).strip() 6 | s2 = ''.join(sorted(s2)).strip() 7 | return s1 == s2 8 | 9 | def anagram2(string1, string2): 10 | ''' We just check if the counts of each character are the same ''' 11 | from collections import Counter 12 | return Counter(string1)==Counter(string2) 13 | 14 | if __name__ == '__main__': 15 | words = ( ('So dark the con of man', 'Madonna of The Rocks'), 16 | (' ba ', ' Ab '), 17 | ('anne', 'annea') ) 18 | for w1, w2 in words: 19 | print('anagram({}, {}): {}'.format(w1, w2, anagram(w1, w2))) 20 | print('anagram({}, {}): {}'.format(w1, w2, anagram2(w1, w2))) 21 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_4/Q1_4.py: -------------------------------------------------------------------------------- 1 | """write a method to replace all space in a string with '%20' 2 | """ 3 | 4 | # using a list to store each char and change space to '%20', then join list into a string 5 | def replaceSpace(string): 6 | charList = [] 7 | for char in string: 8 | if char == ' ': 9 | char = '%20' 10 | charList.append(char) 11 | return ''.join(charList) 12 | 13 | #test 14 | inputStr = " Smith q m " 15 | expectOutput = "%20Smith%20%20%20%20q%20m%20" 16 | if replaceSpace(inputStr) == expectOutput: 17 | print "test passed" 18 | else: 19 | print "test failed" 20 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_4/replace.py: -------------------------------------------------------------------------------- 1 | def replaceSpaces(s): 2 | return '%20'.join(s.split()) 3 | 4 | def replace_spaces(string, size): 5 | return string[:size].replace(' ', '%20') 6 | 7 | if __name__ == '__main__': 8 | words = ( 'hello world ', ' mr. john ', '', ' ', ) 9 | for w in words: 10 | print('replaceSpaces({}): {}'.format(w, replaceSpaces(w))) 11 | -------------------------------------------------------------------------------- /python/Chapter 1/Question1_8/ChapQ1.8.py: -------------------------------------------------------------------------------- 1 | #Assume you have a method isSubstring which checks if one word is a 2 | #substring of another. Given two strings, s1 and s2, write code to check if s2 is 3 | #a rotation of s1 using only one call to isSubstring (e.g.,"waterbottle" is a rotation of "erbottlewat"). 4 | 5 | def isSubstring(s1,s2): 6 | return s1.find(s2) > -1 7 | 8 | def rotatedStringHasSubstring(s1,s2): 9 | #doubling the string ensures a complete substring regardless of rotation 10 | if len(s2)!=len(s1): 11 | return False 12 | doubles1 = s1 + s1 13 | return isSubstring(doubles1,s2) 14 | 15 | 16 | 17 | #testing 18 | if rotatedStringHasSubstring("waterbottle","erbottlewat"): 19 | print "Test 1 Passed" 20 | 21 | if not rotatedStringHasSubstring("waterbottle","nope"): 22 | print "Test 2 Passed" 23 | 24 | if not rotatedStringHasSubstring("waterbottlewater","waterbottle"): 25 | print "Test 3 Passed" 26 | -------------------------------------------------------------------------------- /python/Chapter 2/Question2_2.py: -------------------------------------------------------------------------------- 1 | from classes.LinkedList import * 2 | 3 | 4 | # if k = 1, return the last element 5 | def kth_to_last(linkedlist, k): 6 | if k <= 0: 7 | return "invalid k" 8 | pointer2 = linkedlist.head 9 | for i in range(k-1): 10 | if pointer2.next != None: 11 | pointer2 = pointer2.next 12 | else: 13 | return "k exceeds the length of linkedlist" 14 | pointer1 = linkedlist.head 15 | while pointer2.next != None: 16 | pointer2 = pointer2.next 17 | pointer1 = pointer1.next 18 | return pointer1 19 | 20 | 21 | 22 | #---------------test------------------ 23 | L = randomLinkedList(8, 0, 100) 24 | print L 25 | print "The 3th to last element is", kth_to_last(L, 3) 26 | -------------------------------------------------------------------------------- /python/Chapter 2/Question2_3.py: -------------------------------------------------------------------------------- 1 | from classes.LinkedList import * 2 | 3 | def deleteNode(linkedlist, node): 4 | if node.next != None: 5 | node.value = node.next.value 6 | node.next = node.next.next 7 | 8 | # if the given node is the last one, no way to delete it. 9 | # Here we set the last one's value to None 10 | else: 11 | node.value = None 12 | 13 | 14 | 15 | #-----------test-------------- 16 | L = randomLinkedList(5, 0, 100) 17 | node = L.head.next.next # Given access to the 3rd node 18 | print L 19 | print "After deleting the node" 20 | deleteNode(L, node) 21 | print L -------------------------------------------------------------------------------- /python/Chapter 2/Question2_4.py: -------------------------------------------------------------------------------- 1 | from classes.LinkedList import * 2 | 3 | def partition(linkedlist, x): 4 | if linkedlist.head != None: 5 | p1 = linkedlist.head 6 | p2 = linkedlist.head.next 7 | while p2 != None: 8 | if p2.value < x: 9 | p1.next = p2.next 10 | p2.next = linkedlist.head 11 | linkedlist.head = p2 12 | p2 = p1.next 13 | else: 14 | p1 = p1.next 15 | p2 = p1.next 16 | 17 | 18 | 19 | #----------------test----------------- 20 | L = randomLinkedList(10, 0, 50) 21 | x = 25 22 | 23 | print L, " , x=25" 24 | partition(L, x) 25 | print L 26 | -------------------------------------------------------------------------------- /python/Chapter 2/classes/LinkedList.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/python/Chapter 2/classes/LinkedList.pyc -------------------------------------------------------------------------------- /python/Chapter 2/classes/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/python/Chapter 2/classes/__init__.py -------------------------------------------------------------------------------- /python/Chapter 2/classes/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careercup/ctci/48950f46d346cd3472aa276443f20db6830ed9e0/python/Chapter 2/classes/__init__.pyc -------------------------------------------------------------------------------- /python/Chapter 3/Question3_4/Q3_4.py: -------------------------------------------------------------------------------- 1 | class Hanoi: 2 | 3 | def __init__(self, size): 4 | self.towers = [[], [], []] 5 | self.size = size 6 | self.towers[0] = [x for x in range(size, 0, -1)] 7 | 8 | def playHanoi(self): 9 | self.printTowers() 10 | self.moveDisk(self.size, 1, 2, 3) 11 | self.printTowers() 12 | 13 | def moveDisk(self, size, fr, helper, to): 14 | if size == 1: 15 | data = self.towers[fr-1].pop() 16 | self.towers[to-1].append(data) 17 | print "Disk", data, ": Tower", fr, "->", to 18 | else: 19 | self.moveDisk(size - 1, fr, to, helper) 20 | self.moveDisk(1, fr, helper, to) 21 | self.moveDisk(size - 1, helper, fr, to) 22 | 23 | def printTowers(self): 24 | for i in self.towers: 25 | print i 26 | 27 | 28 | 29 | 30 | #----------------test--------------- 31 | hanoi = Hanoi(4) 32 | hanoi.playHanoi() 33 | -------------------------------------------------------------------------------- /python/Chapter 3/Question3_5/ChapQ3.5.py: -------------------------------------------------------------------------------- 1 | class MyQueue(object): 2 | def __init__(self): 3 | self.s = [[], []] 4 | def push(self, value): 5 | self.s[0].append(value) 6 | def pop(self): 7 | if len(self.s[1]) > 0: 8 | return self.s[1].pop() 9 | while len(self.s[0]) > 0: 10 | self.s[1].append(self.s[0].pop()) 11 | if len(self.s[1]) == 0: 12 | return None 13 | return self.s[1].pop() 14 | 15 | def length(self): 16 | return len(self.s[0]) + len(self.s[1]) 17 | 18 | def empty(self): 19 | return self.length() == 0 20 | 21 | q1 = MyQueue() 22 | from Queue import Queue 23 | q2 = Queue() 24 | 25 | #testing 26 | from random import randrange 27 | for step in xrange(20): 28 | operation = randrange(10) 29 | if operation < 7: 30 | q1.push(operation) 31 | q2.put(operation) 32 | print "push", operation 33 | elif not q2.empty(): 34 | print "pop", q1.pop(), q2.get() 35 | while not q2.empty(): 36 | print "pop", q1.pop(), q2.get() -------------------------------------------------------------------------------- /python/Chapter 3/Question3_6/ChapQ3.6.py: -------------------------------------------------------------------------------- 1 | class Stack(list): 2 | def peak(self): 3 | return self[-1] 4 | def push(self, item): 5 | self.append(item) 6 | def empty(self): 7 | return len(self) == 0 8 | 9 | def sort_stack(s): 10 | r = Stack() 11 | while not s.empty(): 12 | tmp = s.pop() 13 | while not r.empty() and r.peak() > tmp: 14 | s.push(r.pop()) 15 | r.push(tmp) 16 | while not s.empty() and s.peak() >= r.peak(): 17 | #warning, >= here 18 | r.push(s.pop()) 19 | return r 20 | 21 | #testing 22 | from random import randrange 23 | test_items = [randrange(20) for x in xrange(20)] 24 | print test_items 25 | S = Stack() 26 | for item in test_items: 27 | S.push(item) 28 | S = Stack.sort_stack(S) 29 | for i, item in enumerate(sorted(test_items)): 30 | print "item", item, S[i] 31 | -------------------------------------------------------------------------------- /python/Chapter 4/Question4_9/BinaryTreeNode.py: -------------------------------------------------------------------------------- 1 | class BinaryTreeNode: 2 | 3 | def __init__(self, value): 4 | self.value = value 5 | self.left = None 6 | self.right = None 7 | self.parent = None 8 | 9 | def setLeft(self, leftvalue): 10 | leftnode = BinaryTreeNode(leftvalue) 11 | self.left = leftnode 12 | if leftnode != None: 13 | leftnode.parent = self 14 | 15 | def setRight(self, rightvalue): 16 | rightnode = BinaryTreeNode(rightvalue) 17 | self.right = rightnode 18 | if rightnode != None: 19 | rightnode.parent = self 20 | -------------------------------------------------------------------------------- /ruby/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | gem 'rspec' 3 | -------------------------------------------------------------------------------- /ruby/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | diff-lcs (1.2.5) 5 | rspec (2.14.1) 6 | rspec-core (~> 2.14.0) 7 | rspec-expectations (~> 2.14.0) 8 | rspec-mocks (~> 2.14.0) 9 | rspec-core (2.14.8) 10 | rspec-expectations (2.14.5) 11 | diff-lcs (>= 1.1.3, < 2.0) 12 | rspec-mocks (2.14.6) 13 | 14 | PLATFORMS 15 | ruby 16 | 17 | DEPENDENCIES 18 | rspec 19 | -------------------------------------------------------------------------------- /ruby/lib/data-structures/chapter-1/1_1.rb: -------------------------------------------------------------------------------- 1 | module Strings 2 | extend self 3 | 4 | # Example Usage 5 | # is_string_unique?("ABCDEFG") == true 6 | # is_string_unique?("ABCgDEFG") == true 7 | # is_string_unique?("ABCgDEFGG") == false 8 | 9 | def is_string_unique?(str) 10 | # If the string doesn't meet the minimum requirements 11 | return false if str.length > 128 12 | 13 | # Store the keys in our hash 14 | chars = {} 15 | str.each_byte do |s| 16 | # Break out as early as we can 17 | return false if chars.has_key? s 18 | chars[s] = true 19 | end 20 | 21 | true 22 | end 23 | 24 | end 25 | -------------------------------------------------------------------------------- /ruby/lib/data-structures/chapter-1/1_8.rb: -------------------------------------------------------------------------------- 1 | module Strings 2 | extend self 3 | def rotation? str1, str2 4 | return false if str1.length != str2.length || str1.length.zero? 5 | "#{str1}#{str1}".include?(str2) 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /ruby/lib/data-structures/chapter-2/2_1.rb: -------------------------------------------------------------------------------- 1 | require_relative '../linked-list/singly_linked_list' 2 | module LinkedListUtils 3 | def remove_dups 4 | return if self.head.nil? || self.head.next.nil? 5 | nodes = Hash.new 6 | prev = self.head 7 | self.each do |node| 8 | if nodes[node.data] 9 | prev.next = node.next 10 | else 11 | nodes[node.data] = true 12 | prev = node 13 | end 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /ruby/lib/data-structures/chapter-2/2_3.rb: -------------------------------------------------------------------------------- 1 | # see linked-list/singly_linked_list and linked-list/doubly_linked_list #remove method. This method is also tested in their respective _spec files. 2 | -------------------------------------------------------------------------------- /ruby/lib/data-structures/chapter-2/2_4.rb: -------------------------------------------------------------------------------- 1 | module LinkedListUtils 2 | def partition_on k 3 | left = self.class.new 4 | right = self.class.new 5 | self.each do |node| 6 | left.push_top node.data if node.data < k 7 | right.push_top node.data if node.data >= k 8 | end 9 | left.tail.next = right.head 10 | left 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /ruby/lib/data-structures/chapter-2/2_6.rb: -------------------------------------------------------------------------------- 1 | module LinkedListUtils 2 | def looped? 3 | slow = self.head 4 | fast = self.head 5 | 6 | return false if fast.nil? || fast.next.nil? 7 | 8 | until(fast.nil? || fast.next.nil?) do 9 | slow = slow.next; 10 | fast = fast.next.next; 11 | return true if slow == fast 12 | end 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /ruby/lib/data-structures/hash-table/hash_table.rb: -------------------------------------------------------------------------------- 1 | require_relative '../linked-list/singly_linked_list' 2 | Entry = Struct.new(:key, :value) 3 | class HashTable 4 | HASH_FUNCTION_FACTOR = 10 # this is a simple solution, we should use array_length, resize and rehash. 5 | def initialize 6 | @map = [] 7 | end 8 | 9 | def []= key, value 10 | raise UniqueKeyError.new("key must be unique") if self[key] 11 | hashed_key = self.hash_func(key) 12 | entry = Entry.new(key, value) 13 | @map[hashed_key] = SinglyLinkedList.new(entry) and return unless @map[hashed_key] 14 | @map[hashed_key].push_top(entry) 15 | end 16 | 17 | def [] key 18 | if list = @map[self.hash_func(key)] 19 | entry = list.detect {|node| node.data.key == key } 20 | entry.data.value if entry 21 | end 22 | end 23 | 24 | def hash_func key 25 | key.length % HASH_FUNCTION_FACTOR 26 | end 27 | end 28 | 29 | class UniqueKeyError < StandardError;end 30 | -------------------------------------------------------------------------------- /ruby/lib/data-structures/linked-list/node.rb: -------------------------------------------------------------------------------- 1 | class Node 2 | attr_reader :data 3 | attr_accessor :next, :prev 4 | def initialize data 5 | @data = data 6 | @next = nil 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /ruby/spec/data-structures/chapter-1/1_5_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../../spec_helper' 2 | describe Strings do 3 | context "#compress_string" do 4 | 5 | let(:uncompressed) { "abbbcccaadee" } 6 | let(:compressed) { "a1b3c3a2d1e2" } 7 | 8 | it "returns blank if string is blank or nil" do 9 | expect(Strings.compress_string("")).to eq("") 10 | expect(Strings.compress_string(nil)).to eq("") 11 | end 12 | 13 | it "returns compressed version of string" do 14 | expect(Strings.compress_string(uncompressed)).to eq(compressed) 15 | end 16 | 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /ruby/spec/data-structures/chapter-1/1_8_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../../spec_helper' 2 | describe Strings do 3 | context "#rotation?" do 4 | let(:str) { "waterbottle" } 5 | let(:rot) { "erbottlewat" } 6 | context "solely using string include?" do 7 | it "returns false if strings are different lengths and/or length is 0" do 8 | expect(Strings.rotation?(str, "hey")).to be_false 9 | expect(Strings.rotation?("", "")).to be_false 10 | end 11 | 12 | it "returns false if str2 is not a rotation of str 1" do 13 | expect(Strings.rotation?(str, "olleh")).to be_false 14 | end 15 | 16 | it "returns true if string is rotation of another string" do 17 | String.any_instance.should_receive(:include?).exactly(:once).and_call_original 18 | expect(Strings.rotation?(str, rot)).to be_true 19 | end 20 | end 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /ruby/spec/data-structures/chapter-2/2_1_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../../spec_helper' 2 | describe LinkedListUtils do 3 | class SinglyLinkedList 4 | include LinkedListUtils 5 | end 6 | context "#remove_dups" do 7 | let(:nodes) { %w{one two one three one two four} } 8 | let(:list) { SinglyLinkedList.new } 9 | before(:each) do 10 | nodes.each do |node| 11 | list.push_bottom node 12 | end 13 | end 14 | it "remove duplicate values from the list" do 15 | dups = list.remove_dups 16 | expect(list.map(&:data)).to eq %w{one two three four} 17 | end 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /ruby/spec/data-structures/chapter-2/2_4_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../../spec_helper' 2 | describe LinkedListUtils do 3 | class SinglyLinkedList 4 | include LinkedListUtils 5 | end 6 | context "#partition_on" do 7 | let(:nodes) { [3, 4, 2, 1 , 5] } 8 | let(:list) { SinglyLinkedList.new } 9 | before(:each) do 10 | nodes.each do |node| 11 | list.push_bottom node 12 | end 13 | end 14 | it "retuns the partioned linked list" do 15 | expect(list.partition_on(3).map(&:data)).to eq [1, 2, 5, 4, 3] 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /ruby/spec/data-structures/chapter-2/2_6_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative '../../spec_helper' 2 | describe LinkedListUtils do 3 | class SinglyLinkedList 4 | include LinkedListUtils 5 | end 6 | context "#looped?" do 7 | let(:nodes) { [1, 2, 3, 4, 5] } 8 | let(:list) { SinglyLinkedList.new } 9 | before(:each) do 10 | nodes.each do |node| 11 | list.push_bottom node 12 | end 13 | end 14 | it "retuns true if linked list is looped" do 15 | list.tail.next = list.head 16 | expect(list.looped?).to be_true 17 | end 18 | it "retuns false if linked list is not looped" do 19 | expect(list.looped?).to be_false 20 | end 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /ruby/spec/data-structures/linked-list/node_spec.rb: -------------------------------------------------------------------------------- 1 | describe Node do 2 | let(:data) { "sweet" } 3 | let(:next_node) { "awesome" } 4 | let(:node) { Node.new data } 5 | context "#data" do 6 | it "is initialized to the given data" do 7 | expect(node.data).to eq data 8 | end 9 | end 10 | context "#next" do 11 | it "defaults to nil" do 12 | expect(node.next).to be_nil 13 | end 14 | end 15 | context "#next=" do 16 | it "sets the next" do 17 | node.next = next_node 18 | expect(node.next).to eq next_node 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /ruby/spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | require 'rspec' 2 | # require 'debugger';debugger;1 3 | Dir["./lib/**/*.rb"].each {|f| require f} 4 | -------------------------------------------------------------------------------- /scala/build.sbt: -------------------------------------------------------------------------------- 1 | name := "scala-slution" 2 | 3 | organization := "fsi206914" 4 | 5 | version := "1.0" 6 | 7 | scalaVersion := "2.11.2" 8 | 9 | scalacOptions ++= Seq("-unchecked", "-deprecation") 10 | 11 | libraryDependencies ++= Seq("joda-time" % "joda-time" % "1.6", 12 | "org.scalatest" %% "scalatest" % "2.2.0" % "test", 13 | "org.specs2" %% "specs2" % "2.3.12" % "test", 14 | "junit" % "junit" % "4.7" % "test" 15 | ) 16 | -------------------------------------------------------------------------------- /scala/src/test/scala/chapter2/chapter2Test.scala: -------------------------------------------------------------------------------- 1 | package chapter2 2 | 3 | import org.junit.runner.RunWith 4 | import org.specs2.mutable.Specification 5 | import org.specs2.runner.JUnitRunner 6 | 7 | /** 8 | * Chapter 2: 9 | */ 10 | @RunWith(classOf[JUnitRunner]) 11 | class Chapter2Test extends Specification { 12 | 13 | import Chapter2._ 14 | val aNodeList = Array(1,2,3,4,2,3); 15 | val NodeList2 = Array(1,2,3,4) 16 | /* 17 | *Question2_1 18 | */ 19 | "Question2_1" should { 20 | "remove all duplicate characters" in { 21 | val head = createNodeList(aNodeList) 22 | removeDupliEles(head) === createNodeList(NodeList2) 23 | } 24 | } 25 | 26 | /*==============================================================*/ 27 | /* 28 | *Question2_2 29 | */ 30 | "Question2_2" should { 31 | "find kth to last element of a singly linked list" in { 32 | val head = createNodeList(aNodeList) 33 | nthToLast(head, 3) === 4 34 | } 35 | } 36 | } 37 | --------------------------------------------------------------------------------