You are on page 1of 9

Chapter

22 Hints
When I interview people, and they give me an immediate answer, theyre often not thinking. So Im silent. I wait. Because they think they have to keep answering. And its the second train of thought thats the better answer. R. Leach

Use a hint after you have made a serious attempt at the problem. Ideally, the hint should give you the ash of insight needed to complete your solution. Usually, you will receive hints only after you have shown an understanding of the problem, and have made serious attempts to solve it. See Chapter 2 for strategies on conducting yourself at the interview.
5.1: Use a lookup table, but dont use 264 entries! 5.2: When is the swap necessary? 5.3: Use a lookup table. 5.4: Start with the least signicant bit. 5.5: There are 2|S| subsets for a given set S. There are 2k k-bit words. 5.6: Build the result one digit at a time. 5.7: What base can you easily convert to and from? 5.8: There are 26 characters in [A, Z], and each can be mapped to an integer. 5.9: Follow the specications. 5.10: Use case analysis: both even; both odd; one even and one odd. 5.11: Exclude the multiples of primes. 5.12: Think of the x and y dimensions independently. 5.13: Add using bitwise operations; multiply using shift-and-add. 5.14: Relate x/ y to (x y)/ y. 6.1: Think about the partition step in quicksort. 6.2: First use another array to track the initialization status of each entry of A. Improve on this solution if you know the number of writes to uninitialized entries. 6.3: Identifying the minimum and maximum heights is not enough since the minimum height may appear after the maximum height. Focus on valid height dierences. 6.4: What do you need to know about A[0 : i 1] when processing A[i]? 6.5: Try to nd a subarray, rather than an arbitrary subset. 6.7: Map elements to representative elements. 6.6: If A[i] A[i + 1], instead of checking A[i + 1] A[i + 2], go further out in the array.

172

Hints for Problems 6.8: The disjoint-set data structure support fast union and membership checking. 6.9: Use arrays to simulate the grade school multiplication algorithm.

173

6.10: Any permutation can be viewed as a set of of cyclic permutations. For an element in a cycle, how would you identify if it has been permuted? 6.11: Represent the permutation as a set of cycles. 6.12: Study small examples. 6.13: Use small examples to form a hypothesis relating n, i, and the number of cycles. 6.14: Directly test the constraints. Use an array to encode sets. 6.15: Use case analysis and divide and conquer. 6.16: Solve this conceptually, then think about implementation optimizations. 6.17: Use divide and conquer. 6.18: This is similar to converting between binary and string representations. 6.19: Its dicult to solve this with one pass. 6.20: Form a signature from a string. 6.21: Consider performing multiples passes on s. 6.22: Use recursion. 6.23: The input denition is recursive. 7.1: Two sorted arrays can be merged using two indices. For lists, take care when one pointer variable reaches the end. 7.2: Consider using two pointers, one fast and one slow. 7.3: Use two pointerswhen one reaches the end, the other should be at the middle. 7.4: Solve the simple cases rst. 7.5: Use case analysis. What if both lists have cycles? What if they end in a common cycle? What if one list has cycle and the other does not? 7.6: Use temporary additional storage. 7.7: Instead of deleting v can you delete vs successor and still achieve the desired conguration? 7.8: If you know the length of L, can you nd the k-th last node using two pointers? 7.9: Use a pair of pointers. 7.10: Its easy if you can traverse L forwards and backwards simultaneously. 7.11: Consider traversing L in reverse order. 7.12: Copy the jump eld and then copy the next eld. 8.1: Use additional storage to track the maximum value. 8.2: Process incrementally, keeping subexpression values in a stack. How should operators be handled? 8.3: In a recursive program for printing a BST in sorted order the function call stack implicitly hold valuessimulate it. 8.4: Recursion makes the problem trivial. Mimic the recursion with a stack. 8.5: If you know how to transfer the top n 1 rings, how does that help move the n-th ring? 8.6: When does a building not have a sunset view? 8.7: Simulate insertion sort. 8.8: Trace the cases. How should . and .. be handled? Watch for invalid paths. 8.9: First think about solving this problem with a pair of queues. ElementsOfProgrammingInterviews.com

174

Hints for Problems

