Lecture 4 - Problems

  1. A palindrome is a string that reads the same backwards as forwards. For example, civic, radar, deed, and racecar are all palindromes. The definition I just gave is a non-recursive one: the string is equal to its reverse. Come up with a recursive definition of a palindrome, and write pseudocode for the following method. You can use indexing and range indexing to refer to characters and substrings of s.

    /** return true iff s[start..end] is a palindrome
      * Pre: s is not null */
    public boolean isPal(s, start, end) {
     // TODO
    }
  2. Here’s the pseudocode for a factorial function:

    /** return n!; pre: n >= 0 */
    fact(n):
      if n == 0:
        return 1
      return n * fact(n - 1)

    What is the asymptotic runtime class of this function in terms of n?

  3. Recall the count_e method, which processed the string one character at a time (i.e., in an incremental fashion):

    /** returns # of e in string s. Pre: s is not null. */
    public int count_e(String s):
      if s.length() == 0:
        return 0;
      first = 0
      if s[0] == ‘e’:
        first = 1
    
      return first + count_e(s[1..end])

    Write a different version of this method that has the same spec, but solves the problem using the divide-and-conquer paradigm.

  4. The Node class below defines a singly-linked list node:

    public class Node {
      int value;
      Node next;
    }

    Write a recursive implementation of the following method:

    /** Reverse the order of the singly linked list with the given head node;
      return the head node of the new list. Pre: head is not null. */
    public static Node reverse(Node head) {
    
      // your code here
    
    }