10/16/2012

Merge Two Sorted Lists

Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Time complexity: O(m+n)
  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) {
  7. * val = x;
  8. * next = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  14. // Start typing your Java solution below
  15. // DO NOT write main() function
  16. ListNode root = null;
  17. ListNode node = null;
  18. while (l1 != null && l2 != null) {
  19. if (l1.val < l2.val) {
  20. if (node == null) {
  21. node = l1;
  22. root = node;
  23. }
  24. else {
  25. node.next = l1;
  26. node = node.next;
  27. }
  28. l1 = l1.next;
  29. }
  30. else {
  31. if (node == null) {
  32. node = l2;
  33. root = node;
  34. }
  35. else {
  36. node.next = l2;
  37. node = node.next;
  38. }
  39. l2 = l2.next;
  40. }
  41. }
  42. while (l1 != null) {
  43. if (node == null) {
  44. node = l1;
  45. root = node;
  46. }
  47. else {
  48. node.next = l1;
  49. node = node.next;
  50. }
  51. l1 = l1.next;
  52. }
  53. while (l2 != null) {
  54. if (node == null) {
  55. node = l2;
  56. root = node;
  57. }
  58. else {
  59. node.next = l2;
  60. node = node.next;
  61. }
  62. l2 = l2.next;
  63. }
  64. return root;
  65. }
  66. }

Merge Sorted Array


Merge Sorted Array
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

Idea: Simply do it in reverse order
  1. class Solution {
  2. public:
  3. void merge(int A[], int m, int B[], int n) {
  4. // Start typing your C/C++ solution below
  5. // DO NOT write int main() function
  6. int i = m - 1, j = n - 1, k = m + n - 1;
  7. while (i >= 0 && j >= 0) {
  8. if (A[i] < B[j]) {
  9. A[k] = B[j];
  10. --j;
  11. }
  12. else {
  13. A[k] = A[i];
  14. --i;
  15. }
  16. --k;
  17. }
  18. while (j >= 0) {
  19. // copy the rest of B into A
  20. A[k] = B[j];
  21. --k;
  22. --j;
  23. }
  24. }
  25. };

Merge k Sorted Lists


Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Note: Merge sort was used.
Time complexity: O(nlgk).
  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) {
  7. * val = x;
  8. * next = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. public ListNode mergeKLists(ArrayList<listnode> lists) {
  14. // Start typing your Java solution below
  15. // DO NOT write main() function
  16. if (lists.size() == 0) return null;
  17. ArrayList<listnode> klist = new ArrayList<listnode>();
  18. for (int i = 0; i &lt; lists.size(); i++) {
  19. ListNode node = lists.get(i);
  20. if (node != null) {
  21. klist.add(node);
  22. }
  23. }
  24. Collections.sort(klist, new Comparator<listnode>() {
  25. public int compare(ListNode n1, ListNode n2) {
  26. return n1.val - n2.val;
  27. }
  28. });
  29. ListNode root = null;
  30. ListNode node = null;
  31. while (!klist.isEmpty()) {
  32. if (root == null) {
  33. root = klist.get(0);
  34. node = root;
  35. }
  36. else {
  37. node.next = klist.get(0);
  38. node = node.next;
  39. }
  40. klist.set(0, klist.get(0).next);
  41. if (klist.get(0) == null) {
  42. klist.remove(0);
  43. }
  44. if (klist.isEmpty()) {
  45. break;
  46. }
  47. Collections.sort(klist, new Comparator<listnode>() {
  48. public int compare(ListNode n1, ListNode n2) {
  49. return n1.val - n2.val;
  50. }
  51. });
  52. }
  53. return root;
  54. }
  55. }
  56.  

10/13/2012

Search for a Range


Search for a Range
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
Key: Binary search

  1. public class Solution {
  2. public int[] searchRange(int[] A, int target) {
  3. // Start typing your Java solution below
  4. // DO NOT write main() function
  5. int left = getLeft(A, target);
  6. int right = getRight(A, target);
  7. return new int[]{left, right};
  8. }
  9. public int getLeft(int[] A, int target) {
  10. int start = 0;
  11. int end = A.length - 1;
  12. while (end >= start) {
  13. if (end == start) {
  14. if (A[start] == target)
  15. return start;
  16. else
  17. return -1;
  18. }
  19. int mid = (start + end) / 2;
  20. if (A[mid] > target) {
  21. end = mid - 1;
  22. }
  23. else if (A[mid] < target) {
  24. start = mid + 1;
  25. }
  26. else {
  27. end = mid;
  28. }
  29. }
  30. return -1;
  31. }
  32. public int getRight(int[] A, int target) {
  33. int start = 0;
  34. int end = A.length - 1;
  35. while (end >= start) {
  36. if (end == start) {
  37. if (A[start] == target)
  38. return start;
  39. else
  40. return -1;
  41. }
  42. int mid = (start + end) / 2;
  43. if (A[mid] > target) {
  44. end = mid - 1;
  45. }
  46. else if (A[mid] < target) {
  47. start = mid + 1;
  48. }
  49. else {
  50. if (end - start == 1) {
  51. if (A[end] == target) {
  52. return end;
  53. }
  54. else {
  55. return start;
  56. }
  57. }
  58. start = mid;
  59. }
  60. }
  61. return -1;
  62. }
  63. }