8.10: Track the head and tail. How can you dierentiate a full queue from an empty one? 8.11: Think about the base-10 representation of a number. 8.12: Read the requirement on time complexity very carefully. 8.13: When can an element never be returned by max, regardless of future updates? 8.14: You need to be able to identify the maximum element in a queue quickly. 9.1: Think of a classic binary tree algorithm that runs in O(h) additional space. 9.2: Use a global variable to record an unbalanced node. 9.3: The denition of symmetry is recursive. 9.4: Count. 9.5: How can you tell whether a node is a left child or right child of its parent? 9.6: Study ns right subtree. What if n does not have a right subtree? 9.7: Use the decrease and conquer principle. 9.8: Focus on the root. 9.9: Its dicult to solve this problem traversing the preorder visit sequence from left-to-right. 9.10: Build the list incrementallyits easy if the partial list is a global. 9.11: Handle the roots left child and right child in mirror fashion. 9.12: When is the root the LCA? 9.13: The problem is easy if both nodes are the same distance from the root. 9.14: Focus on the extreme case described in the problem introduction. 9.15: How would you represent a set of strings as a rooted tree? 10.1: Which portion of each le is signicant as the algorithm executes? 10.2: Can you cast this in terms of combining k sorted arrays? 10.3: Store an additional value with each element that is inserted. 10.4: Suppose you know the k closest stars in the rst n stars. If the n + 1-th star is to be added to the set of k closest stars, which element in that set should be evicted? 10.5: Which subset of k elements should you track as you read elements? When is should an element be added to this subset, and which tracked element should be evicted? 10.6: How many numbers must you read after reading the i-th number xi to be sure you can place xi in the correct location? 10.7: Would it help to nd the k largest items that are less than the median? 10.8: Can you avoid tracking all elements? 10.9: Systematically enumerate points. 10.10: Visit heap nodes in best-rst order, and count. 11.1: Dont stop after you reach the rst k. Think about the case where every entry equals k. 11.2: Look for the last occurrence of k. 11.3: Reduce this problem to ordinary binary search. 11.4: This problem easy to solve with O(n) additional spacewhy? To solve it with O(1) additional space, rst assume all elements are positive. 11.5: Use the decrease and conquer principle. 11.6: Can decrease and conquer be used to nd the end of the array? P 1 11.7: How does n i=0 min(A[i], ) vary with ? ElementsOfProgrammingInterviews.com

Hints for Problems

175

11.8: The rst k elements of A together with the rst k elements of B are initial candidates. Iteratively eliminates a constant fraction of the candidates. 11.9: Iteratively compute a sequence of intervals, each contained in the previous interval, that contain the result. 11.10: Can you eliminate a row or a column per comparison? 11.11: When is someone not be the second best player? 11.12: Use the fact that a < b and b < c implies a < c to reduce the number of compares used by the brute force approach. 11.13: Use decrease and conquer in conjunction with randomization. 11.14: Track the k largest elements, but dont update the collection immediately after each new element is read. 11.15: Can you be sure there is an address which is not in the le? 11.16: Consider performing multiple passes through A. 11.17: Count the number of 1s at each index. 11.18: Use the close property to skip indices. 11.19: Take advantage of the existence of a majority element to perform elimination. 12.1: Make a list of desirable features. 12.2: XOR is associative, commutative, and fast to compute. Additionally, a a = 0. 12.3: Each entry in the array is a candidate. 12.4: Each time a node with specied key, left child, and right child is to be allocated, rst search for such a node in an appropriate data structure. 12.5: Map sets of attributes to strings. 12.6: Compute hashes for subsets of the attribute set. 12.7: Map strings to strings so that strings which are anagrams map to the same string. 12.8: Find a simple characterization of strings that can be permuted to form a palindrome. 12.9: Count. 12.10: A line can be uniquely represented by two numbers. 12.11: Maintain a list of k candidates. 12.12: Devise a fast way to test if a word is denitely not in E. 12.13: Design a hash function which can incrementally hash S[i : i + k 1] for i = 0, 1, 2, . . .. 12.14: What is the maximum number of minimal subarrays of A that can cover Q? 12.15: For each j compute the maximum i such that A[i : j] sequentially covers Q. 12.16: Amortize the cost of deletion. Alternately, use an auxiliary data structure. 13.1: Think about corner-case inputs. 13.2: Add a degree of indirection. 13.3: Make each swap count. 13.4: Partition the array into subarrays which hold objects with equal keys. 13.5: Solve the problem if n and m dier by orders of magnitude. What if n m? 13.6: First try some concrete inputs, then make a general conclusion. 13.7: Exploit the fact that the keys are drawn from a small set. 13.8: Bring equal items close together. 13.9: What additional task should be assigned to the worker who is assigned the longest task? ElementsOfProgrammingInterviews.com

