Recursion Problems. Warm Ups. Enumeration 1 / 7

Similar documents
Data Structures and Algorithms

Algorithms. AVL Tree

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

Algorithms. Deleting from Red-Black Trees B-Trees

R10 SET - 1. Code No: R II B. Tech I Semester, Supplementary Examinations, May

Binary Trees, Binary Search Trees

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

CE 221 Data Structures and Algorithms

V Advanced Data Structures

Friday Four Square! 4:15PM, Outside Gates

Binary Trees. BSTs. For example: Jargon: Data Structures & Algorithms. root node. level: internal node. edge.

TREES. Trees - Introduction

I2206 Data Structures TS 6: Binary Trees - Binary Search Trees

V Advanced Data Structures

Garbage Collection: recycling unused memory

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs

2-3 Tree. Outline B-TREE. catch(...){ printf( "Assignment::SolveProblem() AAAA!"); } ADD SLIDES ON DISJOINT SETS

Largest Online Community of VU Students

Binary Trees

Trees. (Trees) Data Structures and Programming Spring / 28

CSE 530A. B+ Trees. Washington University Fall 2013

Data Structure. IBPS SO (IT- Officer) Exam 2017

CS301 - Data Structures Glossary By

Trees : Part 1. Section 4.1. Theory and Terminology. A Tree? A Tree? Theory and Terminology. Theory and Terminology

1. Meshes. D7013E Lecture 14

CS F-11 B-Trees 1

Organizing Spatial Data

Lecture 13: AVL Trees and Binary Heaps

Introduction. for large input, even access time may be prohibitive we need data structures that exhibit times closer to O(log N) binary search tree

CSCI2100B Data Structures Trees

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010

Multiway searching. In the worst case of searching a complete binary search tree, we can make log(n) page faults Everyone knows what a page fault is?

EE 368. Weeks 5 (Notes)

Problem A - Complete the sequence

Recall: Properties of B-Trees

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers?

B-Trees and External Memory

CSE100. Advanced Data Structures. Lecture 12. (Based on Paul Kube course materials)

Section Handout 4. Problem One: Weights and Balances (Courtesy of Eric Roberts)

18.3 Deleting a key from a B-tree

CSE 250 Final Exam. Fall 2013 Time: 3 hours. Dec 11, No electronic devices of any kind. You can open your textbook and notes

Basic Data Structures (Version 7) Name:

Programming II (CS300)

CS-301 Data Structure. Tariq Hanif

B-Trees and External Memory

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305

Data Structures Question Bank Multiple Choice

Computer Science 210 Data Structures Siena College Fall Topic Notes: Priority Queues and Heaps

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology

Need Backtracking! L 0 A 1 B 2 K 3 P 4 C 5 I 6 Z 7 S 8 A 9 N 10 X 11 A 12 N 13 X 14 P 15

x-fast and y-fast Tries

12 Abstract Data Types

SFU CMPT Lecture: Week 9

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking

Binary heaps (chapters ) Leftist heaps

Question Bank Subject: Advanced Data Structures Class: SE Computer

Trees. Reading: Weiss, Chapter 4. Cpt S 223, Fall 2007 Copyright: Washington State University

University of Palestine. Final Exam 2 nd semester 2014/2015 Total Grade: 50

CS 206 Introduction to Computer Science II

Binary Search Trees Treesort

March 20/2003 Jayakanth Srinivasan,

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 165

- 1 - Handout #22S May 24, 2013 Practice Second Midterm Exam Solutions. CS106B Spring 2013

Data Structures. Outline. Introduction Linked Lists Stacks Queues Trees Deitel & Associates, Inc. All rights reserved.

CSCI Trees. Mark Redekopp David Kempe

An undirected graph is a tree if and only of there is a unique simple path between any 2 of its vertices.

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage:

Balanced Trees Part Two

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1

Binary Search Trees. Analysis of Algorithms

1 Format. 2 Topics Covered. 2.1 Minimal Spanning Trees. 2.2 Union Find. 2.3 Greedy. CS 124 Quiz 2 Review 3/25/18

17CS33:Data Structures Using C QUESTION BANK

7.1 Introduction. A (free) tree T is A simple graph such that for every pair of vertices v and w there is a unique path from v to w

CS 206 Introduction to Computer Science II

2.2 Syntax Definition

x-fast and y-fast Tries

TREES Lecture 10 CS2110 Spring2014

l So unlike the search trees, there are neither arbitrary find operations nor arbitrary delete operations possible.

Chapter 10: Trees. A tree is a connected simple undirected graph with no simple circuits.

Final Examination CSE 100 UCSD (Practice)

DDS Dynamic Search Trees

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree.

