# Difference between revisions of "Chapter 3"

Jump to navigation
Jump to search

m (Protected "Chapter 3" ([Edit=Allow only administrators] (indefinite) [Move=Allow only administrators] (indefinite))) |
|||

(11 intermediate revisions by the same user not shown) | |||

Line 1: | Line 1: | ||

− | =Data | + | =Data Structures= |

===Stacks, Queues, and Lists=== | ===Stacks, Queues, and Lists=== | ||

− | [[3.1]] | + | :[[3.1]]. A common problem for compilers and text editors is determining whether the parentheses in a string are balanced and properly nested. For example, the string <math>((())())()</math> contains properly nested pairs of parentheses, which the strings <math>)()(</math> and <math>())</math> do not. Give an algorithm that returns true if a string contains properly nested and balanced parentheses, and false if otherwise. For full credit, identify the position of the first offending parenthesis if the string is not properly nested and balanced. |

+ | [[3.1|Solution]] | ||

− | 3.2 | + | :3.2. Give an algorithm that takes a string <math>S</math> consisting of opening and closing parentheses, say )()(())()()))())))(, and finds the length of the longest balanced parentheses in <math>S</math>, which is 12 in the example above. (Hint: The solution is not necessarily a contiguous run of parenthesis from <math>S</math>.) |

− | [[3.3]] | + | :[[3.3]]. Give an algorithm to reverse the direction of a given singly linked list. In other words, after the reversal all pointers should now point backwards. Your algorithm should take linear time. |

+ | [[3.3|Solution]] | ||

− | 3.4 | + | :3.4. Design a stack <math>S</math> that supports ''S.push(x)'', ''S.pop()'', and ''S.findmin()'', which returns the minimum element of <math>S</math>. All operations should run in constant time. |

− | [[3.5]] | + | :[[3.5]]. We have seen how dynamic arrays enable arrays to grow while still achieving constant-time amortized performance. This problem concerns extending dynamic arrays to let them both grow and shrink on demand. |

+ | :(a) Consider an underflow strategy that cuts the array size in half whenever the array falls below half full. Give an example sequence of insertions and deletions where this strategy gives a bad amortized cost. | ||

+ | :(b) Then, give a better underflow strategy than that suggested above, one that achieves constant amortized cost per deletion. | ||

+ | [[3.5|Solution]] | ||

− | 3.6 | + | :3.6. Suppose you seek to maintain the contents of a refrigerator so as to minimize food spoilage. What data structure should you use, and how should you use it? |

− | [[3.7]] | + | :[[3.7]]. Work out the details of supporting constant-time deletion from a singly linked list as per the footnote from page 79, ideally to an actual implementation. Support the other operations as efficiently as possible. |

+ | [[3.7|Solution]] | ||

===Elementary Data Structures=== | ===Elementary Data Structures=== | ||

− | 3.8 | + | :3.8. Tic-tac-toe is a game played on an <math>n * n</math> board (typically <math>n = 3</math>) where two players take consecutive turns placing “O” and “X” marks onto the board cells. The game is won if n consecutive “O” or ‘X” marks are placed in a row, column, or diagonal. Create a data structure with <math>O(n)</math> space that accepts a sequence of moves, and reports in constant time whether the last move won the game. |

− | [[3.9]] | + | :[[3.9]]. Write a function which, given a sequence of digits 2–9 and a dictionary of <math>n</math> words, reports all words described by this sequence when typed in on a standard telephone keypad. For the sequence 269 you should return any, box, boy, and cow, among other words. |

+ | [[3.9|Solution]] | ||

− | 3.10 | + | :3.10. Two strings <math>X</math> and <math>Y</math> are anagrams if the letters of <math>X</math> can be rearranged to form <math>Y</math> . For example, silent/listen, and incest/insect are anagrams. Give an efficient algorithm to determine whether strings <math>X</math> and <math>Y</math> are anagrams. |

===Trees and Other Dictionary Structures=== | ===Trees and Other Dictionary Structures=== | ||

− | [[3.11]] | + | :[[3.11]]. Design a dictionary data structure in which search, insertion, and deletion can all be processed in <math>O(1)</math> time in the worst case. You may assume the set elements are integers drawn from a finite set <math>1, 2, .., n</math>, and initialization can take <math>O(n)</math> time. |

+ | [[3.11|Solution]] | ||

− | 3.12 | + | :3.12. The maximum depth of a binary tree is the number of nodes on the path from the root down to the most distant leaf node. Give an <math>O(n)</math> algorithm to find the maximum depth of a binary tree with <math>n</math> nodes. |

− | [[3.13]] | + | :[[3.13]]. Two elements of a binary search tree have been swapped by mistake. Give an <math>O(n)</math> algorithm to identify these two elements so they can be swapped back. |

+ | [[3.13|Solution]] | ||

− | 3.14 | + | :3.14. Given two binary search trees, merge them into a doubly linked list in sorted order. |

− | [[3.15]] | + | :[[3.15]]. Describe an <math>O(n)</math>-time algorithm that takes an <math>n</math>-node binary search tree and constructs an equivalent height-balanced binary search tree. In a height-balanced binary search tree, the difference between the height of the left and right subtrees of every node is never more than 1. |

+ | [[3.15|Solution]] | ||

− | 3.16 | + | :3.16. Find the storage efficiency ratio (the ratio of data space over total space) for each of the following binary tree implementations on n nodes: |

+ | :(a) All nodes store data, two child pointers, and a parent pointer. The data field requires 4 bytes and each pointer requires 4 bytes. | ||

+ | :(b) Only leaf nodes store data; internal nodes store two child pointers. The data field requires four bytes and each pointer requires two bytes. | ||

− | [[3.17]] | + | :[[3.17]]. Give an <math>O(n)</math> algorithm that determines whether a given <math>n</math>-node binary tree is height-balanced (see Problem 3-15). |

+ | [[3.17|Solution]] | ||

− | 3.18 | + | :3.18. Describe how to modify any balanced tree data structure such that search, insert, delete, minimum, and maximum still take <math>O(log n)</math> time each, but successor and predecessor now take <math>O(1)</math> time each. Which operations have to be modified to support this? |

− | [[3.19]] | + | :[[3.19]]. Suppose you have access to a balanced dictionary data structure that supports each of the operations search, insert, delete, minimum, maximum, successor, and predecessor in <math>O(log n)</math> time. Explain how to modify the insert and delete operations so they still take <math>O(log n)</math> but now minimum and maximum take <math>O(1)</math> time. (Hint: think in terms of using the abstract dictionary operations, instead of mucking about with pointers and the like.) |

+ | [[3.19|Solution]] | ||

− | 3.20 | + | :3.20. Design a data structure to support the following operations: |

+ | :• ''insert''(<math>x,T</math>) – Insert item <math>x</math> into the set <math>T</math>. | ||

+ | :• ''delete''(<math>k,T</math>) – Delete the <math>k</math>th smallest element from <math>T</math>. | ||

+ | :• ''member''(<math>x,T</math>) – Return true iff <math>x \in T</math>. | ||

+ | :All operations must take <math>O(log n)</math> time on an <math>n</math>-element set. | ||

− | [[3.21]] | + | :[[3.21]]. A ''concatenate operation'' takes two sets <math>S_1</math> and <math>S_2</math>, where every key in <math>S_1</math> is smaller than any key in <math>S_2</math>, and merges them. Give an algorithm to concatenate two binary search trees into one binary search tree. The worst-case running time should be <math>O(h)</math>, where <math>h</math> is the maximal height of the two trees. |

+ | [[3.21|Solution]] | ||

===Applications of Tree Structures=== | ===Applications of Tree Structures=== | ||

− | 3.22 | + | :3.22. Design a data structure that supports the following two operations: |

+ | :• ''insert''(<math>x</math>) – Insert item <math>x</math> from the data stream to the data structure. | ||

+ | :• ''median''() – Return the median of all elements so far. | ||

+ | :All operations must take <math>O(log n)</math> time on an <math>n</math>-element set. | ||

− | [[3.23]] | + | :[[3.23]]. Assume we are given a standard dictionary (balanced binary search tree) defined on a set of <math>n</math> strings, each of length at most <math>l</math>. We seek to print out all strings beginning with a particular prefix <math>p</math>. Show how to do this in <math>O(ml log n)</math> time, where <math>m</math> is the number of strings. |

+ | [[3.23|Solution]] | ||

− | 3.24 | + | :3.24. An array <math>A</math> is called <math>k</math>-unique if it does not contain a pair of duplicate elements within <math>k</math> positions of each other, that is, there is no <math>i</math> and <math>j</math> such that <math>A[i] = A[j]</math> and <math>|j - i| \leq k</math>. Design a worst-case <math>O(n log k)</math> algorithm to test if <math>A</math> is <math>k</math>-unique. |

− | [[3.25]] | + | :[[3.25]]. In the ''bin-packing problem'', we are given <math>n</math> objects, each weighing at most 1 kilogram. Our goal is to find the smallest number of bins that will hold the <math>n</math> objects, with each bin holding 1 kilogram at most. |

+ | :• The ''best-fit heuristic'' for bin packing is as follows. Consider the objects in the order in which they are given. For each object, place it into the partially filled bin with the smallest amount of extra room after the object is inserted. If no such bin exists, start a new bin. Design an algorithm that implements the best-fit heuristic (taking as input the <math>n</math> weights <math>w_1, w_2, ..., w_n</math> and outputting the number of bins used) in <math>O(n log n)</math> time. | ||

+ | :• Repeat the above using the ''worst-fit heuristic'', where we put the next object into the partially filled bin with the largest amount of extra room after the object is inserted. | ||

+ | [[3.25|Solution]] | ||

− | 3.26 | + | :3.26. Suppose that we are given a sequence of <math>n</math> values <math>x_1, x_2, ..., x_n</math> and seek to quickly answer repeated queries of the form: given <math>i</math> and <math>j</math>, find the smallest value in <math>x_i, . . . , x_j</math>. |

+ | :(a) Design a data structure that uses <math>O(n^2)</math> space and answers queries in <math>O(1)</math> time. | ||

+ | :(b) Design a data structure that uses <math>O(n)</math> space and answers queries in <math>O(log n)</math> time. For partial credit, your data structure can use <math>O(n log n)</math> space and have <math>O(log n)</math> query time. | ||

− | [[3.27]] | + | :[[3.27]]. Suppose you are given an input set <math>S</math> of <math>n</math> integers, and a black box that if given any sequence of integers and an integer <math>k</math> instantly and correctly answers whether there is a subset of the input sequence whose sum is exactly <math>k</math>. Show how to use the black box <math>O(n)</math> times to find a subset of <math>S</math> that adds up to <math>k</math>. |

+ | [[3.27|Solution]] | ||

− | 3.28 | + | :3.28. Let <math>A[1..n]</math> be an array of real numbers. Design an algorithm to perform any sequence of the following operations: |

+ | :• ''Add''(<math>i,y</math>) – Add the value <math>y</math> to the <math>i</math>th number. | ||

+ | :• ''Partial-sum''(<math>i</math>) – Return the sum of the first <math>i</math> numbers, that is, <math>\sum_{j=1}^i A[j]</math>. | ||

+ | :There are no insertions or deletions; the only change is to the values of the numbers. Each operation should take <math>O(log n)</math> steps. You may use one additional array of size <math>n</math> as a work space. | ||

− | [[3.29]] | + | :[[3.29]]. Extend the data structure of the previous problem to support insertions and deletions. Each element now has both a ''key'' and a ''value''. An element is accessed by its key, but the addition operation is applied to the values. The ''Partial_sum'' operation is different. |

+ | :• ''Add''(<math>k,y</math>) – Add the value <math>y</math> to the item with key <math>k</math>. | ||

+ | :• ''Insert''(<math>k,y</math>) – Insert a new item with key <math>k</math> and value <math>y</math>. | ||

+ | :• ''Delete''(<math>k</math>) – Delete the item with key <math>k</math>. | ||

+ | :• ''Partial-sum''(<math>k</math>) – Return the sum of all the elements currently in the set whose key is less than <math>k</math>, that is, <math>\sum_{i < k} x_i</math>. | ||

+ | :The worst-case running time should still be <math>O(n log n)</math> for any sequence of <math>O(n)</math> operations. | ||

+ | [[3.29|Solution]] | ||

− | 3.30 | + | :3.30. You are consulting for a hotel that has <math>n</math> one-bed rooms. When a guest checks in, they ask for a room whose number is in the range <math>[l, h]</math>. Propose a data structure that supports the following data operations in the allotted time: |

+ | :(a) ''Initialize''(<math>n</math>): Initialize the data structure for empty rooms numbered <math>1, 2, . . . , n</math>, in polynomial time. | ||

+ | :(b) ''Count''(<math>l, h</math>): Return the number of available rooms in <math>[l, h]</math>, in <math>O(log n)</math> time. | ||

+ | :(c) ''Checkin''(<math>l, h</math>): In <math>O(log n)</math> time, return the first empty room in <math>[l, h]</math> and mark it occupied, or return NIL if all the rooms in <math>[l, h]</math> are occupied. | ||

+ | :(d) ''Checkout''(<math>x</math>): Mark room <math>x</math> as unoccupied, in <math>O(log n)</math> time. | ||

− | [[3.31]] | + | :[[3.31]]. Design a data structure that allows one to search, insert, and delete an integer <math>X</math> in <math>O(1)</math> time (i.e., constant time, independent of the total number of integers stored). Assume that <math>1 \leq X \leq n</math> and that there are <math>m + n</math> units of space available, where <math>m</math> is the maximum number of integers that can be in the table at any one time. (Hint: use two arrays <math>A[1..n]</math> and <math>B[1..m]</math>.) You are not allowed to initialize either <math>A</math> or <math>B</math>, as that would take <math>O(m)</math> or <math>O(n)</math> operations. This means the arrays are full of random garbage to begin with, so you must be very careful. |

+ | [[3.31|Solution]] | ||

===Implementation Projects=== | ===Implementation Projects=== | ||

− | 3.32 | + | :3.32. Implement versions of several different dictionary data structures, such as linked lists, binary trees, balanced binary search trees, and hash tables. Conduct experiments to assess the relative performance of these data structures in a simple application that reads a large text file and reports exactly one instance of each word that appears within it. This application can be efficiently implemented by maintaining a dictionary of all distinct words that have appeared thus far in the text and inserting/reporting each new word that appears in the stream. Write a brief report with your conclusions. |

− | [[3.33]] | + | :[[3.33]]. A Caesar shift (see Section 21.6 (page 697)) is a very simple class of ciphers for secret messages. Unfortunately, they can be broken using statistical properties of English. Develop a program capable of decrypting Caesar shifts of sufficiently long texts. |

+ | [[3.33|Solution]] | ||

===Interview Problems=== | ===Interview Problems=== | ||

− | 3.34 | + | :3.34. What method would you use to look up a word in a dictionary? |

− | [[3.35]] | + | :[[3.35]]. Imagine you have a closet full of shirts. What can you do to organize your shirts for easy retrieval? |

+ | [[3.35|Solution]] | ||

− | 3.36 | + | :3.36. Write a function to find the middle node of a singly linked list. |

− | [[3.37]] | + | :[[3.37]]. Write a function to determine whether two binary trees are identical. Identical trees have the same key value at each position and the same structure. |

+ | [[3.37|Solution]] | ||

− | 3.38 | + | :3.38. Write a program to convert a binary search tree into a linked list. |

− | [[3.39]] | + | :[[3.39]]. Implement an algorithm to reverse a linked list. Now do it without recursion. |

+ | [[3.39|Solution]] | ||

− | 3.40 | + | :3.40. What is the best data structure for maintaining URLs that have been visited by a web crawler? Give an algorithm to test whether a given URL has already been visited, optimizing both space and time. |

− | [[3.41]] | + | :[[3.41]]. You are given a search string and a magazine. You seek to generate all the characters in the search string by cutting them out from the magazine. Give an algorithm to efficiently determine whether the magazine contains all the letters in the search string. |

+ | [[3.41|Solution]] | ||

− | 3.42 | + | :3.42. Reverse the words in a sentence—that is, “My name is Chris” becomes “Chris is name My.” Optimize for time and space. |

− | [[3.43]] | + | :[[3.43]]. Determine whether a linked list contains a loop as quickly as possible without using any extra storage. Also, identify the location of the loop. |

+ | [[3.43|Solution]] | ||

− | 3.44 | + | :3.44. You have an unordered array <math>X</math> of <math>n</math> integers. Find the array <math>M</math> containing <math>n</math> elements where <math>M_i</math> is the product of all integers in <math>X</math> except for <math>X_i</math>. You may not use division. You can use extra memory. (Hint: there are solutions faster than <math>O(n^2)</math>.) |

− | [[3.45]] | + | :[[3.45]]. Give an algorithm for finding an ordered word pair (e.g. “New York”) occurring with the greatest frequency in a given webpage. Which data structures would you use? Optimize both time and space. |

+ | [[3.45|Solution]] | ||

Back to [[Chapter List]] | Back to [[Chapter List]] |

## Latest revision as of 18:06, 1 October 2020

## Contents

# Data Structures

### Stacks, Queues, and Lists

- 3.1. A common problem for compilers and text editors is determining whether the parentheses in a string are balanced and properly nested. For example, the string contains properly nested pairs of parentheses, which the strings and do not. Give an algorithm that returns true if a string contains properly nested and balanced parentheses, and false if otherwise. For full credit, identify the position of the first offending parenthesis if the string is not properly nested and balanced.

- 3.2. Give an algorithm that takes a string consisting of opening and closing parentheses, say )()(())()()))())))(, and finds the length of the longest balanced parentheses in , which is 12 in the example above. (Hint: The solution is not necessarily a contiguous run of parenthesis from .)

- 3.3. Give an algorithm to reverse the direction of a given singly linked list. In other words, after the reversal all pointers should now point backwards. Your algorithm should take linear time.

- 3.4. Design a stack that supports
*S.push(x)*,*S.pop()*, and*S.findmin()*, which returns the minimum element of . All operations should run in constant time.

- 3.5. We have seen how dynamic arrays enable arrays to grow while still achieving constant-time amortized performance. This problem concerns extending dynamic arrays to let them both grow and shrink on demand.
- (a) Consider an underflow strategy that cuts the array size in half whenever the array falls below half full. Give an example sequence of insertions and deletions where this strategy gives a bad amortized cost.
- (b) Then, give a better underflow strategy than that suggested above, one that achieves constant amortized cost per deletion.

- 3.6. Suppose you seek to maintain the contents of a refrigerator so as to minimize food spoilage. What data structure should you use, and how should you use it?

- 3.7. Work out the details of supporting constant-time deletion from a singly linked list as per the footnote from page 79, ideally to an actual implementation. Support the other operations as efficiently as possible.

### Elementary Data Structures

- 3.8. Tic-tac-toe is a game played on an board (typically ) where two players take consecutive turns placing “O” and “X” marks onto the board cells. The game is won if n consecutive “O” or ‘X” marks are placed in a row, column, or diagonal. Create a data structure with space that accepts a sequence of moves, and reports in constant time whether the last move won the game.

- 3.9. Write a function which, given a sequence of digits 2–9 and a dictionary of words, reports all words described by this sequence when typed in on a standard telephone keypad. For the sequence 269 you should return any, box, boy, and cow, among other words.

- 3.10. Two strings and are anagrams if the letters of can be rearranged to form . For example, silent/listen, and incest/insect are anagrams. Give an efficient algorithm to determine whether strings and are anagrams.

### Trees and Other Dictionary Structures

- 3.11. Design a dictionary data structure in which search, insertion, and deletion can all be processed in time in the worst case. You may assume the set elements are integers drawn from a finite set , and initialization can take time.

- 3.12. The maximum depth of a binary tree is the number of nodes on the path from the root down to the most distant leaf node. Give an algorithm to find the maximum depth of a binary tree with nodes.

- 3.13. Two elements of a binary search tree have been swapped by mistake. Give an algorithm to identify these two elements so they can be swapped back.

- 3.14. Given two binary search trees, merge them into a doubly linked list in sorted order.

- 3.15. Describe an -time algorithm that takes an -node binary search tree and constructs an equivalent height-balanced binary search tree. In a height-balanced binary search tree, the difference between the height of the left and right subtrees of every node is never more than 1.

- 3.16. Find the storage efficiency ratio (the ratio of data space over total space) for each of the following binary tree implementations on n nodes:
- (a) All nodes store data, two child pointers, and a parent pointer. The data field requires 4 bytes and each pointer requires 4 bytes.
- (b) Only leaf nodes store data; internal nodes store two child pointers. The data field requires four bytes and each pointer requires two bytes.

- 3.17. Give an algorithm that determines whether a given -node binary tree is height-balanced (see Problem 3-15).

- 3.18. Describe how to modify any balanced tree data structure such that search, insert, delete, minimum, and maximum still take time each, but successor and predecessor now take time each. Which operations have to be modified to support this?

- 3.19. Suppose you have access to a balanced dictionary data structure that supports each of the operations search, insert, delete, minimum, maximum, successor, and predecessor in time. Explain how to modify the insert and delete operations so they still take but now minimum and maximum take time. (Hint: think in terms of using the abstract dictionary operations, instead of mucking about with pointers and the like.)

- 3.20. Design a data structure to support the following operations:
- •
*insert*() – Insert item into the set . - •
*delete*() – Delete the th smallest element from . - •
*member*() – Return true iff . - All operations must take time on an -element set.

- 3.21. A
*concatenate operation*takes two sets and , where every key in is smaller than any key in , and merges them. Give an algorithm to concatenate two binary search trees into one binary search tree. The worst-case running time should be , where is the maximal height of the two trees.

### Applications of Tree Structures

- 3.22. Design a data structure that supports the following two operations:
- •
*insert*() – Insert item from the data stream to the data structure. - •
*median*() – Return the median of all elements so far. - All operations must take time on an -element set.

- 3.23. Assume we are given a standard dictionary (balanced binary search tree) defined on a set of strings, each of length at most . We seek to print out all strings beginning with a particular prefix . Show how to do this in time, where is the number of strings.

- 3.24. An array is called -unique if it does not contain a pair of duplicate elements within positions of each other, that is, there is no and such that and . Design a worst-case algorithm to test if is -unique.

- 3.25. In the
*bin-packing problem*, we are given objects, each weighing at most 1 kilogram. Our goal is to find the smallest number of bins that will hold the objects, with each bin holding 1 kilogram at most. - • The
*best-fit heuristic*for bin packing is as follows. Consider the objects in the order in which they are given. For each object, place it into the partially filled bin with the smallest amount of extra room after the object is inserted. If no such bin exists, start a new bin. Design an algorithm that implements the best-fit heuristic (taking as input the weights and outputting the number of bins used) in time. - • Repeat the above using the
*worst-fit heuristic*, where we put the next object into the partially filled bin with the largest amount of extra room after the object is inserted.

- 3.26. Suppose that we are given a sequence of values and seek to quickly answer repeated queries of the form: given and , find the smallest value in .
- (a) Design a data structure that uses space and answers queries in time.
- (b) Design a data structure that uses space and answers queries in time. For partial credit, your data structure can use space and have query time.

- 3.27. Suppose you are given an input set of integers, and a black box that if given any sequence of integers and an integer instantly and correctly answers whether there is a subset of the input sequence whose sum is exactly . Show how to use the black box times to find a subset of that adds up to .

- 3.28. Let be an array of real numbers. Design an algorithm to perform any sequence of the following operations:
- •
*Add*() – Add the value to the th number. - •
*Partial-sum*() – Return the sum of the first numbers, that is, . - There are no insertions or deletions; the only change is to the values of the numbers. Each operation should take steps. You may use one additional array of size as a work space.

- 3.29. Extend the data structure of the previous problem to support insertions and deletions. Each element now has both a
*key*and a*value*. An element is accessed by its key, but the addition operation is applied to the values. The*Partial_sum*operation is different. - •
*Add*() – Add the value to the item with key . - •
*Insert*() – Insert a new item with key and value . - •
*Delete*() – Delete the item with key . - •
*Partial-sum*() – Return the sum of all the elements currently in the set whose key is less than , that is, . - The worst-case running time should still be for any sequence of operations.

- 3.30. You are consulting for a hotel that has one-bed rooms. When a guest checks in, they ask for a room whose number is in the range . Propose a data structure that supports the following data operations in the allotted time:
- (a)
*Initialize*(): Initialize the data structure for empty rooms numbered , in polynomial time. - (b)
*Count*(): Return the number of available rooms in , in time. - (c)
*Checkin*(): In time, return the first empty room in and mark it occupied, or return NIL if all the rooms in are occupied. - (d)
*Checkout*(): Mark room as unoccupied, in time.

- 3.31. Design a data structure that allows one to search, insert, and delete an integer in time (i.e., constant time, independent of the total number of integers stored). Assume that and that there are units of space available, where is the maximum number of integers that can be in the table at any one time. (Hint: use two arrays and .) You are not allowed to initialize either or , as that would take or operations. This means the arrays are full of random garbage to begin with, so you must be very careful.

### Implementation Projects

- 3.32. Implement versions of several different dictionary data structures, such as linked lists, binary trees, balanced binary search trees, and hash tables. Conduct experiments to assess the relative performance of these data structures in a simple application that reads a large text file and reports exactly one instance of each word that appears within it. This application can be efficiently implemented by maintaining a dictionary of all distinct words that have appeared thus far in the text and inserting/reporting each new word that appears in the stream. Write a brief report with your conclusions.

- 3.33. A Caesar shift (see Section 21.6 (page 697)) is a very simple class of ciphers for secret messages. Unfortunately, they can be broken using statistical properties of English. Develop a program capable of decrypting Caesar shifts of sufficiently long texts.

### Interview Problems

- 3.34. What method would you use to look up a word in a dictionary?

- 3.35. Imagine you have a closet full of shirts. What can you do to organize your shirts for easy retrieval?

- 3.36. Write a function to find the middle node of a singly linked list.

- 3.37. Write a function to determine whether two binary trees are identical. Identical trees have the same key value at each position and the same structure.

- 3.38. Write a program to convert a binary search tree into a linked list.

- 3.39. Implement an algorithm to reverse a linked list. Now do it without recursion.

- 3.40. What is the best data structure for maintaining URLs that have been visited by a web crawler? Give an algorithm to test whether a given URL has already been visited, optimizing both space and time.

- 3.41. You are given a search string and a magazine. You seek to generate all the characters in the search string by cutting them out from the magazine. Give an algorithm to efficiently determine whether the magazine contains all the letters in the search string.

- 3.42. Reverse the words in a sentence—that is, “My name is Chris” becomes “Chris is name My.” Optimize for time and space.

- 3.43. Determine whether a linked list contains a loop as quickly as possible without using any extra storage. Also, identify the location of the loop.

- 3.44. You have an unordered array of integers. Find the array containing elements where is the product of all integers in except for . You may not use division. You can use extra memory. (Hint: there are solutions faster than .)

- 3.45. Give an algorithm for finding an ordered word pair (e.g. “New York”) occurring with the greatest frequency in a given webpage. Which data structures would you use? Optimize both time and space.

Back to Chapter List