176
13.10: Focus on endpoints. 13.11: Do a case analysis. 13.12: Think about extremal points.

Hints for Problems

13.13: When is there a natural starting point for constructing the desired set? 13.14: How would you check if A[i] is part of a triple that 3-creates t? 13.15: Reduce the problem from an array of size |A| to an array of size |A| 1. 14.1: Is it correct to check for each node that its key is greater than or equal to the key at its left child and less than or equal to the key at its right child? 14.2: Deleting leaves is easy. 14.3: Make use of the decrease and conquer principle. 14.4: Perform binary search, keeping some additional state. 14.5: Can the min-rst property help prune the search? 14.6: Which element should be the root? 14.7: The tricky part is attaching the root to its subtrees. 14.8: Update pointer elds, not node contents. 14.9: Can you relate this problem to Problems 14.7 on Page 106 and 14.8 on Page 107? 14.10: What does an inorder traversal yield? 14.11: Draw the ve BSTs on the keys 1, 2, 3, and the corresponding traversal orders. 14.12: Take advantage of the BST property. 14.13: For what specic arrangements of r, s, and m does the check pass? 14.14: How many edges are traversed when the successor function is repeatedly called m times? 14.15: How would you solve this if A, B, and C were in a single sorted array? 14.16: For each page, count of the number of times it has been visited. 14.17: Use a federation of data structures. 14.18: How does the distance of z = z0 z1 from the origin relate to the distances of z0 and z1 from the origin? 14.19: First organize the individual line segments. 14.20: Use additional global state. 14.21: How would you count the number of entries that are less than a given value? How does that relate to the question? 14.22: Build a BST on left endpoints. For a node n what do you need to know about the right endpoints corresponding to left endpoints in the subtree rooted at n? 15.1: Think of an ecient way of merging skylines. 15.2: Let A and B be arrays. How would you count the number of inversions where one element is from A and the other from B in the array consisting of elements from A and B? 15.3: Start with the one dimensional case. 15.4: The longest path may or may not pass through the root. 15.5: The maximum subarray may or may not wrap around. 15.6: Express the longest nondecreasing subsequence ending at A[i] in terms of the longest nondecreasing subsequence in A[0 : i 1]. desired property, without looking past i? ElementsOfProgrammingInterviews.com 15.7: When can you be sure that an index i cannot be the starting point of a subarray with the

Hints for Problems

177

15.8: How would you eciently nd the largest rectangle which includes the i-th building, and has height A[i]? 15.9: How would you eciently check if A[i : i + a][ j : j + b] satises the constraints, assuming you have already performed similar checks? 15.10: Imagine you know for each (i, j) if it is possible to traverse entries in A in the order prescribed by S[0 : k 1] and end at (i, j). 15.11: Consider the same problem for A[0 : i 1] and B[0 : j 1]. concatenation of dictionary words. 15.13: Focus on the last word and the last line. 15.14: Write an equation. 15.15: Count the number of combinations in which there are 0 w0 plays, then 1 w0 plays, etc. 15.16: If i > 0 and j > 0, you can get to (i, j) from (i 1, j) or ( j 1, i). 15.18: Maximize the values of the coins picked up by Player F. 15.19: There are two possibilities for each nodend the optimum minimum power for each. 15.20: Follow the denition of a two-dimensional tree but watch out for repeated computation. 15.21: Write an equation for the total waiting time, assuming Client i is the ci -th client served. 15.22: Think about the total wasted time. 15.23: Intuitively, which load should be assigned to the server with the largest capacity? 15.24: Consider the problem of determining if it is feasible to implement the storage using no more than M bytes per server. 15.25: Design a data structure that makes it possible to quickly nd the rst box with a specied capacity. It should also be fast to update once an item has been placed. 15.26: Reduce the problem from n symbols to one on n 1 symbols. 15.27: Would you prefer to add weight to a node or to its children? everyone who cannot be invited from consideration? 15.29: Focus on the number of nondiverse edges rather than the number of nondiverse nodes. 16.1: Model the maze as a graph. 16.2: Treat strings as vertices in an undirected graph, with an edge between u and v i the corresponding strings dier in one character. 16.3: Model as a graph and think about the implication of an odd length cycle. 16.4: Study the relationship between cycles and degrees of connectedness. 16.5: Model using a directed graph. 16.6: Form a partition {E0 , S1 , . . . , Ek1 } of the variables such that xi El and x j El if and only if the equality constraints force them to be equal. 16.7: Form a DAG in which paths correspond to valid placements. 16.8: What property does a minimal set of infeasible tasks have? 16.9: Change the edge cost and cast it as an instance of the standard shortest path problem. 16.10: Assuming you know the fastest route to a city c, how would you compute the fastest routes to cities c has outgoing ights to, assuming you have to pass through c rst? 15.28: Who can you guarantee cannot be invited? What happens after you have removed 15.17: What is the maximum value of sh the sherman can catch if he ends his trip at (i, j)?

