The Algorithm Design Manual Problem 3-11

Suppose that we are given a sequence of n values x1, x2, …, xn and seek to
quickly answer repeated queries of the form: given i and j, find the smallest value
in xi, . . . , xj .
(a) Design a data structure that uses O(n2) space and answers queries in O(1)
time.
(b) Design a data structure that uses O(n) space and answers queries in O(log n)
time. For partial credit, your data structure can use O(n log n) space and have
O(log n) query time.

Following is my solution for (b)

package avdongre.skiena;

import java.util.ArrayList;
import java.util.Collections;

/**
 * Suppose that we are given a sequence of n values x1 , x2 , ..., xn and seek
 * to quickly answer repeated queries of the form: given i and j, find the
 * smallest value in xi , . . . , xj .
 * 
 * @author adongre
 *
 */

public class RangeQuerySearch {

	/**
	 * Design a data structure that uses O(n2 ) space and answers queries in
	 * O(1) time.
	 */
	int findSmallestValue1(int input[], int left, int right) {
		if (left < 0 || right > input.length) {
			return -1;
		}
		return 0;
	}

	/**
	 * Design a data structure that uses O(n) space and answers queries in O(log
	 * * n) time.
	 * 
	 * @param args
	 */

	private static TreeNode put(TreeNode x, int val) {
		if (x == null)
			return new TreeNode(val);
		
		if (val < x.val)
			x.left = put(x.left, val);
		else
			x.right = put(x.right, val);
		
		return x;
	}

	private static int findSmallestValue2(Object input[], int i, int j) {
		if (i < 0 || j > input.length) {
			return -1;
		}
		// Construct a BST from left to right
		TreeNode root = new TreeNode((int) input[0]);
		for (int k = i + 1; k <j; k++) {
			put(root, (int)input[k]);
		}
		// Find minimum which will be leftmost element int he tree
		TreeNode x = root;
		while (x.left != null) {
			x = x.left;
		}
		return x.val;
	}

	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<Integer>();
		for (int i = 1; i < 10; i++) {
			list.add(new Integer(i));
		}
		Collections.shuffle(list);
		System.out.println(list);
		System.out.println(findSmallestValue2(list.toArray(), 0, 6));

	}

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s