UNIT III BALANCED SEARCH TREES AND INDEXING

B-Trees. Disk Storage. What is a multiway tree? What is a B-tree? Why B-trees? Insertion in a B-tree. Deletion in a B-tree

Data and File Structures Laboratory

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree

Problem Set 5 Solutions

CS 206 Introduction to Computer Science II

Lecture 9 March 4, 2010

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

INF2220: algorithms and data structures Series 1

XVIII Open Cup named after E.V. Pankratiev Stage 1: Grand Prix of Romania, Sunday, September 17, 2017

Figure 4.1: The evolution of a rooted tree.

MITOCW watch?v=ninwepprkdq

logn D. Θ C. Θ n 2 ( ) ( ) f n B. nlogn Ο n2 n 2 D. Ο & % ( C. Θ # ( D. Θ n ( ) Ω f ( n)

Outline for Today. Why could we construct them in time O(n)? Analyzing data structures over the long term.

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

References and Homework ABSTRACT DATA TYPES; LISTS & TREES. Abstract Data Type (ADT) 9/24/14. ADT example: Set (bunch of different values)

Transcription:

1 / 7 Recursion Problems Warm Ups 1. Write a recursive implementation of the factorial function. Recall that n! = 1 2 n, with the special case that 0! = 1. 2. Write a recursive function that, given a number n, returns the sum of the digits of the number n. 3. Write a recursive function that, given a string s, prints the characters of s in reverse order. 4. Write a recursive function that checks whether a string is a palindrome (a palindrome is a string that's the same when reads forwards and backwards.) 5. Write a recursive function that, given a pointer to the root of a binary search tree, prints out the elements in that tree in sorted order. 6. Write a recursive function that, given two strings, returns whether the first string is a subsequence of the second. For example, given hac and cathartic, you should return true, but given bat and table, you should return false. Enumeration 7. Given a list of n distinct elements, write a function that lists all subsets of those elements. 8. Given a list of n distinct elements, write a function that lists all permutations of that list. 9. Given a list of n distinct elements and a number k, write a function that lists all k element subsets of that list. Make sure not to output the same subset multiple times. 10. Given a list of n distinct elements and a number k, write a function that lists all k element permutations of that list. 11. Given a list of n distinct elements and a number k, write a function that lists all possible ways of assigning those elements into k (possibly empty) groups. 12. Given a nonnegative integer n, write a function that lists all strings formed from exactly n pairs of balanced parentheses. For example, given n = 3, you'd list these five strings: ((())) (()()) (())() ()(()) ()()() As a hint, given any string of n 1 balanced parentheses, focus on the first open parentheses and the close parentheses it matches. What can you say about the string inside those parentheses? What about the string that follows those parentheses? 13. Given a number n, generate all n character passwords, subject to the restriction that every password must have a number, a lower case letter, an upper case letter, and a symbol. 14. Given a number n, generate all distinct ways to write n as the sum of positive integers. For example, with n = 4, the options are 4, 3 + 1, 2 + 2, 2 + 1 + 1, and 1 + 1 + 1 + 1.

2 / 7 Backtracking 15. Given a list of n integers and a number U, write a function that returns whether there is a subset of those n integers that adds up to exactly U. (This is a famous problem called the subset sum problem, by the way.) 16. A shrinkable word is a word that can be reduced down to the empty string by deleting one letter at a time such that, at each stage, the remaining string is a word. For example, the word startling is shirnkable because of this sequence of words: startling starting staring string sting sing sin in i (empty) Write a function that accepts as input a string and a set of all the words in English, then reports whether the input word is shrinkable. 17. Some words can be spelled out using only element symbols from the periodic table. For example, the world canine can be spelled as CaNiNe (calcium, nickel, neon). Some words, like element, cannot. Write a function that accepts as input a string and a set of all the element symbols in the periodic table, then returns whether the word can or cannot be spelled using element symbols. Even better, if the string can be spelled this way, return the string with the capitalization changed to reflect that spelling. 18. Suppose you have n doctors, each of which are free for a certain number of hours per day, and m patients, each of whom needs to be seen for a certain number of hours. Write a function that determines whether it's possible for all the patients to be scheduled so that none of the doctors spends more time than they have available. Better yet, tell us which people should see which doctors. 19. You have a collection of cell phone towers, each represented by an (x, y) coordinate in the plane. Each cell phone tower needs to be assigned a transmitting frequency chosen from a list of k different frequencies. The only requirement is that no two towers within distance d of one another can be assigned the same frequency, since that would cause interference. Determine whether it's possible to assign the cell towers the frequencies so that no two towers overlap. If you can, tell us what frequencies get assigned to which towers. 20. You are given a grid of nonnegative integers. You begin in the upper left corner, and your goal is to get to the lower right corner. However, at each point in time, you can only move up, down, left, or right exactly the number of squares given by the number you're standing on. For example, if you were standing on a 3, you could move exactly three spots left, exactly three spots right, exactly three spots up, or exactly three spots down. You can't walk off the board. Determine if there's a path that gets you from the upper left corner of the grid to the lower right corner. Trees 21. Write a function that takes as input a pointer to the root of a binary tree, then returns whether it's a valid binary search tree. 22. Write a function that takes in a pointer to the root of a binary search tree, then deallocates all the nodes in that binary search tree.

3 / 7 23. In a binary tree, a common value subtree is a complete subtree (that is, either the empty tree or a node and all its descendants) where every node has the same value. Given a binary tree, return a pointer to the largest common value subtree in that tree. 24. Write a function that, given a sorted array, builds a balanced binary search tree with the same values. 25. A palindromic tree is a tree that is the same when it's mirrored around the root. For example, the left tree below is a palindromic tree and the right tree below is not: 3 3 2 2 1 1 5 4 4 5 1 2 1 2 1 2 2 1 Given a binary tree, determine whether it is a palindromic tree. Then try generalizing this to arbitrary multiway trees. 26. In a binary search tree, a node u is called an ancestor of a node v if the path from v back up to the root of the tree passes through u. For example, consider this BST: 7 2 12 1 5 9 13 4 6 8 11 15 3 10 14 16 Here, the ancestors of 6 are 6, 5, 2, and 7; the ancestors of 10 are 10, 11, 9, 12, and 7; and the only ancestor of 7 is 7 itself. (Note that every node is always an ancestor of itself). A common ancestor of two nodes v 1 and v 2 is a node u such that u is an ancestor of both v 1 and v 2. For example, in the above BST, 3 and 6 have 5 as a common ancestor, 9 and 16 have 7 as a common ancestor, and 2 and 15 have 7 as a common ancestor. The common ancestor of two nodes might be one of those nodes: for example, 12 is a common ancestor of 8 and 12. Finally, the lowest common ancestor of two nodes v 1 and v 2 is the node u such that u is a common ancestor of v 1 and v 2 that is as deep as possible. For example, the common ancestors of 14 and 16 include 7, 12, 13, and 15, of which 15 is their lowest common ancestor. The lowest common ancestor of 1 and 6 is 2, and the lowest common ancestor of 10 and 16 is 12. The lowest common ancestor of two nodes might be one of those nodes: the lowest common ancestor of 13 and 16 is 13, for example. Write a function that takes in a binary search tree and two values known to be present in that binary search tree, then returns their lowest common ancestor.

4 / 7 27. Suppose you have a multiway tree where each node has an associated integer value. Find a set of nodes with the maximum possible sum, subject to the constraint that you cannot choose a node and any of its children at the same time. 28. (The Great Tree List Recursion Problem, by Nick Parlante) A cell in a circularly, doublylinked list essentially looks the same as a node in a binary search tree each stores a value and two pointers. The only difference is that in a doubly linked list the pointers stand for previous and next, while in a binary search tree the pointers stand for left subtree and right subtree. Write a function that, given a pointer to the root of a binary search tree, converts that binary search tree into a sorted, doubly linked list by rewiring the pointers so that left and right now stand for previous and next. 29. Write a function that takes as input a pointer to the root of a binary tree, then deletes all the leaves from that binary tree. 30. Write a function that takes as input a pointer to the root of a binary tree, then returns whether that binary tree is a binary max heap (that is, whether it's a complete binary tree and whether each element is greater than its children). 31. A typical multiway tree is represented by having each node store pointers to each of its children. There's an alternative representation of a multiway tree as a binary tree called the left child, right sibling (LCRS) representation. In this representation, every node stores two pointers: a left pointer pointing to its first (leftmost) child, and a right pointer pointing to its next sibling. For example, here is a multiway tree and its LCRS representation: a b a b c d e c d e f g h i f g j h j k k i For example, focus on the node b. Its left pointer points to e, its first child. Its right pointer points to c, its next sibling (the next node that's a child of the same parent). Node c has no children, so its left pointer is null. Its right pointer points to its next sibling, d, whose right pointer points to null because it has no more siblings. Notice that node e has a null right pointer even though in the multiway tree the node f is to its right, f is not a sibling of node e. Write a pair of functions, one that converts a multiway tree into its LCRS representation, and one that converts an LCRS representation into a multiway tree.

5 / 7 32. Another way of representing multiway trees is as a spaghetti stack, where instead of nodes storing multiple pointers, one per child, the nodes store a single pointer that points back up to the parent. For example, below is a multiway tree and its representation as a spaghetti stack: When working with a spaghetti stack, instead of storing a single pointer to the root, you store a list of pointers, one for each leaf. Write three functions: one that converts a multiway tree to a spaghetti stack, one that converts a spaghetti stack into a multiway tree, and one that deallocates all the nodes in a spaghetti stack. Tries 33. Write a function that, given a pointer to the root of a trie, prints out all words in that trie. 34. Write a function that, given pointers to the roots of two tries, returns a pointer to the root of a new trie that contains all the words present in both tries. 35. Solve the previous problem, but do so in a way that doesn't allocate any new memory and instead destructively modifies the two input tries to combine them together into a single trie. 36. Write a function that, given a pattern string consisting of a series of letters intermixed with question marks (for example, a string like do?ble) and a pointer to the root of a trie, returns all words in the trie that match the pattern, where a question mark matches any single character. If given the pattern do?ble, for example, and a trie of all words in English, your code should return doable and double. Given the pattern??, it would return a list of all two letter words in English. 37. A Patricia trie (sometimes called a radix trie) is a variation on a trie. We'll say that a trie node is a silly node if it doesn't represent a word and has exactly one child. A Patri cia trie is a trie formed by removing all the silly nodes from a trie and allowing edges to be labeled with arbitrary strings, not just individual characters. Write a function that, given a trie, converts it to a Patricia trie, and a reverse function that converts a Patricia trie to a regular trie.

6 / 7 General Recursion 38. A rotated array is an array formed by taking a sorted array, splitting it into two pieces, then interchanging the order of those pieces. For example, the array [6, 7, 9, 0, 1, 2, 3, 4] is a rotated array, as is [0, 1, 2, 3] (to see why it's rotated, split the array [0, 1, 2, 3] into the pieces [] and [0, 1, 2, 3], then interchange their order). Design an efficient algorithm that, given a rotated array and a key k, determines whether k is present in the array. 39. Suppose that you are interested in setting up a collection point to funnel rainwater into a town's water supply. The town is next to a ridge, which for simplicity we will assume is represented as a 1D array of the elevations of different points along the ridge. When rain falls on the ridge, it will roll downhill along the ridge. We'll call a point where water naturally accumulates (that is, a point lower than all neighboring points) a good collection point. For example, here is a possible ridge and its good collection points: 11 8 4 2 5 3 12 10 14 15 6 You are given an array of n elements representing the altitudes of points along the ridge, all of which are distinct. Design an efficient algorithm for finding a good collection point. 40. The Fibonacci strings are a series of recursively defined strings. F ₀ is the string a, F ₁ is the string bc, and F ₙ+₂ is the concatenation of F ₙ and F ₙ+₁. For example, F ₂ is abc, F ₃ is bcabc, F ₄ is abcbcabc, etc. Given a number n and an index k, return the kth character of the string F ₙ. Memoization and Dynamic Programming 41. Write a function that uses memoization to compute the nth Fibonacci number without recomputing any intermediate values. 42. You are given a pyramid of numbers like the one shown here: 137 42 15 4 13 45 21 14 92 33 Values in the pyramid can be both positive or negative. A path from the top of the pyramid to the bottom consists of starting at the top of the pyramid and taking steps diagonally left or diagonally right down to the bottom of the pyramid. The cost of a path is the sum of all the values in the pyramid. Find the path from the top of the pyramid to the bottom with the lowest total cost. Use memoization or dynamic programming to dramatically speed up your solution over a naïve recursive algorithm.

7 / 7 43. Let's consider a pattern matching problem. You're given as input two strings, a text string and a pattern string. The text string consists purely of lower case letters. The pattern string contains lower case letters (which only match the given character), plus the? character (which means match anything ) and the * character (which means match zero or more characters. ) For example, the word apple matches the patterns apple, ap?le, a*e, and *, but not the patterns a?, *p, or apple?. Write a function that takes in a text and a pattern and determines whether the text matches the pattern. Use memoization or dynamic programming to dramatically speed up your solution over a naïve recursive algorithm. 44. Imagine you have a strip of highway connecting n towns in a line. Each town is being evaluated as a possible location for building a cellular phone tower. Each cell tower will provide coverage to the town it's built in, but no other towns. However, due to the way that cell towers interfere with one another, it's not possible to build cell phone towers in two adjacent cities. Design an algorithm that, given the populations of each of the towns, reports the maximum number of people you can provide cell phone coverage to, subject to the restriction that no two adjacent towns can each have cell towers in them. Use memoization or dynamic programming to dramatically speed up your solution over a naïve recursive algorithm.