15.12: Solve the generalized problem, i.e., determine for each prex of s whether it is the

ElementsOfProgrammingInterviews.com

178

Hints for Problems

16.11: Suppose best new section is from bs to b f . What property must be true of the portion of the route from El Paso to bs and from b f to Corpus Christi? 16.12: The eect of a sequence of conversions is multiplicative. Can you recast the problem so that it can be calculated additively? 16.13: What can you say about an edge that is the heaviest on some cycle? How about an edge that is the lightest across a set of edges that disconnect the graph? 17.1: Consider the Boolean-valued function P(i, w), which is true i it is possible for the rst i states to assign w votes to R. 17.2: The obvious recurrence is not the right one. 17.3: See whether dierences of 0, 1, 2, . . . can be achieved. 17.4: Solve the n jugs case. 17.5: Compute M(v, ), the minimum cost path from s to v with a delay less than or equal to . Alternately, try to use a well-known graph algorithm as a subroutine in a heuristic solution. 17.6: A minimum spanning tree on the cities is fast to compute. 17.7: Given i 1 warehouses whose locations are xed, where would you place the i-th one? 17.8: Apply the constraints to speed up a brute-force algorithm. 17.9: Choosing the right data structure helps with an enumerative solution. 17.10: Find a shortest derivation of xk given shortest derivations of xi , for all i < k. 17.11: A CNF is satisable i for every variable v, v=0 or v=1 are satisable, where v=b is the expression resulting from the substitution of v by b in . 17.12: How would you eciently check the conjecture for n assuming it holds for all m < n? 17.13: Use a graph representation of the constraints. 18.1: Look for races, and lock as little as possible to avoid reducing throughput. 18.2: Use multithreading, but control the number of threads. 18.3: For each request create a thread which launches another thread. 18.4: There are two aspectsdata structure design and concurrency. 18.5: Track the number of readers. 18.6: Force readers to acquire a write lock. 18.7: Introduce additional state. 18.8: Use wait and notify judiciously 18.9: Identify races, and when the barber and customers need to be woken up. 18.10: Break symmetries with a total ordering. 18.11: Use multithreading for performancetake care to minimize threading overhead. 18.12: Which child should u message rst? 18.13: Have hosts share the portion of the graph they have discovered with their neighbors. 18.14: Can a trillion 1000 byte strings t on one machine? 18.15: Use a server to coordinate the crawl. 19.1: How would you dene the distance between two images? 19.2: Build on the idea of a books index. 19.3: Consider both data structure and hardware optimizations. 19.4: Start with an appropriate notion of distance between words. ElementsOfProgrammingInterviews.com

Hints for Problems 19.5: The examples are suggestive of general rules. 19.6: There are two aspectsbuilding blocks (e.g., fonts, symbols) and hierarchical layout. 19.7: Dont start at the beginning of the le. 19.8: Normalize the video format and create signatures.

179

