Cracking The Coding Interview

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

11.5 Test a Pen: How would you test a pen?

Interviewer: How would you test a pen? • Candidate: Let me find out a bit about the pen.Who is going to use the pen? • Interviewer: Probably children. • Candidate: Okay, that's interesting. What will they be doing with it? Will they be writing, drawing, or doing something else with it? Interviewer: Drawing. • Candidate: Okay, great. On what? Paper? Clothing? Walls? • Interviewer: On clothing. Candidate: Great. What kind of tip does the pen have? Felt? Ballpoint? Is it intended to wash off, or is it intended to be permanent? Interviewer: It's intended to wash off.

8.10 Paint Fill: Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color, fill in the surrounding area until the color changes from the original color.

enum Color { boolean PaintFill(Color[][] screen, int r, int c, Color ncolor) { boolean PaintFill(Color[][] screen, int r, int c, Color ocolor, Color ncolor) {

4.1 Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

enum State { boolean search(Graph g, Node start, Node end) {

5.6 Conversion: Write a function to determine the number of bits you would need to flip to convert integer A to integer B. EXAMPLE Input: 29 (or: 111(1), 15 (or: (1111) Output: 2

int bitSwapRequired(int a, int b) {

4.12 Paths with Sum: You are given a binary tree in which each node contains an integer value (which might be positive or negative). Design an algorithm to count the number of paths that sum to a given value.The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

int countPathsWithSum(TreeNode root, int targetSum) { int countPathsWithSumFromNode(TreeNode node, int targetSum, int currentSum) { int countpathsWithSum(TreeNode root, int targetSum) { int countpathsWithSum(TreeNode root, int targetSum, int runningSum, HashMap<Integer, Integer> pathCount) { void incrementHashTable(HashMap<Integer, Integer> hashTable, int key, int delta) {

8.1 Triple Step: A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs.

int countWays(int n) { int countWays(int n, int[) memo) {

8.13 Stack of Boxes: You have a stack of n boxes, with widths Wi' heights hi' and depths d1• The boxes cannot be rotated and can only be stacked on top of one another if each box in the stack is strictly larger than the box above it in width, height. and depth. Implement a method to compute the height of the tallest possible stack. The height of a stack is the sum of the heights of each box.

int createStack(ArrayList<Box> boxes) { int createStack(ArrayList<Box> boxes, int bottomlndex) { class BoxComparator implements Comparator<Box> { int createStack(ArrayList<Box> boxes) { int createStack(ArrayList<Box> boxes, int bottomlndex, int[] stackMap) { int createStack(ArrayList<Box> boxes) { int createStack(ArrayList<BOx> boxes, Box bottom, int offset, int[] stackMap) {

4.4 Check Balanced: Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.

int getHeight(TreeNode root) { boolean isBalanced(TreeNode root) { int checkHeight(TreeNode root) { boolean isBalanced(TreeNode root) {

5.4 Next Number: 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.

int getNext(int n) { int getPrev(int n) {

10.10 Rank from Stream: Imagine you are reading in a stream of integers. Periodically, you wish to be able to look up the rank of a number x (the number of values less than or equal to x). Implement the data structures and algorithms to support these operations. That is, implement the method track(int x), which is called when each number is generated, and the method getRankOfNumber(int x), which returns the number of values less than or equal to x (not including x itself). EXAMPLE Stream (in order o f appearance) : 5, 1, 4, 4, 5, 9, 7, 13, 3 getRankOfNumber(1) = 0 getRankOfNumber(3) =1 getRankOfNumber(4) 3

int getRank(Node node, int x) { void track(int number) { int getRankOfNumber(int number) { public class RankNode { public void insert(int d) { public int getRank(int d) {

5.3 Flip Bit to Win: You have an integer and you can flip exactly one bit from a 0 to a 1. Write code to find the length of the longest sequence of 1s you could create.

int longestSequence(int n) { ArrayList<Integer> getAlternatingSequences(int n) { int findLongestSequence(ArrayList<Integer> seq) { --------- int flipBit(int a) {

8.3 Magic Index: A magic index in an array A[1. .. n-1] is defined to be an index such that A[ i] i. Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A.

int magicSlow(int[] array) { int magicFast(int[] array) { int magicFast(int[] array) int start) int end) {

8.11 Coins: Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent), write code to calculate the number of ways of representing n cents.

int makeChange(int amount, int[] denoms, int index) { int makeChange(int n) { int makeChange(int n) { int makeChange(int amount, int[] denoms, int index, int[][] map) {

8.5 Recursive Multiply: Write a recursive function to multiply two positive integers without using the * operator (or / operator). You can use addition, subtraction, and bit shifting, but you should minimize the number of those operations.

int minProduct(int a, int b) { int minProductHelper(int smallerJ int bigger) { int minProduct(int a, int b) { int minProduct(int smallerJ int biggerJ int[] memo) { int minProduct(int a, int b) { int minProductHelper(int smaller, int bigger) {

2.2 Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list.

int nthToLastR1(LinkedListNode head, int n) { LinkedListNode nthToLastR2(LinkedListNode head, int n, IntWrapper i) { Result nthToLastR3Helper(LinkedListNode head, int k) { LinkedListNode nthToLastR3(LinkedListNode head, int k) { LinkedListNode nthToLast(LinkedListNode head, int n) { void main(String[] args) {

10.4 Sorted Search, No Size: You are given an array-like data structure Listy which lacks a size method. It does, however, have an elementAt (i) method that returns the element at index i in 0(1) time. If i is beyond the bounds of the data structure, it returns - 1. (For this reason, the data structure only supports positive integers.) Given a Listy which contains sorted, positive integers, find the index at which an element x occurs. If x occurs multiple times, you may return any index.

int search(Listy list, int value) { int binarySearch(Listy list, int value, int low, int high) {

10.5 Sparse Search: Given a sorted array of strings that is interspersed with empty strings, write a method to find the location of a given string.

int search(String[] strings, String str, int first, int last) {

10.3 Search in Rotated Array: Given a sorted array of n integers that has been rotated an unknown number of times, write code to find an element in the array. You may assume that the array was originally sorted in increasing order.

int search(int a[], int left, int right, int x) {

1.6 String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed"string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).

int setChar(char[] array, char c, int index, int count) { int countCompression(String str) { String compressBad(String str) { String compressBetter(String str) { String compressAlternate(String str) { void main(String[] args) {

5.7 Pairwise Swap: Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on).

int swapOddEvenBits(int x) {

5.1 Insertion: You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to insert Minto N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. That is, if M= 18811, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because M could not fully fit between bit 3 and bit 2.

int updateBits(int n, int m, int i, int j) {

11.2 Random Crashes: You are given the source to an application which crashes when it is run. After running it ten times in a debugger, you find it never crashes in the same place. The application is single threaded, and uses only the C standard library. What programming errors could be causing this crash? How would you test each one?

"RandomVariable:"Theapplicationmayusesomerandomnumberorvariablecomponentthatmaynot be fixed for every execution of the program. Examples include user input, a random number generated by the program, or the time of day. Uninitialized Variable: The application could have an uninitialized variable which, in some languages, may cause it to take on an arbitrary value. The values of this variable could result in the code taking a slightly different path each time. 3. Memory Leak: The program may have run out of memory. Other culprits are totally random for each run since it depends on the number of processes running at that particular time. This also includes heap overflow or corruption of data on the stack. 4. External Dependencies: The program may depend on another application, machine, or resource. If there are multiple dependencies, the program could crash at any point.

5.5 Debugger: Explain what the following code does: «n & (n-1)) == 0).

((n & (n-1)) == 0)checksifnisapowerof2(orifnis0)

10.11 Peaks and Valleys: In an array of integers, a "peak" is an element which is greater than or equal to the adjacent integers and a "valley" is an element which is less than or equal to the adjacent integers. For example, in the array {S, 8, 6, 2, 3, 4, 6}, {8, 6} are peaks and {S, 2} are valleys. Given an array of integers, sort the array into an alternating sequence of peaks and valleys. EXAMPLE Input: {5, 3, 1, 2, 3} Output: {5, 1, 3, 2, 3}

1. Sort the array in ascending order. 2. Iterate through the elements, starting from index 1 (not 0) and jumping two elements at a time. 3. At each element, swap it with the previous element. void sortValleyPeak(int[] array) { void swap(int[] array, int left, int right) { void sortvalleyPeak(int[] array) { int maxlndex(int[] array, int a, int b, int c) {

13.5 TreeMap, HashMap, LinkedHashMap: Explain the differences between TreeMap, HashMap, and LinkedHashMap. Provide an example of when each one would be best.

All offer a key->value map and a way to iterate through the keys. The most important distinction between these classes is the time guarantees and the ordering of the keys. • HashMap offers O( 1) lookup and insertion. If you iterate through the keys, though, the ordering of the keys is essentially arbitrary. It is implemented by an array of linked lists. • TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you need to iterate through the keys in sorted order, you can.This means that keys must implement the Comparable interface. TreeMap is implemented by a Red-BlackTree. LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by their insertion order. It is implemented by doubly-linked buckets. When might you need ordering in real life? • Suppose you were creating a mapping of names to Person objects. You might want to periodically output the people in alphabetical order by name. A TreeMap lets you do this, • A TreeMap also offers a way to, given a name, output the next 10 people, This could be useful for a "More" function in many applications. • A LinkedHashMap is useful whenever you need the ordering of keys to match the ordering of inser- tion.This might be useful in a caching situation, when you want to delete the oldest item. Generally, unless there is a reason not to, you would use HashMap.That is, if you need to get the keys back in insertion order, then use LinkedHashMap. lfyou need to get the keys back in their true/natural order, then use TreeMap, Otherwise, HashMap is probably best It is typically faster and requires less overhead.

8.7 Permutations without Dups: Write a method to compute all permutations of a string of unique characters .

ArrayList <String> getPerms(String str) { String insertCharAt(String word, char c, int i) { ArrayList<String> getPerms(String remainder) { ArrayList<String> getPerms(String str) { void getPerms(String prefix, String remainder, ArrayList<String> result) {

8.4 Power Set: Write a method to return all subsets of a set.

ArrayList<ArrayList<Integer» getSubsets(ArrayList<Integer> set, int index) { ArrayList<ArrayList<Integer» getSubsets2(ArrayList<Integer> set) { <ArrayList<Integer»convertlntToSet(int x, ArrayList<Integer> set) {

4.9 BST Sequences: A binary search tree was created by traversing through an array from left to right and inserting each element. Given a binary search tree with distinct elements, print all possible arrays that could have led to this tree.

ArrayList<LinkedList<Integer» allSequences(TreeNode node) { void weaveLists(LinkedList<Integer> first, LinkedList<Integer> second, ArrayList<LinkedList<Integer» results, LinkedList<Integer> prefix) {

8.2 Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right.

ArrayList<Point> getPath(boolean[][] maze) { boolean getPath(boolean[][] maze, int row, int col, ArrayList<Point> path) {

8.8 Permutations with Duplicates: Write a method to compute all permutations of a string whose characters are not necessarily unique. The list of permutations should not have duplicates.

ArrayList<String> printPerms(String s) { HashMap<Character, Integer> buildFreqTable(String s) { void printPerms(HashMap<Character, Integer> map, String prefix, int remaining, ArrayList<String> result) {

6.8 The Egg Drop Problem: There is a building of 100 floors. If an egg drops from the Nth floor or above, it will break. If it's dropped from any floor below, it will not break. You're given two eggs. Find N, while minimizing the number of drops for the worst case.

As a first try, suppose we drop an egg from the 10th floor, then the 20th, ... • If Egg 1 breaks on the first drop (floor 10), then we have at most 10 drops total. If Egg 1 breaks on the last drop (floor 100), then we have at most 19 drops total (floors 10,20, ...,90, 100, then 91 through 99). That's pretty good, but all we've considered is the absolute worst case.We should do some "load balancing" to make those two cases more even. Our goal is to create a system for dropping Egg 1 such that the number of drops is as consistent as possible, whether Egg 1 breaks on the first drop or the last drop. 1. A perfectly load-balanced system would be one in which Drops (Egg 1) + Drops (Egg 2) is always the same, regardless of where Egg 1 breaks. 2. For that to be the case, since each drop of Egg 1 takes one more step, Egg 2 is allowed one fewer step. 3. We must, therefore, reduce the number of steps potentially required by Egg 2 by one drop each time. For example, if Egg 1 is dropped on floor 20 and then floor 30, Egg 2 is potentially required to take 9 steps. When we drop Egg 1 again, we must reduce potential Egg 2 steps to only 8.That is, we must drop Egg 1at floor 39. 4. Therefore, Egg 1 must start at floor X, then go up by X-1 floors, then X- 2, ..., until it gets to 100. 5. Solve for X. X+(X - l)+(X - 2)+...+1=100 X(X+1/2)' =00 X:::::: 13.65 X clearly needs to be an integer. Should we round X up or down? • If we round X up to 14, then we would go up by 14, then 13, then 12, and so on. The last increment would be 4, and it would happen on floor 99. If Egg 1 broke on any of the prior floors, we know we've balanced the eggs such that the number of drops of Egg 1 and Egg 2 always sum to the same thing: 14. If Egg 1 hasn't broken by floor 99, then we just need one more drop to determine if it will break at floor 100. Either way, the number of drops is no more than 14. • If we round X down to 13, then we would go up by 13, then 12, then 11, and so on. The last increment will be 1 and it will happen at floor 91 . This is after 13 drops. Floors 92 through 100 have not been covered yet. We can't cover those floors in just one drop (which would be necessary to merely tie the round up case. Therefore, we should round X up to 14. That is, we go to floor 14, then 27, then 39, .... This takes 14 steps in the worse case.

13.1 Private Constructor: In terms of inheritance, what is the effect of keeping a constructor private?

Declaring a constructor p r i vate on class A means that you can only access the (private) constructor if you could also access A's private methods. Who, other than A, can access A's private methods and constructor? A's inner classes can. Additionally, if A is an inner class of Q, then Q's other inner classes can. This has direct implications for inheritance, since a subclass calls its parent's constructor. The class A can be inherited, but only by its own or its parent's inner classes.

13.3 Final, etc.: What is the difference between final, finally,and finalize?

Despite their similar sounding names, final, finally and finalize have very different purposes. To speak in very general terms, f i n a l is used to control whether a variable, method, or class is "change- able:'Thefinallykeywordisusedinatry/ catchblocktoensurethatasegmentofcodeisalways executed.The finalize() method is called by the garbage collector once it determines that no more references exist.

15.3 Dining Philosophers: In the famous dining philosophers problem, a bunch of philosophers are sitting around a circular table with one chopstick between each of them. A philosopher needs both chopsticks to eat, and always picks up the left chopstick before the right one. A deadlock could potentially occur if all the philosophers reached for the left chopstick at the same time. Using threads and locks, implement a simulation of the dining philosophers problem that prevents deadlocks.

First, let's implement a simple simulation of the dining philosophers problem in which we don't concern ourselves with deadlocks. We can implement this solution by having Philosopher extend Thread, and Chopstick call lock .lock() when it is picked up and lock. unlock() when it is put down. class Chopstick {

11.1 Mistake: Find the mistake(s) in the following code: unsigned int ij for (i = 100; i >= a; --i) printf("%d\n", i);

First,notethatanunsigned intis,bydefinition,alwaysgreaterthanorequaltozero.Theforloopcondi- tion will therefore always be true, and it will loop infinitely. The correct code to print all numbers from 100 to 1, is i > e. If we truly wanted to print zero, we could add an additional p r i n t f statement after the for loop.

6.3 Dominos: There is an 8x8 chessboard in which two diagonally opposite corners have been cut off. You are given 31 dominos, and a single domino can cover exactly two squares. Can you use the 31 dominos to cover the entire board? Prove your answer (by providing an example or showing why it's impossible).

For each row we place, we'll always have one domino that needs to poke into the next row. No matter how many times and ways we try to solve this issue, we won't be able to successfully lay down all the dominoes. There'sa cleaner, more solid prooffor why it won't work.The chessboard initially has 32 black and 32 white squares. By removing opposite corners (which must be the same color), we're left with 30 of one color and 32 of the other color. Let's say, for the sake of argument, that we have 30 black and 32 white squares. Each domino we set on the board will always take up one white and one black square.Therefore, 31 dominos will take up 31 white squares and 31 black squares exactly. On this board, however, we must have 30 black squares and 32 white squares. Hence, it is impossible.

6.2 Basketball: You have a basketball hoop and someone says that you can play one of two games. Game 1:You get one shot to make the hoop. Game 2: You get three shots and you have to make two of three shots. If p is the probability of making a particular shot, for which values of p should you pick one game or the other?

If P =0,0.5,or1,thenP(Game 1) =P(Game 2), so it doesn't matter which game we play.

6.7 The Apocalypse: In the new post-apocalyptic world, the world queen is desperately concerned about the birth rate. Therefore, she decrees that all families should ensure that they have one girl or else they face massive fines. If all families abide by this policy-that is, they have continue to have children until they have one girl, at which point they immediately stop-what will the gender ratio of the new generation be? (Assume that the odds of someone having a boy or a girl on any given pregnancy is equal.) Solve this out logically and then write a computer simulation of it.

If the earlier sum is 1, this would mean that the gender ratio is even.Families contribute exactly one girl and on average one boy.The birth policy is therefore ineffective. Does this make sense? At first glance, this seems wrong. The policy is designed to favor girls as it ensures that all families have a girl. On the other hand, the families that keep having children contribute (potentially) multiple boys to the population.This could offset the impact of the "one girl" policy. One way to think about this is to imagine that we put all t he gender sequence of each family into one giant string. So if family 1 has BG, family 2 has BBG, and family 3 has G, we would write BGBBGG. In fact, we don't really care about the groupings of families because we're concerned about the population as a whole. As soon as a child is born, we can just append its gender (B or G) to the string. What are the odds of the next character being a G? Well, if the odds of having a boy and girl is the same, then the odds of the next character being a G is 50%. Thereforece, roughly half the string should be Gs and half should be Bs, giving an even gender ratio. This actually makes a lot of sense. Biology hasn't been changed. Half of newborn babies are girls and half are boys. Abiding by some rule about when to stop having children doesn't change this fact. Therefore, the gender ratio is 50% girls and 50% boys.

9.4 Duplicate URLs: You have 10 billion URLs. How do you detect the duplicate documents? In this case, assume "duplicate" means that the URLs are identical.

If we stored all the data on one machine, we would do two passes of the document. The first pass would split the list of URLs into 4000 chunks of 1 GB each. An easy way to do that might be to store each URL u in a file named <x>. tx t where x = hash (u) % 4000.That is, we divide up the URLs based on their hash value (modulo the number of chunks).This way, all URLs with the same hash value would be in the same file. In the second pass, we would essentially implement the simple solution we came up with earlier: load each file into memory, create a hash table of the URLs, and look for duplicates.

13.4 Generics vs. Templates: Explain the difference between templates in C++ and generics in Java.

In Java, static variables are shared across instances ofMyClas s, regardless of the different type parameters. Java generics and C++ templates have a number of other differences. These include: c + + t e m p l a t e s c a n u s e p r i m i t i v e t y p e s , l i k e i n t oJ a v a c a n n o t a n d m u s t i n s t e a d u s e I n t e g e r . • In Java, you can restrict the template's type parameters to be of a certain type. For instance, you might use generics to implement a CardDeck and specify that the type parameter must extend from CardGame. • In C++, the type parameter can be instantiated, whereas Java does not support this. In Java, the type parameter (Le., the Foo in MyClass<Foo» cannot be used for static methods and variables, since these would be shared between MyClass<Foo> and MyClass<Bar>.ln C++, these classes are different, so the type parameter can be used for static methods and variables. In Java, all instances of MyClass, regardless of their type parameters, are the same type. The type parameters are erased at runtime. In C++, instances with different type parameters are different types. Remember: Although Java generics and C++ templates look the same in many ways, they are very different.

13.7 Lambda Expressions: There is a class Country that has methods getContinent() and getPopulation().Write a function int getPopulation(List<Country> countries, String continent) that computes the total population of a given continent, given a list of all countries and the name of a continent.

It's tempting to approach this problem by picking a subset size from e to N and then generating a random subset of that size. That creates two issues: 1. We'd have to weight those probabilities. If N > 1, there are more subsets of size N/ 2 than there are of subsets of size N(of which there is always only one). 2. It's actually more difficult to generate a subset of a restricted size (e.g., specifically 10) than it is to generate a subset of any size.

6.6 Blue-Eyed Island: A bunch of people are living on an island, when a visitor comes with a strange order: all blue-eyed people must leave the island as soon as possible. There will be a flight out at 8:00pm every evening. Each person can see everyone else's eye color, but they do not know their own (nor is anyone allowed to tell them). Additionally, they do not know how many people have blue eyes, although they do know that at least one person does. How many days will it take the blue-eyed people to leave?

Let's apply the Base Case and Build approach. Assume that there are n people on the island and c of them have blue eyes. We are explicitly told that c > 8. Case c = 1: Exactly one person has blue eyes. Assuming all the people are intelligent, the blue-eyed person should look around and realize that no one else has blue eyes. Since he knows that at least one person has blue eyes, he must conclude that it is he who has blue eyes.Therefore, he would take the flight that evening. Case c = 2: Exactly two people have blue eyes. The two blue-eyed people see each other, but are unsure whether c is , or 2. They know, from the previous case, that if c = " the blue-eyed person would leave on the first night. Therefore, if the other blue-eyed person is still there, he must deduce that c = 2, which means that he himself has blue eyes. Both men would then leave on the second night. Case c > 2: The General Case. As we increase c, we can see that this logic continues to apply. If c = 3, then those three people will imme- diately know that there are either 2 or 3 people with blue eyes. If there were two people, then those two people would have left on the second night. So, when the others are still around after that night, each person would conclude that c = 3 and that they, therefore, have blue eyes too. They would leave that night. This same pattern extends up through any value of c. Therefore, if c men have blue eyes, it will take c nights for the blue-eyed men to leave. All will leave on the same night.

2.8 Loop Detection: Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop. DEFINI TION Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list. EXAMPLE Input: A -> B -> C -> D -> E -> C[thesameCasearlier) Output: C

LinkedListNode FindBeginning(LinkedListNode head) {

2.7 Intersection: Given two (singly) linked lists, determine if the two lists intersect. Return the intersecting node. Note that the intersection is defined based on reference, not value. That is, if the kth node of the first linked list is the exact same node (by reference) as the jth node of the second linked list, then they are intersecting.

LinkedListNode FindBeginning(LinkedListNode head) { void main(String[] args) {

2.4 Partition: Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions.

LinkedListNode partition(LinkedListNode node, int x) { void main(String[] args) { Question B: LinkedListNode partition(LinkedListNode node, int x) { void main(String[] args) { Question C: LinkedListNode partition(LinkedListNode node, int x) { void main(String[] args) {

4.6 Successor: Write an algorithm to find the "next" node (i.e., in-order successor) of a given node in a binary search tree. You may assume that each node has a link to its parent.

Node inorderSucc(Node n){ TreeNode inorderSucc(TreeNode n){ TreeNode leftMostChild(TreeNode n) {

6.10 Poison: You have 1000 bottles of soda, and exactly one is poisoned. You have latest strips which can be used to detect poison. A single drop of poison will turn the test strip positive permanently. You can put any number of drops on a test strip at once and you can reuse a test strip as many times as you'd like (as long as the results are negative). However, you can only run tests once per day and it takes seven days to return a result. How would you figure out the poisoned bottle in as few days as possible? Follow up:Write code to simulate your approach.

Notice what each test strip really means. It's a binary indicator for poisoned or unpoisoned. Is it possible to map 1000 keys to 10 binary values such that each key is mapped to a unique configuration of values? Yes, of course. This is what a binary number is. We can take each bottle number and look at its binary representation. If there's a 1 in the ith digit, then we will add a drop of this bottle's contents to test strip i. Observe that 210 is 1024, so 10 test strips will be enough to handle up to 1024 bottles. We wait seven days, and then read the results. If test strip i is positive, then set bit i of the result value. Reading all the test strips will give us the ID of the poisoned bottle. int findPoisonedBottle(ArrayList<Bottle> bottles, ArrayList<TestStrip> strips) { void runTests(ArrayList<Bottle> bottles, ArrayList<TestStrip> testStrips) { ArrayList<Integer> getPositiveOnDay(ArrayList<TestStrip> testStrips, int day) { int setBits(ArrayList<Integer> positive) {

13.6 Object Reflection: Explain what object reflection is in Java and why it is useful.

Object Reflection is a feature in Java that provides a way to get reflective information about Java classes and objects, and perform operations such as: 1. Gettinginformationaboutthemethodsandfieldspresentinsidetheclassatruntime. 2, Creating a new instance of a class. 3. Getting and setting the object fields directly by getting field reference, regardless of what the access modifier is. It can help you observe or manipulate the runtime behavior of applications. 2. It can help you debug or test programs, as you have direct access to methods, constructors, and fields. 3. You can call methods by name when you don't know the method in advance. For example, we may let the user pass in a class name, parameters for the constructor, and a method name. We can then use this information to create an object and call a method. Doing these operations without reflection would require a complex series of if-statements, if it's possible at all.

9.1 Stock Data: Imagine you are building some sort of service that will be called by up to 1,000 client applications to get simple end-of-day stock price information (open, close, high, low). You may assume that you already have the data, and you can store it in any format you wish. How would you design the client-facing service that provides the information to client applications? You are responsible for the development, rollout, and ongoing monitoring and maintenance of the feed. Describe the different methods you considered and why you would recommend your approach. Your service can use any technologies you wish, and can distribute the information to the client applications in any mechanism you choose.

One option is that we could keep the data in simple text files and let clients download the data through some sort of FTP server.This would be easy to maintain in some sense, since files can be easily viewed and backed up, but it would require more complex parsing to do any sort of query. And, if additional data were added to our text file, it might break the clients' parsing mechanism.

15.1 Thread vs. Process: What's the difference between a thread and a process?

Processes and threads are related to each other but are fundamentally different. pg 179 A process can be thought of as an instance of a program in execution. A process is an independent entity to which system resources (e.g., CPU time and memory) are allocated. Each process is executed in a separate address space, and one process cannot access the variables and data structures of another process. If a process wishes to access another process'resources, inter-process communications have to be used.These include pipes, files, sockets, and other forms. A thread exists within a process and shares the process' resources (including its heap space). Multiple threads within the same process will share the same heap space.This is very different from processes, which cannot directly access the memory of another process. Each thread still has its own registers and its own stack, but other threads can read and write the heap memory. A thread is a particular execution path of a process. When one thread modifies a process resource, the change is immediately visible to sibling threads.

4.7 Build Order: You are given a list of projects and a list of dependencies (which is a list of pairs of projects, where the second project is dependent on the first project). All of a project's dependencies must be built before the project is. Find a build order that will allow the projects to be built. If there is no valid build order, return an error.

Project[] findBuildOrder(String[] projects, String[][] dependencies) { Graph buildGraph(String[] projects, String[][] dependencies) { Project[] orderProjects(ArrayList<Project> projects) { int addNonDependent(Project[] order, ArrayList<Project> projects, int offset) { public class Graph { public Project getOrCreateNode(String name) { public void addEdge(String startName, String endName) { public ArrayList<Project> getNodes() { public class Project { public Project(String n) { public void addNeighbor(Project node) { public void incrementDependencies() { public void decrementDependencies() { public String getName() { public ArrayList<Project> getChildren() { public int getNumberDependencies() { Stack<Project) findBuildOrder(String[] projects, String[][] dependencies) { Stack<Project> orderProjects(ArrayList<Project> projects) { boolean doDFS(Project project, Stack<Project> stack) { Graph buildGraph(String[] projects, String[][] dependencies) { public class Graph { public class Project { public enum State { public State getState() { public void setState(State st) { .

6.9 100 Lockers: There are 100 closed lockers in a hallway. A man begins by opening all 100 lockers. Next, he closes every second locker.Then, on his third pass, he toggles every third locker (closes it if it is open or opens it if it is closed). This process continues for 100 passes, such that on each pass i, the man toggles every i th locker. After his 100th pass in the hallway, in which he toggles only locker #100, how many lockers are open?

Question: For which rounds is a door toggled (open or closed)? A door n is toggled once for each factor of n, including itself and 1. That is, door 15 is toggled on rounds 1, 3,5, and 15. Question: When would a door be left open? A door is left open if the number of factors (which we will call x) is odd.You can think about this by pairing factors off as an open and a close. If there's one remaining, the door will be open. Question: When would x be odd? The value x is odd if n is a perfect square. Here's why: pair n's factors by their complements. For example, if n is 36, the factors are (1, 36), (2, 18), (3, 12), (4, 9), (6,6). Note that (6, 6) only contributes one factor, thus giving n an odd number of factors. Question: How many perfect squares are there? There are 10 perfect squares. You could count them (1 , 4,9, 16, 25, 36,49,64, 81, 100)' or you could simply realize that you can take the numbers 1 through 10 and square them: 1*1, 2*2, 3*3, ... , 10*10 Therefore, there are 10 lockers open at the end of this process.

8.9 Parens: Implement an algorithm to print all valid (Le., properly opened and closed) combinations of n pairs of parentheses. EXAMPLE Input: 3 Output: ((())), ( ( ) ( ) ), ( ( ) ) ( ), ( ) ( ( ) ), ( ) ( ) ( )

Set<String> generateParens(int remaining) { String insertInside(String str, int leftIndex) { void addParen(ArrayList<String> list, int leftRem, int rightRem, char[] str, int index) { ArrayList<String> generateParens(int count) {

5.2 Binary to String: Given a real number between 8 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR:'

String printBinary2(double num) {

1.2 Check Permutation: Given two strings, write a method to decide if one is a permutation of the other.

String sort(String s) { boolean permutation(String s, String t) { boolean anagram(String s, String t) { void main(String[] args) { boolean permutation(String s, String t) { void main(String[] args) {

9.2 Social Network: How would you design the data structures for a very large social network like Facebook or Linkedln? Describe how you would design an algorithm to show the shortest path between two people (e.g., Me -> Bob -> Susan -> Jason -> You).

Suppose every person has k friends, and node S and node D have a friend C in common. • Traditiona lbreadth-firstsearch from S to D:We go through roughlyk+k*knodes:each of S's k friends, and then each of their k friends. idirectional breadth-first search: We go through 2k nodes: each of S's k friends and each of D's k friends. Of course, 2k is much less than k+k*k. Generalizing this to a path of length q, we have this: BFS: O( kq ) • Bidirectional BFS: O( kq/ 2 + kQ(2), which is just O( kQ/ 2 ) If you imagine a path like A- >B- >C - >D- >E where each person has 100 friends, this is a big difference. BFS will require looking at 100 million (1004) nodes. A bidirectional BFS will require looking at only 20,000 nodes(2 x 1002). A bidirectional BFS will generally be faster than the traditional BFS. However, it requires actually having access to both the source node and the destination nodes, which is not always the case. Question: Breadth-first search usually requires "marking" a node as visited. How do you do that in this case? Usually, in BFS, we mark a node as visited by setting a v i s i t e d flag in its node class. Here, we don't want to do that. There could be multiple searches going on at the same time, so it's a bad idea to just edit our data. Instead, we could mimic the marking of nodes with a hash table to look up a node id and determine whether it's been visited. People are much more likely to be friends with people who live in the same country as they do. Rather than randomly dividing people across machines, try to divide them by country, city, state, and so on. This will reduce the number of jumps.

11.3 Chess Test: We have the following method used in a chess game: boolean canMoveTo( int x, int y). This method is part of the Piece class and returns whether or not the piece can move to position (x , y) . Explain how you would test this method.

Test with negative numbers for x and y Test with x larger than the width Test with y larger than the height • Test with a completely full board Test with an empty or nearly empty board Test with far more white pieces than black

6.4 Ants on a Triangle: There are three ants on different vertices of a triangle. What is the probability of collision (between any two or all of them) if they start walking on the sides of the triangle? Assume that each ant randomly picks a direction, with either direction being equally likely to be chosen, and that they walk at the same speed.

The ants will collide if any of them are moving towards each other. So, the only way that they won't collide is if they are al l moving in the same direction (clockwise or counterclockwise). We can compute this prob- ability and work backwards from there. Since each ant can move in two directions, and there are three ants, the probability is: probability of collision is therefore the probability of the ants not moving in the same direction:

15.2 Context Switch: How would you measure the time spent in a context switch?

This is a tricky question, but let's start with a possible solution. pg 179 A context switch is the time spent switching between two processes (Le., bringing a waiting process into execution and sending an executing process into waiting/terminated state).This happens in multitasking. The operating system must bring the state information of waiting processes into memory and save the state information of the currently running process. In order to solve this problem, we would like to record the timestamps of the last and first instruction of the swapping processes. The context switch time is the difference in the timestamps between the two processes.

9.3 Web Crawler: If you were designing a web crawler, how would you avoid getting into infinite loops?

Thisis great- but what does it mean to visit page v? Is page v defined based on its content or its URL? If it's defined based on its URL, we must recognize that URL parameters might indicate a completely different page. For example, the page www.careercup.com/page?pid=microsoft-interview- questions istotallydifferentfromthepagewww.careercup.com/page?pid=google-interview- questions. But, we can also append URL parameters arbitrarily to any URL without truly changing the page, provided it's not a parameter that the web application recognizes and handles. The page www. careercup.com?foobar=helloisthesameaswww.careercup.com. "Okay, then;' you might say, "let's define it based on its content:' That sounds good too, at first, but it also doesn't quite work. Suppose I have some randomly generated content on the careercup.com home page. Is it a different page each time you visit it? Not really. The reality is that there is probably no perfect way to define a"different"page, and this is where this problem gets tricky. One way to tackle this is to have some sort of estimation for degree of similarity. If, based on the content and the URL, a page is deemed to be sufficiently similar to other pages, we deprioritize crawling its children. For each page, we would come up with some sort of signature based on snippets of the content and the page's URL. Let's see how this would work. We have a database which stores a list of items we need to crawl. On each iteration, we select the highest priority page to crawl. We then do the following : 1. Open up the page and create a signature of the page based on specific subsections of the page and its URL. 2. Querythedatabasetoseewhetheranythingwiththissignaturehasbeencrawledrecently. 3. If something with this signature has been recently crawled, insert this page back into the database at a low priority. 4. Ifnot,crawlthepageandinsertitslinksintothedatabase. Under the above implementation, we never "complete" crawling the web, but we will avoid getting stuck in a loop of pages. If we want to allow for the possibility of "finishing" crawling the web (which would clearly happen only if the "web"were actually a smaller system, like an intranet), then we can set a minimum priority that a page must have to be crawled.

4.8 First Common Ancestor: Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE:This is not necessarily a binary search tree.

TreeNode commonAncestor(TreeNode p, TreeNode q) { TreeNode goUpBy(TreeNode node, int delta) { int depth(TreeNode node) { TreeNode commonAncestor(TreeNode root, TreeNode p, TreeNode q) { boolean covers(TreeNode root, TreeNode p) { TreeNode getSibling(TreeNode node) { TreeNode commonAncestor(TreeNode root, TreeNode p, TreeNode q ){ TreeNode ancestorHelper(TreeNode root, TreeNode p, TreeNode q) { boolean covers(TreeNode root, TreeNode p) { TreeNode commonAncestor(TreeNode root, TreeNode p, TreeNode q) { class Result { public Result(TreeNode n, boolean isAnc) { TreeNode commonAncestor(TreeNode r o o t , TreeNode p, TreeNode q) { Result commonAncHelper(TreeNode root, TreeNode p, TreeNode q) {

4.2 Minimal Tree: Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height.

TreeNode createMinimalBST(int array[]) { TreeNode createMinimalBST(int arr[], int start, int end) {

9.6 Sales Rank: A large eCommerce company wishes to list the best-selling products, overall and by category. For example, one product might be the #1 056th best-selling product overall but the #13th best-selling product under "Sports Equipment" and the #24th best-selling product under "Safety." Describe how you would design this system.

We could treat the general category as just another directory, and write every purchase to that directory. That would mean a lot of files in this directory. Or, since we'll already have the products sorted by sales volume order for each category, we can also do an N-way merge to get the overall rank. Alternatively, we can take advantage of the fact that the data doesn't need (as we assumed earlier) to be 100% up-to-date.We just need the most popular items to be up-to-date. We can merge the most popular items from each category in a pairwise fashion. So, two categories get paired together and we merge the most popular items (the first 100 or so). After we have 100 items in this sorted order, we stop merging this pair and move onto the next pair. To get the ranking for all products, we can be much lazier and only run this work once a day. One ofthe advantages ofthis is that it scales nicely.We can easily divide up the files across multiple servers, as they aren't dependent on each other.

10.6 Sort Big File: Imagine you have a 20 GB file with one string per line. Explain how you would sort the file.

When an interviewer gives a size limit of 20 gigabytes, it should tell you something. In this case, it suggests that they don't want you to bring all the data into memory. So what do we do? We only bring part of the data into memory. We'll divide the file into chunks, which are x megabytes each, where x is the amount of memory we have available. Each chunk is sorted separately and then saved back to the file system. Once all the chunks are sorted, we merge the chunks, one by one. At the end, we have a fully sorted file. This algorithm is known as external sort.

11.6 Test an ATM: How would you test an ATM in a distributed banking system?

Who is going to use the ATM? Answers might be "anyone;' or it might be "blind people;' or any number of other answers. What are they going to use it for? Answers might be "withdrawing money," "transferring money;' "checking their balance;' or many other answers. • What tools do we have to test? Do we have access to the code, or just to the ATM?

13.2 Return from Finally: In Java, does the finally block get executed if we insert a return statement inside the try block of a try-catch-finally?

Yes, it will get executed.The finally block gets executed when the try block exits. Even when we attempt to exit within the try block (via a return statement,a continue statement, a break statement or any exception), the fin a lly block will still be executed. Note that there are some cases in which the fin a lly block will not get executed, such as the following: • If the virtual machine exits during try / catch block execution. • Ifthethreadwhichisexecutingduringthetry/catchblockgetskilled.

9.8 Pastebin: Design a system like Pastebin, where a user can enter a piece of text and get a randomly generated URL for public access.

You can discuss this with your interviewer, but it probably makes sense to store the raw data. We never know what features we'll add to the analytics down the road.The raw data allows us flexibility. This does not mean that the raw data needs to be easily searchable or even accessible. We can just store a log of each visit in a file, and back this up to other servers.

3.6 Animal Shelter: An animal shelter, which holds only dogs and cats, operates on a strictly "first in, first out"basis. People must adopt either the "oldest"(based on arrival time) of all animals at the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot select which specific animal they would like. Create the data structures to maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog, and dequeueCat. You may use the built-in LinkedList data structure.

abstract class Animal { public Animal(String n) { public void setOrder(int ord) { public int getOrder() { public boolean isOlderThan(Animal a) { class AnimalQueue { public void enqueue(Animal a) { public Animal dequeueAny() { public Dog dequeueDogs() { public Cat dequeueCats() { public class Dog extends Animal { public class Cat extends Animal {

4.10 Check Subtree: Tl and T2 are two very large binary trees, with Tl much bigger than T2. Create an algorithm to determine if T2 is a subtree of Tl . A tree T2 is a subtree of T1 if there exists a node n in Tl such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.

boolean containsTree(TreeNode t1, TreeNode t2) { void getOrderString(TreeNode node, StringBuilder sb) { boolean containsTree(TreeNode t1, TreeNode t2) { boolean subTree(TreeNode r1, TreeNode r2) { boolean matchTree(TreeNode r1, TreeNode r2) {

2.3 Delete Middle Node: Implement an algorithm to delete a node in the middle (Le., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node. EXAMPLE Input: the node c from the linked list a- >b- >c - >d - >e- >f Result: nothing is returned, but the new linked list looks like a->b->d->e->f

boolean deleteNode(LinkedListNode n) { void main(String[] args) {

10.9 Sorted Matrix Search: Given an M x N matrix in which each row and each column is sorted in ascending order, write a method to find an element.

boolean findElement(int[][] matrix, int elem) { Coordinate findElement(int[][] matrix, Coordinate orlgln, Coordinate dest, int x){ Coordinate partitionAndSearch(int[][] matrix, Coordinate origin, Coordinate dest, Coordinate pivot, int x) { Coordinate findElement(int[)[) matrix, int x) { public class Coordinate implements Cloneable { public boolean inbounds(int[)[) matrix) { public boolean isBefore(Coordinate p) { public Object clone() { public void setToAverage(Coordinate min, Coordinate max) {

2.6 Palindrome: Implement a function to check if a linked list is a palindrome.

boolean isPalindrome(LinkedListNode head) { LinkedListNode reverseAndClone(LinkedListNode node){ boolean isEqual(LinkedListNode one, LinkedListNode two){

1.4 Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome.

boolean isPermutationOfPalindrome(String phrase) {

1.9 String Rotation: Assume you have a method i 5 S u b s t r i n g which checks if one word is a substring of another. Given two strings, 51 and 52, write code to check if 52 is a rotation of 51 using only one call to isSubstring (e.g., "waterbottle" is a rotation of "erbottlewat").

boolean isSubstring(String big, String small) { boolean isRotation(String s1, String s2) { void main(String[] args) {

1.1 Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?

boolean isUniqueChars(String str) boolean isUniqueChars2(String str) { void main(String[] args) {

10.2 Group Anagrams: Write a method to sort an array of strings so that all the anagrams are next to each other.

class AnagramComparator implements Comparator<String> { public String sortChars(String s) { public int compare(String sl, String s2) {

3.1 Three in One: Describe how you could use a single array to implement three stacks.

class FixedMultiStack { public FixedMultiStack(int stackSize) { void push(int stackNum, int value) throws FullStackException { public int pop(int stackNum) { public int peek(int stackNum) { public boolean isEmpty(int stackNum) { public boolean isFull(int stackNum) { private int indexOfTop(int stackNum) { public class MultiStack { private class StackInfo { public StackInfo(int start, int capacity) { public boolean isWithinStackCapacity(int index) { public int lastCapacitylndex() { public int lastElementIndex() { public MultiStack(int numberOfStacks, int defaultSize) { public void push(int stackNum, int value) throws FullStackException { public int pop(int stackNum) throws Exception { public int peek(int stackNum) { private void shift(int stackNum) { private void expand(int stackNum) { public int numberOfElements() { public boolean alIStacksAreFull() { private int adjustlndex(int index) { private int nextlndex(int index) { private int previouslndex(int index) {

2.5 Sum Lists: You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

class PartialSum { Question A: LinkedListNode addLists( LinkedListNode l1, LinkedListNode l2, int carry) { int linkedListToInt(LinkedListNode node) { void main(String[] args) { Question B: int length(LinkedListNode l) { PartialSum addListsHelper(LinkedListNode l1, LinkedListNode l2) { LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2) { LinkedListNode padList(LinkedListNode l, int padding) { LinkedListNode insertBefore(LinkedListNode list, int data) { int linkedListToInt(LinkedListNode node) { void main(String[] args) {

4.11 Random Node: You are implementing a binary search tree class from scratch, which, in addition to insert, find, and delete, has a method getRandomNode() which returns a random node from the tree. All nodes should be equally likely to be chosen. Design and implement an algorithm f o r g e t Ra n d o m N o d e , a n d e x p l a i n h o w y o u w o u l d i m p l e m e n t t h e r e s t o f t h e m e t h o d s .

class TreeNode { public TreeNode(int d) { public TreeNode getRandomNode() { public void insertlnOrder(int d) { public int size() { public int data() { public TreeNode find(int d) { class Tree { public int size() { public TreeNode getRandomNode() { public void insertlnOrder(int value) { class TreeNode { public TreeNode getlthNode(int i) { public void insertlnOrder(int d) { public int size() { public TreeNode find(int d) {

8.14 Boolean Evaluation: Given a boolean expression consisting of the symbols e (false), 1 (true), & (AND), I (OR), and A(XOR), and a desired boolean result value result, implement a function to count the number of ways of parenthesizing the expression such that it evaluates to result. The expression should be fully parenthesized (e.g.,(0)^(1)) but not extraneously (e.g.,(((0)) ^ (1))) EXAMPLE countEval("1^ 0|0|1", false) -> 2 countEval("0&0&0&1^1 | 0", true) - > 10

left = "e"e" right ="e"111" countEval(left & right, true) = countEval(left, true) * countEval(right, true) int countEval(String s, boolean result) { boolean stringToBool(String c) { int countEval(String s, boolean result, HashMap<String, Integer> memo) {

8.6 Towers of Hanoi: In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower.The puzzle starts with disks sorted in ascending order of size from top to bottom (Le., each disk sits on top of an even larger one). You have the following constraints: (1) Only one disk can be moved at a time. (2) A disk is slid off the top of one tower onto another tower. (3) A disk cannot be placed on top of a smaller disk. Write a program to move the disks from the first tower to the last using Stacks.

moveDisks(int n, Tower origin, Tower destination, Tower buffer) { void main(String[] args) { class Tower { public Tower(int i) { public int index() { public void add(int d) { public void moveTopTo(Tower t) { public void moveDisks(int n, Tower destination, Tower buffer) {

7.1 Deck of Cards: Design the data structures for a generic deck of cards. Explain how you would subclass the data structures to implement blackjack.

public T deaICard() { public abstract class Card { public Card(int c, Suit s) { public Suit suit() { public boolean isAvailable() { public void markUnavailable() { public void markAvailable() { public class Hand <T extends Card> { public int score() { public void addCard(T card) { public class BlackJackHand extends Hand<BlackJackCard> { public int score() { private ArrayList <Integer> possibleScores(){ public boolean busted(){ public boolean is21() public boolean isBlackJack(){ public class BlackJackCard extends Card { public int value(){ public int minValue(){ public int maxValue(){ public boolean isAce(){ public boolean isFaceCard(){

7.11 File System: Explain the data structures and algorithms that you would use to design an in-memory file system. Illustrate with an example in code where possible.

public abstract class Entry { public Entry(String n, Directory p) { public boolean delete() { public String getFullPath() { public long getCreationTime() { public long getLastUpdatedTime() { public long getLastAccessedTime() { public class File extends Entry { public File(String n, Directory p, int sz) { public int size() { public String getContents() { public void setContents(String c) { public class Directory extends Entry{ public Directory(String n, Directory p){ public int size(){ public int numberOfFiles(){ public boolean deleteEntry(Entry entry){ public void addEntry(Entry entry){ protected ArrayList<Entry> getContents() {

7.2 Call Center: Imagine you have a call center with three levels of employees: respondent, manager, and director. An incoming telephone call must be first allocated to a respondent who is free. If the respondent can't handle the call, he or she must escalate the call to a manager. If the manager is not free or not able to handle it, then the call should be escalated to a director. Design the classes and data structures for this problem. Implement a method dispatchCall() which assigns a call to the first available employee.

public class CallHandler { public CaIIHandler() { public Employee getHandlerForCall(Call call) { public void dispatchCall(Caller caller) { public void dispatchCall(Call call) { public boolean assignCall(Employee emp) { public class Call { public Call(Caller c) { public void setHandler(Employee e) { public void reply(String message) { public Rank getRank() { public void setRank(Rank r) { public Rank incrementRank() { public void disconnect () { abstract class Employee { public Employee(CallHandler handler) { public void receiveCall(Call call) { public void caIICompleted() { public void escalateAndReassign() { public boolean assignNewCall() { public boolean isFree() { public Rank getRank() { class Director extends Employee { public Director() { class Manager extends Employee { public Manager() { class Respondent extends Employee { public Respondent() {

7.10 Minesweeper: Design and implement a text-based Minesweeper game. Minesweeper is the classic single-player computer game where an NxN grid has B mines (or bombs) hidden across the grid. The remaining cells are either blank or have a number behind them. The numbers reflect the number of bombs in the surrounding eight cells.The user then uncovers a cell. If it is a bomb, the player loses. If it is a number, the number is exposed. If it is a blank cell, this cell and all adjacent blank cells (up to and including the surrounding numeric cells) are exposed. The player wins when all non-bomb cells are exposed. The player can also flag certain places as potential bombs. This doesn't affect game play, other than to block the user from accidentally clicking a cell that is thought to have a bomb. (Tip for the reader: if you're not familiar with this game, please playa few rounds online first.)

public class Cell { public Cell(int r, int c) { public boolean flip() { public boolean toggleGuess() { public class Board{ public Board(int r, int c, int b) { private void initializeBoard(){ private boolean flipCell(Cell cell){ public void expandBlank(Cell cell){ public UserPlayResult playFlip(UserPlay play){ public int getNumRemaining() { public class UserPlay{ public class UserPlayResult{ public class Game{ public enum GameState{ public Game(int r, int c, int b) { public boolean initialize() { public boolean start() { private boolean playGame() { void shuffleBoard() { void setNumberedCells() { void expandBlank(Cell cell) {

7.9 Circular Array: Implement a C i r c u l a r A r r a y class that supports an array-like data structure which can be efficiently rotated. If possible, the class should use a generic type (also called a template), and should support iteration via the standard for (Obj 0 : circularArray) notation.

public class CircularArray<T> { public CircularArray(int size) { private int convert(int index) { public void rotate(int shiftRight) { public T get(int i) { public void set(int i, T item) {

7.12 Hash Table: Design and implement a hash table which uses chaining (linked lists) to handle collisions.

public class Hasher<K, V> { private static class LinkedListNode<K, V> { public LinkedListNode(K k, V v) { public Hasher(int capacity) { public void put(K key, V value) { public void remove(K key) { public V get(K key) { private LinkedListNode<K, V> getNodeForKey(K key) { public int getlndexForKey(K key) {

7.3 Jukebox: Design a musical jukebox using object-oriented principles.

public class Jukebox { public Jukebox(CDPlayer cdPlayer, User user, Set<CD> cdCollection, SongSelector ts){ public Song getCurrentSong() { public void setUser(User u) { public class CDPlayer { public CDPlayer(CD c, Playlist p){ public CDPlayer(Playlist p) { public CDPlayer(CD c) { public void playSong(Song s) { public Playlist getPlaylist() { public void setPlaylist(Playlist p) { public CD getCD() { public void setCD(CD c) { public class Playlist { public Playlist(Song song, Queue<Song> queue) { public Song getNextSToPlay() { public void queueUpSong(Song s) { public class CD { public class Song { public class User { public String getName() { public void setName(String name) { public long getID() { public void setID(long iD) { public User(String name, long iD) { public User getuser() { public static User addUser(String name, long iD) {

3.4 Queue via Stacks: Implement a MyQueue class which implements a queue using two stacks.

public class MyQueue<T> { public MyQueue() { public int size() { public void add(T value) { private void shiftStacks() { public T peek() { public T remove() {

7.5 Online Book Reader: Design the data structures for an online book reader system.

public class OnlineReaderSystem { public OnlineReaderSystem() { public Library getLibrary() { public UserManager getUserManager() { public Display getDisplay() { public Book getActiveBook() { public void setActiveBook(Book book) { public User getActiveUser() { public void setActiveUser(User user) { public class Library { public Book addBook(int id, String details) { public boolean remove(Book b) { public boolean remove(int id) { public Book find(int id) { public class UserManager { public User addUser(int id, String details, int accountType) { public User find(int id) { public boolean remove(User u) { public boolean remove(int id) { public class Display { public void displayUser(User user) { public void displayBook(Book book) { public void turnPageForward() { public void turnPageBackward() { public void refreshUsername() { public void refreshTitle() { public void refreshDetails() { public void refreshPage( ) { public class Book { public Book(int id, String det) { public int getID() { public void setID(int id) { public String getDetails() { public void setDetails(String d) { public class User { public void renewMembership() { public User(int id, String details, int accountType) { public int getID() { public void setID(int id) { public String getDetails() { public void setDetails(String details) { public int getAccountType() { public void setAccountType(int t) {

3.3 Stack of Plates: Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of several stacks and should create a new stack once the previous one exceeds capacity. SetOfStacks. push () and SetOfStacks. pop() should behave identically to a single stack (that is, pop ( ) should return the same values as it would if there were just a single stack). FOLLOW UP Implement a function popAt (int index) which performs a pop operation on a specific sub- stack.

public class SetOfStacks { public Stack getLastStack() { public void push(int v) { public int pope) { public boolean isEmpty() { public int popAt(int index) { public int leftShift(int index, boolean removeTop) { public class Stack { public Stack(int capacity) { public boolean isFull() { public void join(Node above, Node below) { public boolean push(int v) { public int pop() { public boolean isEmpty(){ public int removeBottom() {

3.2 Stack Min: How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time.

public class StackWithMin extends Stack<NodeWithMin> { public void push(int value) { public int min() { class NodeWithMin { public class StackWithMin2 extends Stack<Integer> { public void push(int value){ public Integer pop() { public int min() {

7.8 Othello: Othello is played as follows: Each Othello piece is white on one side and black on the other. When a piece is surrounded by its opponents on both the left and right sides, or both the top and bottom, it is said to be captured and its color isflipped.On your turn, you must capture at least one of your opponent's pieces. The game ends when either user has no more valid moves. The win is assigned to the person with the most pieces. Implement the object-oriented design for Othello.

public class User { public User(int id, String accountName, String fullName) { public boolean sendMessageToUser(User to, String content){ public boolean sendMessageToGroupChat(int id, String cnt){ public void setStatus(UserStatus status) { public UserStatus getStatus() { public boolean addContact(User user) { public void receivedAddRequest(AddRequest req) { public void sentAddRequest(AddRequest req) { public void removeAddRequest(AddRequest req) { public void requestAddUser(String accountName) { public void addConversation(PrivateChat conversation) { public void addConversation(GroupChat conversation) { public int getld() { public String getAccountName() { public String getFullName() { public abstract class Conversation { public ArrayList<Message> getMessages() { public boolean addMessage(Message m) { public int getld() { public class GroupChat extends Conversation { public void removeParticipant(User user) { public void addParticipant(User user) { public class PrivateChat extends Conversation { public PrivateChat(User userl, User user2) { public User getOtherParticipant(User primary) { public class Message { public Message(String content, Date date) { public String getContent() { public Date getDate() { public class AddRequest { public AddRequest(User from, User to, Date date) { public RequestStatus getStatus() { public User getFromUser() { public User getToUser() { public Date getDate() { public class UserStatus { public UserStatus(UserStatusType type, String message) { public UserStatusType getStatusType() { public String getMessage() { public enum UserStatusType { public enum RequestStatus { The following questions may be interesting to discuss with your interviewer further. 01: How do we know if someone is offline-I mean, really, really know? While we would like users to tell us when they sign off, we can't know for sure. A user's connection might have died, for example. To make sure that we know when a user has signed off, we might try regularly pinging the client to make sure it's still there. 02: How do we deal with conflicting information? We have some information stored in the computer's memory and some in the database. What happens if they get out of sync? Which one is "right"? Q3: How do we make our server scale? While we designed out chat server without worrying- too much- about scalability, in real life this would be a concern. We'd need to split our data across many servers, which would increase our concern about out-of-sync data. Q4: How we do prevent denial o f service attacks ? Clients can push data to us-what if they try to DOS (denial of service) us? How do we prevent that?

7.7 Chat Server: Explain how you would design a chat server. In particular, provide details about the various backend components, classes, and methods. What would be the hardest problems to solve?

public class UserManager { public static UserManager getlnstance() { public void addUser(User fromUse r , String toAccountName){ public void approveAddRequest(AddRequest req) { public void rejectAddRequest(AddRequest req) { public void userSignedOn(String accountName) { public void userSignedOff(String accountName) {

7.6 Jigsaw: Implement an NxN jigsaw puzzle. Design the data structures and explain an algorithm to solve the puzzle. You can assume that you have a fitsWith method which, when passed two puzzle edges, returns true if the two edges belong together.

public enum Orientation { public Orientation getOpposite() { public enum Shape { public Shape getOpposite() { public class Puzzle { public Puzzle(int size, LinkedList<Piece> pieces) { private void setEdgelnSolution(LinkedList<Piece> pieces, Edge edge, int row, int column, Orientation orientation) { public boolean solve() { public class Piece { public Piece(Edge[] edgeList) { public void rotateEdgesBy(int numberRotations ) { public boolean isCorner() { public boolean isBorder() { public class Edge { public Edge(Shape shape) { public boolean fitsWith(Edge edge) { boolean fitNextEdge(LinkedList<Piece> piecesToSearch, int row, int column) { boolean solve() {

7.4 Parking Lot: Design a parking lot using object-oriented principles.

public enum VehicleSize { public abstract class Vehicle { public int getSpotsNeeded() { public VehicleSize getSize() { public void parkInSpot(ParkingSpot s) { public void clearSpots() { public class Bus extends Vehicle { public Bus() { public boolean canFitInSpot(ParkingSpot spot) { public class Car extends Vehicle { public Car() { public boolean canFitInSpot(ParkingSpot spot){ public class Motorcycle extends Vehicle { public Motorcycle() { public boolean canFitInSpot(ParkingSpot spot){ public class ParkingLot { public ParkingLot () { public boolean parkVehicle(Vehicle vehicle) { public class Level { public Level(int fIr, int numberSpots) { public int availableSpots() { public boolean parkVehicle(Vehicle vehicle) { private boolean parkStartingAtSpot(int num, Vehicle v) { private int findAvailableSpots(Vehicle vehicle) { public void spotFreed() { public class ParkingSpot { public ParkingSpot(Level lvI, int r, int n, VehicleSize s) { public boolean isAvailable() { public boolean canFitVehicle(Vehicle vehicle) { public boolean park(Vehicle v) { public int getRow() { public int getSpotNumber() { public void removeVehicle() {

10.8 Find Duplicates:You have an array with all the numbers from 1 to N,where N is at most 32,000. The array may have duplicate entries and you do not know what N is. With only 4 kilobytes of memory available, how would you print all duplicate elements in the array?

void checkDuplicates(int[] array) { class BitSet { public BitSet(int size){ boolean get(int pos) { void set(int pos) {

4.5 Validate 8ST: Implement a function to check ifa binary tree is a binary search tree.

void copyBST(TreeNode root, int[] array) { boolean checkBST(TreeNode root) { boolean checkBST(TreeNode n) {

4.3 List of Depths: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists).

void createLevelLinkedList(TreeNode root, ArrayList<LinkedList<TreeNode» lists, int level) { ArrayList<LinkedList<TreeNode» createLevelLinkedList(TreeNode root) { ArrayList<LinkedList<TreeNode» createLevelLinkedList(TreeNode root) {

2.1 Remove Dups: Write code to remove duplicates from an unsorted linked list. FOLLOW UP How would you solve this problem if a temporary buffer is not allowed?

void deleteDupsA(LinkedListNode n) { void deleteDupsC(LinkedListNode head) { void deleteDupsB(LinkedListNode head) { void main(String[] args) {

5.8 Draw Line: A monochrome screen is stored as a single array of bytes, allowing eight consecutive pixels to be stored in one byte.The screen has width w, where wis divisible by 8 (that is, no byte will be split across rows).The height of the screen, of course, can be derived from the length of the array and the width. Implement a function that draws a horizontal line from (xl, y) to (x2, y). The method signature should look something like: drawLine(byte[] screen, int width, int Xl, int x2, int y)

void drawLine(byte[] screen, int width, int xl, int x2, int y) {

10.7 Missing Int: Given an input file with four billion non-negative integers, provide an algorithm to generate an integer that is not contained in the file. Assume you have 1 GB of memory available for this task.

void findOpenNurnber() throws FileNotFoundException { void findOpenNurnber() throws FileNotFoundException { int[] getCountperBlock(String filename, int rangeSize) throws FileNotFoundException { byte[] getBitVectorForRange(String filename, int blockIndex, int rangeSize) throws FileNotFoundException { int findBlockWithMissing(int[] blocks, int rangeSize) { byte[] getBitVectorForRange(String filename, int blockIndex, int rangeSize) throws FileNotFoundException { int findZero(byte b) { int findZero(byte[] bitVector) {

10.1 Sorted Merge: You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge Bin to A in sorted order.

void merge(int[] a, int[] b, int lastA, int lastB) {

1.8 Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.

void nullifyRow(int[][] matrix, int row) { void nullifyColumn(int[][] matrix, int col) { void setZeros2(int[][] matrix) { void setZeros(int[][] matrix) { boolean matricesAreEqual(int[][] m1, int[][] m2) { int[][] cloneMatrix(int[][] matrix) { void main(String[] args) {

8.12 Eight Queens: Write an algorithm to print all ways of arranging eight queens on an 8x8 chess board so that none of them share the same row, column, or diagonal. In this case, "diagonal" means all diagonals, not just the two that bisect the board.

void placeQueens(int row, Integer[] columns, ArrayList<Integer[] > results) { boolean checkValid(Integer[] columns, int rowl, int column1) {

1.5 One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away.

void replaceSpaces(char[] str, int length) { void main(String[] args) {

1.3 URLify: Write a method to replace all spaces in a string with '%2e: You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)

void replaceSpaces(char[] str, int trueLength) { boolean checkMaxOne(int[] table) { int getCharNumber(Character c) { int[] buildCharFrequencyTable(String phrase) { boolean isPermutationOfPalindrome(String phrase) { boolean isPermutationOfPalindrome(String phrase) { int createBitVector(String phrase) { int toggle(int bitVector, int index) { boolean checkExactlyOneBitSet(int bitVector) {

1.7 Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

void rotate(int[][] matrix, int n) { void main(String[] args) {

3.5 Sort Stack: Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array).The stack supports the following operations: push, pop, peek, and isEmpty.

void sort(Stack<Integer> s) {

6.1 The Heavy Pill: You have 20 bottles of pills. 19 bottles have 1.0 gram pills, but one has pills of weight 1.1 grams. Given a scale that provides an exact measurement, how would you find the heavy bottle? You can only use the scale once.

weight - 210 grams 0.1 grams So, if the set of pills weighed 211.3 grams, then Bottle #13 would have the heavy pills.

11.4 No Test Tools: How would you load test a webpage without using any test tools?

• Response time • Throughput • Resource utilization • Maximum load that the system can bear.


Ensembles d'études connexes

Chapter 12 Disordered Eating and Exercise Patterns in Athletes

View Set

NURS 3 - Mod 17 Musculoskeletal (Med Surg) EAQ's

View Set

Monopolist Competition, Oligopoly and Externalities (FINAL)

View Set

BA 418: Management Policies, Unit 2 Quizzes

View Set