The Algorithm Design Manual Problem 4-4

Assume that we are given n pairs of items as input, where the first item is a
number and the second item is one of three colors (red, blue, or yellow). Further
assume that the items are sorted by number. Give an O(n) algorithm to sort the
items by color (all reds before all blues before all yellows) such that the numbers
for identical colors stay sorted.
For example: (1,blue), (3,red), (4,blue), (6,yellow), (9,red) should become (3,red),
(9,red), (1,blue), (4,blue), (6,yellow)
.

package avdongre.tadm;

import java.util.ArrayList;
import java.util.List;

public class ColorSort {
	private enum Color {
		RED, BLUE, YELLOW
	}

	private class Pair {
		public int first;
		public Color second;

		public Pair(int x, Color y) {
			first = x;
			second = y;
		}

		@Override
		public String toString() {
			return String.format(first + "," + second);
		}
	}

	public List<Pair> colorSortRedBlueYello(List<Pair> input) {
		if (input == null) {
			return null;
		}
		// This is special case or similar to Dutch national flag problem.
		int left = 0;
		int mid = 0;
		int right = input.size() - 1;

		while (mid <= right) {
			switch (input.get(mid).second) {
			case RED: {
				Pair temp = input.get(left);
				input.set(left, input.get(mid));
				input.set(mid, temp);
				left++;
				mid++;
				break;
			}
			case BLUE:
				mid++;
				break;
			case YELLOW: {
				Pair temp = input.get(mid);
				input.set(mid, input.get(right));
				input.set(right, temp);
				right--;

				break;
			}
			}
		}
		return input;
	}

	private List<Pair> generateInput() {
		List<Pair> lp = new ArrayList<Pair>();

		lp.add(new Pair(1, Color.BLUE));
		lp.add(new Pair(3, Color.RED));
		lp.add(new Pair(4, Color.BLUE));
		lp.add(new Pair(6, Color.YELLOW));
		lp.add(new Pair(9, Color.RED));

		return lp;
	}

	public static void main(String args[]) {
		ColorSort cs = new ColorSort();
		List<Pair> input = cs.generateInput();
		cs.colorSortRedBlueYello(input);
		System.out.println(input);
		
	}
}

The Algorithm Design Manual Problem 4-3

Take a sequence of 2n real numbers as input. Design an O(n log n) algorithm that
partitions the numbers into n pairs, with the property that the partition minimizes
the maximum sum of a pair. For example, say we are given the numbers (1,3,5,9).
The possible partitions are ((1,3),(5,9)), ((1,5),(3,9)), and ((1,9),(3,5)). The pair
sums for these partitions are (4,14), (6,12), and (10,8). Thus the third partition has
10 as its maximum sum, which is the minimum over the three partitions.

Solution for this problem is first sort the input and choose x[0], x[length-1]), ( x[1], x[length-2])......

THE ALGORITHM DESIGN MANUAL PROBLEM 4-2

For each of the following problems, give an algorithm that finds the desired
numbers within the given amount of time. To keep your answers brief, feel free to
use algorithms from the book as subroutines. For the example, S = {6, 13, 19, 3, 8},
19 − 3 maximizes the difference, while 8 − 6 minimizes the difference.
(a) Let S be an unsorted array of n integers. Give an algorithm that finds the pair
x, y ∈ S that maximizes |x − y|. Your algorithm must run in O(n) worst-case time.
(b) Let S be a sorted array of n integers. Give an algorithm that finds the pair
x, y ∈ S that maximizes |x − y|. Your algorithm must run in O(1) worst-case time.
(c) Let S be an unsorted array of n integers. Give an algorithm that finds the pair
x, y ∈ S that minimizes |x − y|, for x = y. Your algorithm must run in O(n log n)
worst-case time.
(d) Let S be a sorted array of n integers. Give an algorithm that finds the pair
x, y ∈ S that minimizes |x − y|, for x = y. Your algorithm must run in O(n)
worst-case time.

package avdongre.adm;

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