Search a 2D Matrix


Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
Given target = 3, return true.

Key: Binary search (There may be better code than mine in locating row number. The edge condition is when only two rows left. Incorrect treatment may lead to incorrect answer or infinite loop.)


  1. public class Solution {
  2. public boolean searchMatrix(int[][] matrix, int target) {
  3. // Start typing your Java solution below
  4. // DO NOT write main() function
  5. //locate row
  6. int rs = 0;
  7. int re = matrix.length - 1;
  8. while (re - rs > 1) {
  9. int rm = (rs + re) / 2;
  10. if (matrix[rm][0] > target) {
  11. re = rm;
  12. }
  13. else if (matrix[rm][0] < target) {
  14. rs = rm;
  15. }
  16. else {
  17. return true;
  18. }
  19. }
  20. int row = 0;
  21. if (matrix[rs][0] > target) {
  22. return false;
  23. }
  24. if (matrix[re][0] <= target) {
  25. row = re;
  26. }
  27. else {
  28. row = rs;
  29. }
  30. int start = 0;
  31. int end = matrix[row].length - 1;
  32. if (matrix[row][start] == target || matrix[row][end] == target) {
  33. return true;
  34. }
  35. else if (matrix[row][end] < target) {
  36. return false;
  37. }
  38. else {
  39. //might be in this row
  40. while (start < end) {
  41. if (matrix[row][start] == target || matrix[row][end] == target) {
  42. return true;
  43. }
  44. int mid = (start + end) / 2;
  45. if (matrix[row][mid] > target) {
  46. end = mid - 1;
  47. }
  48. else if (matrix[row][mid] < target) {
  49. start = mid + 1;
  50. }
  51. else {
  52. return true;
  53. }
  54. }
  55. return false;
  56. }
  57. }
  58. }

Longest Valid Parentheses

Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
  1. public class Solution {
  2. public int longestValidParentheses(String s) {
  3. int n = s.countgth();
  4. int maxCount = 0;
  5. int lb = 0;
  6. int count = 0;
  7. for(int i = 0; i < n; i++){
  8. if(s.charAt(i) == '('){
  9. lb++;
  10. count++;
  11. }
  12. if(s.charAt(i) == ')') {
  13. lb--;
  14. count++;
  15. }
  16. if(lb == 0 && count > maxCount) {
  17. maxCount = count;
  18. }
  19. else if(lb < 0){
  20. //invalid
  21. lb = 0;
  22. count = 0;
  23. }
  24. }
  25. int rb = 0;
  26. count = 0;
  27. for(int i = n-1; i >= 0; i--) {
  28. if(s.charAt(i) == ')'){
  29. rb++;
  30. count++;
  31. }
  32. if(s.charAt(i) == '(') {
  33. rb--;
  34. count++;
  35. }
  36. if(lb == 0 && count > maxCount) {
  37. maxCount = count;
  38. }
  39. else if(lb < 0){
  40. //invalid
  41. rb = 0;
  42. count = 0;
  43. }
  44. }
  45. return maxCount;
  46. }
  47. }

10/07/2012

Jump Game II

Jump Game II
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
 
Strategy: Greedy (reversed order)

Complexity: O(n^2)

  1. public class Solution {
  2. public int jump(int[] A) {
  3. // Start typing your Java solution below
  4. // DO NOT write main() function
  5. if (A.length == 1) return 0;
  6. int lastIndex = A.length - 1;
  7. int steps = 0;
  8. while (lastIndex > 0) {
  9. int preIndexMin = lastIndex;
  10. for (int i=lastIndex - 1; i>=0; i--) {
  11. if (A[i] >= lastIndex - i) {
  12. if (preIndexMin > i) {
  13. preIndexMin = i;
  14. }
  15. }
  16. }
  17. if (lastIndex == preIndexMin) return -1;
  18. lastIndex = preIndexMin;
  19. steps++;
  20. }
  21. return steps;
  22. }
  23. }

Jump Game

Jump Game
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
Strategy: For each '0' in the array, find if it could be jumped over from its previous indexes, or if we can directly jump to the end.