19.9: This must be performed on an ensemble of machines. The right data structures will simplify the computation. 19.10: How would you partition jobs across machines? Is it always essential to operate on the highest priority job? 19.11: Use two queues. 19.12: Consider the stakeholders separately. 19.13: This problem can be solved with various degrees of algorithmic sophistication: none at all, simple frequency analysis, or machine learning. 19.14: Separate algorithmic challenges from UI implementation. 19.15: Exploit the data center. 19.16: Identify the key challenges. Think about the class design. 19.17: Follow the ow of information. 20.1: Focus on small n. Specically, count the number of possible exchanges. 20.2: Use a routine that yields k-sized subsets to create a routine for k + 1-sized subsets. 20.3: If the result is stored in A, how would you proceed once A[n 1] is assigned correctly? 20.4: How would you mimic a three-sided coin with a two-sided coin? X . What do the jumps correspond to? 20.5: Look at the graph of the probability distribution function FX (), i.e., the probability that 20.6: Suppose you have a procedure which selects k packets from the rst n k packets as specied. How would you deal with the n + 1-th packet? 20.7: Simulate Solution 20.2 on Page 441, using an appropriate data structure to reduce space. 20.8: Write a recurrence relation for Pr(r, n), the probability that exactly r Republicans win in elections {1, 2, . . . , n}. Solve it programmatically, taking care to be ecient. appropriate sum of Bernoulli random variables. 20.10: Start by write an exact and then an approximate expression for the probability of any given bin being empty. 20.11: Use a 0/1-valued random variable per index, and exploit the linearity of expectation. 20.12: Start with a two-sided die, i.e., a coin. 20.13: Find a simple necessary and sucient condition for the segments to form a a triangle. 20.14: Write an expression for the probability distribution for u2. 20.15: It is a bad idea to make a decision very early or very late. 20.16: Find a strategy that maximizes the winning probability, then compute the expected gain. 20.17: Solve the problem for a deck with two red and two black cards, then write a recurrence for the general case. Solve it programmatically for a standard deck. 20.18: Write a recurrence equation for the maximum prot as a function of r and b, the number of red and black cards in the deck. Solve the recurrence for small values of r and b and form a hypothesis as to the general solution. 20.19: Write an equation for the prot as a function of B and X and then compute its expectation. ElementsOfProgrammingInterviews.com 20.9: Use Bayes rule to compute the probability. Then apply bounding techniques to an

180
20.20: For most people, the utility of money increases logarithmically.

Hints for Problems

20.21: Use the basic denitions of Boolean AND and OR to force an evaluator to look at both terms in an expression. 20.22: There are two possible outcomes at expiration. Write the conditions that imply an arbitrage in terms of option price, and the number of shares and the number of options. 20.23: Write a system of inequalities in terms of the quantity of stocks, options, and bonds that captures an arbitrage. 20.24: Compute the expected value of the random variable which is equal to the stock price minus 300 at expiration, when the stock price is greater than or equal to 300, and 0 otherwise. 21.1: Solve the same problem with 2, 5, 10, and 20 doors. 21.2: Use transitivity to eliminate as many cyclists with each race as possible. 21.3: Draw a picturespecically, graph height against time. 21.4: Try the same problem out on smaller bars. 21.5: Is there a subset of coins that the rst player can force the second player to choose? 21.6: Think of symmetrical game play. 21.7: Consider a rectangle with an additional square on the lower row. 21.8: Think about shadowing your opponent. 21.9: Process the buildings in sorted order. 21.10: Think about starting with more than enough gas to complete the circuit without gassing up. Track the amount of gas as you perform the circuit, gassing up at each city. 21.11: Focus on the rst half of x. For example, if x = 10110101, the rst half of x is 1011. Could the closest palindrome begin with a 0, or a 11? 21.12: Consider the products of the rst i 1 and the last n i elements. Alternately, count the number of negative entries and zero entries. 21.13: Write a recurrence relation. 21.14: Does the order in which whacks are performed matter? 21.15: Iteratively eliminate noncelebrities. 21.16: Model using graphs and perform a case analysis. 21.17: Build the path inductively. 21.18: The simple greedy strategy does not always work. Devise an algorithm that permanently pairs at least one professor and a student in each iteration. 21.19: Model celebrities and bidders as vertices. 21.20: Look for a long path in a graph. 21.21: This problem can be reduced to one of the four graph problems on Page 135. 21.22: Suppose you knew the maximum matches for each of a and bs children, where a lies in A and b in B. How would you nd the maximum match between a and b? 21.23: Model the problem as a graph with ows corresponding to unassigned wins. 21.24: Many assignment problems can be solved using max-ow. 21.25: Think about islands with 24 inhabitants and dierent combinations of eye colors. 21.26: Introduce a new variable that captures the maximum.

ElementsOfProgrammingInterviews.com

You might also like