/**
 * For each of the following problems, give an algorithm that finds the desired
 * numbers within the given amount of time. To keep your answers brief, feel
 * free to use algorithms from the book as subroutines. For the example, 
 * S = {6, 13, 19, 3, 8}, 19 − 3 maximizes the difference, while 8 − 6 minimizes the
 * difference.
 * 
 * (a) Let S be an unsorted array of n integers. Give an algorithm that finds
 * the pair x, y ∈ S that maximizes |x − y|. Your algorithm must run in O(n)
 * worst-case time.
 * 
 * (b) Let S be a sorted array of n integers. Give an algorithm that finds the
 * pair x, y ∈ S that maximizes |x − y|. Your algorithm must run in O(1)
 * worst-case time.
 * 
 * (c) Let S be an unsorted array of n integers. Give an algorithm that finds
 * the pair x, y ∈ S that minimizes |x − y|, for x = y. Your algorithm must run
 * in O(n log n) worst-case time.
 * 
 * (d) Let S be a sorted array of n integers. Give an algorithm that finds the
 * pair x, y ∈ S that minimizes |x − y|, for x = y. Your algorithm must run in
 * O(n) worst-case time.
 * 
 * @author adongre
 *
 */
public class MaxMinVariations {
	private class Pair {
		public int first;
		public int second;
		public Pair(int x, int y ) {
			first = x;
			second = y;
		}
		@Override
	    public String toString() {
	        return String.format(first + "," + second);
	    }
	}
	private int [] generateInputArray(int size) {
		ArrayList<Integer> list = new ArrayList<Integer>();
		for (int i = 1; i < size; i++) {
			list.add(new Integer(i));
		}
		Collections.shuffle(list);
		int[] result = new int [ list.size()];
		for (int i = 0; i < list.size(); i++) {
			result[i] = list.get(i).intValue();
		}		
		return result;
	}
	public Pair getMaxPairFromUnsortedArray(int [] input) {
		if ( input == null) {
			return null;
		}
		int largest = Integer.MIN_VALUE;
        int smallest = Integer.MAX_VALUE;
		for ( int i = 0; i < input.length; i++) {
			if (input[i] > largest) {
                largest = input[i];
            } else if (input[i] < smallest) {
                smallest = input[i];
            }
		}
		Pair p = new Pair(smallest, largest);
		return p;		
	}
	public Pair getMaxPairFromSortedArray(int [] input) {
		if ( input == null) {
			return null;
		}
		Arrays.sort(input);
		Pair p = new Pair(input[0], input[input.length - 1]);
		return p;		
	}
	
	public Pair getMinPairFromUnsortedArray(int [] input) {
		if ( input == null) {
			return null;
		}
		if ( input.length < 2) {
			return null;	
		}
		Arrays.sort(input);
		int smallest = 0;
		int largest = 0;
		int currentMinimum =  Integer.MAX_VALUE;
		for ( int i = 1; i < input.length; i++) {
			if ( currentMinimum > (input[i] - input[i-1])) {
				currentMinimum = input[i] - input[i-1];
				smallest = input[i -1];
				largest = input[i];
			}
		}
		Pair p = new Pair(smallest, largest);
		return p;		
	}
	public Pair getMinPairFromSortedArray(int [] input) {
		if ( input == null) {
			return null;
		}
		if ( input.length < 2) {
			return null;	
		}
		Arrays.sort(input);
		int smallest = 0;
		int largest = 0;
		//Pair p = new Pair(input[0], input[1]);
		int currentMinimum =  Integer.MAX_VALUE;
		for ( int i = 1; i < input.length; i++) {
			if ( currentMinimum > (input[i] - input[i-1])) {
				currentMinimum = input[i] - input[i-1];
				smallest = input[i -1];
				largest = input[i];
			}
		}		
		Pair p = new Pair(smallest, largest);
		return p;
	}
	
	
	public static void main(String[] args) {
		MaxMinVariations mm = new MaxMinVariations();
		{
			int [] inputArray = mm.generateInputArray(10);
			System.out.println(Arrays.toString(inputArray));
			System.out.println(mm.getMaxPairFromUnsortedArray(inputArray));
		}
		{
			int [] inputArray = mm.generateInputArray(10);
			System.out.println(Arrays.toString(inputArray));
			System.out.println(mm.getMaxPairFromSortedArray(inputArray));
		}
		{
			int [] inputArray = mm.generateInputArray(10);
			System.out.println(Arrays.toString(inputArray));
			System.out.println(mm.getMinPairFromUnsortedArray(inputArray));
		}		
		{
			int [] inputArray = mm.generateInputArray(10);
			System.out.println(Arrays.toString(inputArray));
			System.out.println(mm.getMinPairFromSortedArray(inputArray));
		}	
		{
			int [] inputArray = new int[] {5,10,11,12};
			System.out.println(Arrays.toString(inputArray));
			System.out.println(mm.getMinPairFromSortedArray(inputArray));
		}	
	}

}

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));

	}

}