Complexity: O(n^2)?

  1. public class Solution {
  2. public boolean canJump(int[] A) {
  3. // Start typing your Java solution below
  4. // DO NOT write main() function
  5. int end = A.length - 1;
  6. for (int i=0; i<A.length; i++) {
  7. if (A.length != 1 && A[i] == 0 && i != end) {
  8. int nextNonZeroIndex = i+1;
  9. while (nextNonZeroIndex < end) {
  10. if (A[nextNonZeroIndex] > 0) {
  11. break;
  12. }
  13. else {
  14. nextNonZeroIndex++;
  15. }
  16. } //max: end
  17. int j = i - 1;
  18. boolean continueSearch = false;
  19. while (j>=0) {
  20. if (A[j] >= end - j || A[j] >= nextNonZeroIndex - j) {
  21. continueSearch = true;
  22. break;
  23. }
  24. j--;
  25. }
  26. if (!continueSearch)
  27. return false;
  28. }
  29. }
  30. return true;
  31. }
  32. }

10/04/2012

Spiral Matrix


Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].

  1. public static ArrayList spiralOrder(int[][] matrix) {
  2. // Start typing your Java solution below
  3. // DO NOT write main() function
  4. ArrayList res = new ArrayList();
  5. if (matrix.length == 0) {
  6. return res;
  7. }
  8. int colStart = 0;
  9. int colEnd = matrix[0].length - 1;
  10. int rowStart = 0;
  11. int rowEnd = matrix.length - 1;
  12. while (colStart <= colEnd && rowStart <= rowEnd) {
  13. for (int i=colStart; i<=colEnd; i++) {
  14. res.add(matrix[rowStart][i]);
  15. }
  16. rowStart++;
  17. for (int i=rowStart; i<=rowEnd; i++) {
  18. res.add(matrix[i][colEnd]);
  19. }
  20. colEnd--;
  21. if (rowStart > rowEnd) break;
  22. for (int i=colEnd; i>=colStart; i--) {
  23. res.add(matrix[rowEnd][i]);
  24. }
  25. rowEnd--;
  26. if (colStart > colEnd) break;
  27. for (int i=rowEnd; i>=rowStart; i--) {
  28. res.add(matrix[i][colStart]);
  29. }
  30. colStart++;
  31. }
  32. return res;
  33. }


Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]



  1. public class Solution {
  2. public int[][] generateMatrix(int n) {
  3. // Start typing your Java solution below
  4. // DO NOT write main() function
  5. int[][] matrix = new int[n][n];
  6. int colStart = 0;
  7. int colEnd = n - 1;
  8. int rowStart = 0;
  9. int rowEnd = n - 1;
  10. int val = 1;
  11. while (colStart <= colEnd && rowStart <= rowEnd) {
  12. for (int i = colStart; i <= colEnd; i++) {
  13. matrix[rowStart][i] = val;
  14. val++;
  15. }
  16. rowStart++;
  17. for (int i = rowStart; i <= rowEnd; i++) {
  18. matrix[i][colEnd] = val;
  19. val++;
  20. }
  21. colEnd--;
  22. for (int i = colEnd; i >= colStart; i--) {
  23. matrix[rowEnd][i] = val;
  24. val++;
  25. }
  26. rowEnd--;
  27. for (int i = rowEnd; i >= rowStart; i--) {
  28. matrix[i][colStart] = val;
  29. val++;
  30. }
  31. colStart++;
  32. }
  33. return matrix;
  34. }
  35. }

10/03/2012

Permutations


Permutations
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].



  1. public class Solution {
  2.  
  3.     public ArrayList<ArrayList<Integer>> permute(int[] num) {
  4.  
  5.         // Start typing your Java solution below
  6.  
  7.         // DO NOT write main() function
  8.  
  9.         ArrayList<ArrayList<Integer>> permutations =
  10.  
  11.                new ArrayList<ArrayList<Integer>>();
  12.  
  13.         permutations.add(new ArrayList<Integer>());
  14.  
  15.         for (int i=0; i<num.length; i++) {
  16.  
  17.             int currentSize = permutations.size();
  18.  
  19.             for (int j=0; j<currentSize; j++) {
  20.  
  21.                 ArrayList<Integer> sub = permutations.get(0);
  22.  
  23.                 permutations.remove(sub);
  24.  
  25.                 for (int k=0; k<=sub.size(); k++) {
  26.  
  27.                     ArrayList<Integer> newSub = new ArrayList<Integer>(sub);
  28.  
  29.                     newSub.add(k,num[i]);
  30.  
  31.                     permutations.add(newSub);
  32.  
  33.                 }
  34.  
  35.             }
  36.  
  37.         }
  38.  
  39.         return permutations;
  40.  
  41.     }
  42.  
  43. }