[LeetCode #171] Excel Sheet Column Number

Excel Sheet Column Number

Given a column title as appear in an Excel sheet, return its corresponding column number.

For example:

    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28 
public class Solution {
    public int titleToNumber(String s) {
        
        int result = 0;
        for (int i = 0; i < s.length(); i++) {
            result = result * 26 + (s.charAt(i) - 'A' + 1);
        }
        return result;

	
    }
}

[LeetCode #169] Majority Element

Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

public class Solution {
    public int majorityElement(int[] num) {
        
	    int count = 0, i, result = 0;
	    for (i = 0; i &amp;amp;lt; num.length; i++) {
	        if (count == 0)
	            result = num[i];
	        if (num[i] == result) 
	            count++;
	        else
	            count--;
	    }
	    count = 0;
	    for (i = 0; i &amp;amp;lt; num.length; i++)
	        if (num[i] == result)
	            count++;
	    if (count &amp;amp;gt; num.length/2)
	        return result;
	    
		return result;
	
    }
}

[LeetCode #168] Excel Sheet Column Title

Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 
public class Solution {
    public String convertToTitle(int n) {
        
		// http://en.wikipedia.org/wiki/Bijective_numeration#The_bijective_base-26_system
		if (n &amp;amp;lt; 27) {
			return (char) ('A' + (n - 1)) + &amp;amp;quot;&amp;amp;quot;;
		}

		if (n % 26 == 0) {
			return convertToTitle(n / 26 - 1) + 'Z';
		}

		return convertToTitle(n / 26) + convertToTitle(n % 26);

	
    }
}

[LeetCode #145] Binary Tree Postorder Traversal

Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [3,2,1].

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    	public void postorderTraversal(TreeNode root, java.util.List&amp;amp;lt;Integer&amp;amp;gt;  result) {
		if ( root == null) {
			return;
		}		
		postorderTraversal( root.left , result);
		postorderTraversal( root.right, result); 

		result.add(root.val);
	}
	
	
	public java.util.List&amp;amp;lt;Integer&amp;amp;gt; postorderTraversal(TreeNode root) {		
		java.util.List&amp;amp;lt;Integer&amp;amp;gt; result = new java.util.ArrayList&amp;amp;lt;Integer&amp;amp;gt;();
		postorderTraversal(root, result);
		return result;

	}

}

[LeetCode #122] Best Time to Buy and Sell Stock II

Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

public class Solution {
    public int maxProfit(int[] prices) {
		
		int maxProfit = 0;
		if (prices.length == 0 ) {
			return maxProfit;
		}
		for (int i = 0; i &amp;lt; prices.length - 1; i++) {
			int signleProfit = prices[i + 1] - prices[i];
			if (signleProfit &amp;gt; 0) {
				maxProfit += signleProfit;
			}
		}
		
		return maxProfit;
	        
    }
}

[LeetCode #121] Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

public class Solution {
    public int maxProfit(int[] prices) {
		int maxProfit = 0;
		if (prices.length == 0 ) {
			return maxProfit;
		}		
		int buyPrice = prices[0];
		int sellPrice = 0;
		for ( int i = 1; i &amp;lt; prices.length; i++) {
			sellPrice = prices[i];
			if ( buyPrice &amp;lt; sellPrice) {
				maxProfit = java.lang.Math.max(maxProfit, sellPrice - buyPrice);
			} else {
				buyPrice = sellPrice;
			}
		}
		
		return maxProfit;
	        
    }
}