Algorithm from EPI


From http://elementsofprogramminginterviews.com/solutions/
Compute all Valid IP Address
public static List<String> getValidIpAddress(String s) {
    List<String> result = new ArrayList<>();
    for (int i = 1; i < 4 && i < s.length(); ++i) {
      String first = s.substring(0, i);
      if (isValidPart(first)) {
        for (int j = 1; i + j < s.length() && j < 4; ++j) {
          String second = s.substring(i, i + j);
          if (isValidPart(second)) {
            for (int k = 1; i + j + k < s.length() && k < 4; ++k) {
              String third = s.substring(i + j, i + j + k), fourth = s
                  .substring(i + j + k);
              if (isValidPart(third) && isValidPart(fourth)) {
                result.add(first + "." + second + "." + third + "." + fourth);
              }
            }
          }
        }
      }
    }
    return result;
  }

  private static boolean isValidPart(String s) {
    if (s.length() > 3) {
      return false;
    }
    // "00", "000", "01", etc. are not valid, but "0" is valid.
    if (s.startsWith("0") && s.length() > 1) {
      return false;
    }
    int val = Integer.parseInt(s);
    return val <= 255 && val >= 0;
  }
Implement even-odd mergeEvenOddMergeLinkedListTemplate.java
  public static <T> Node<T> evenOddMerge(Node<T> L) {
    Node<T> odd = (L != null) ? L.next : null;
    Node<T> oddCurr = odd;
    Node<T> preEvenCurr = null, evenCurr = L;

    while (evenCurr != null && oddCurr != null) {
      evenCurr.next = oddCurr.next;
      preEvenCurr = evenCurr;
      evenCurr = evenCurr.next;
      if (evenCurr != null) {
        oddCurr.next = evenCurr.next;
        oddCurr = oddCurr.next;
      }
    }

    // Odd number of nodes.
    if (evenCurr != null) {
      preEvenCurr = evenCurr;
    }
    // Prevents empty list.
    if (preEvenCurr != null) {
      preEvenCurr.next = odd;
    }
    return L;
  }

Test whether a singly linked list is palindromic
PalindromeLinkedListTemplate.java
  public static <T> boolean isLinkedListAPalindrome(Node<T> L) {
    // Find the middle point of L if L is odd length,
    // and right-middle point if L is even length.
    Node<T> slow = L, fast = L;
    while (fast != null) {
      fast = fast.next;
      if (fast != null) {
        fast = fast.next;
        slow = slow.next;
      }
    }

    // Compare the first half and reversed second half lists.
    Node<T> reverse = ReverseLinkedListIterativeTemplate
        .reverseLinkedList(slow);
    while (reverse != null && L != null) {
      if (reverse.data != L.data) {
        return false;
      }
      reverse = reverse.next;
      L = L.next;
    }
    return true;
  }

Compute the median of a sorted circular linked list

MedianSortedCircularLinkedListTemplate.java
  public static double findMedianSortedCircularLinkedList(Node<Integer> rNode) {
    if (rNode == null) {
      // no node in this linked list.
      throw new IllegalArgumentException("empty list");
    }

    // Checks all nodes are identical or not and identify the start of list.
    Node<Integer> curr = rNode;
    Node<Integer> start = rNode;
    int count = 0;
    do {
      ++count;
      curr = curr.next;
      // start will point to the largest element in the list.
      if (start.data.compareTo(curr.data) <= 0) {
        start = curr;
      }
    } while (curr != rNode);
    // start's next is the begin of the list.
    start = start.next;

    // Traverses to the middle of the list and return the median.
    for (int i = 0; i < ((count - 1) >> 1); ++i) {
      start = start.next;
    }
    return (count & 1) != 0 ? start.data : 0.5 * (start.data + start.next.data);
  }

Implement list pivoting

ListPivoting.java
Split original list and maintain multiple lists, and concat them at last. Use dummy head node for each list.
public static NodeT<Integer> listPivoting(NodeT<Integer> L, int x) {
    NodeT<Integer> now = L;
    NodeT<Integer> lessHead = new NodeT<>(0, null);
    NodeT<Integer> equalHead = new NodeT<>(0, null);
    NodeT<Integer> largerHead = new NodeT<>(0, null);
    NodeT<Integer> lessTail = lessHead;
    NodeT<Integer> equalTail = equalHead;
    NodeT<Integer> largerTail = largerHead;
    while (now != null) {
      if (now.data < x) {
        lessTail.next = now;
        lessTail = now;
      } else if (now.data == x) {
        equalTail.next = now;
        equalTail = now;
      } else { // now->data > x.
        largerTail.next = now;
        largerTail = now;
      }
      now = now.next;
    }

    lessTail.next = equalTail.next = largerTail.next = null;
    if (largerHead.next != null) {
      equalTail.next = largerHead.next;
    }
    if (equalHead.next != null) {
      lessTail.next = equalHead.next;
    }
    return lessHead.next;
  }

Sort a list

InsertionSortList.java
Uses insertion sort on linked list.
  public static NodeT<Integer> insertionSort(final NodeT<Integer> L) {
    if (L == null) {
      return L;
    }

    NodeT<Integer> dummyHead = new NodeT<>(0, L);
    NodeT<Integer> now = L;
    while (now != null && now.next != null) {
      if (now.data > now.next.data) {
        NodeT<Integer> target = now.next;
        NodeT<Integer> pre = dummyHead;
        while (pre.next.data < target.data) {
          pre = pre.next;
        }
        NodeT<Integer> temp = pre.next;
        pre.next = target;
        now.next = target.next;
        target.next = temp;
      } else {
        now = now.next;
      }
    }
    return dummyHead.next;
  }
Add list-based integers
add-two-number-list.cc AddTwoNumberList.java
  public static NodeT<Integer> addTwoNumbers(NodeT<Integer> L1,
                                             NodeT<Integer> L2) {
    NodeT<Integer> dummyHead = new NodeT<>(0, null);
    NodeT<Integer> digit = dummyHead;
    int sum = 0;
    while (L1 != null || L2 != null) {
      if (L1 != null) {
        sum += L1.data;
        L1 = L1.next;
      }
      if (L2 != null) {
        sum += L2.data;
        L2 = L2.next;
      }
      digit.next = new NodeT<>(sum % 10, null);
      sum /= 10;
      digit = digit.next;
    }
    if (sum > 0) {
      digit.next = new NodeT<>(sum, null);
    }
    return dummyHead.next;
  }

Stack and Queue

Implement a stack with max API

StackWithMaxTemplate.java StackWithMaxImproved.java
  public static class Stack {
    private LinkedList<Integer> s = new LinkedList<>();
    private LinkedList<Pair<Integer, Integer>> aux = new LinkedList<>();

    public boolean empty() {
      return s.isEmpty();
    }

    public Integer max() {
      if (!empty()) {
        return aux.peek().getFirst();
      }
      throw new RuntimeException("empty_stack");
    }

    public Integer pop() {
      if (empty()) {
        throw new RuntimeException("empty_stack");
      }
      Integer ret = s.pop();
      if (ret.equals(aux.peek().getFirst())) {
        aux.peek().setSecond(aux.peek().getSecond() - 1);
        if (aux.peek().getSecond().equals(0)) {
          aux.pop();
        }
      }
      return ret;
    }

    public void push(Integer x) {
      s.push(x);
      if (!aux.isEmpty()) {
        if (x.compareTo(aux.peek().getFirst()) == 0) {
          aux.peek().setSecond(aux.peek().getSecond() + 1);
        } else if (x.compareTo(aux.peek().getFirst()) > 0) {
          aux.push(new Pair<>(x, 1));
        }
      } else {
        aux.push(new Pair<>(x, 1));
      }
    }
  }
  public static class Stack<T extends Comparable<T>> {
    private LinkedList<Pair<T, T>> s = new LinkedList<Pair<T, T>>();

    public boolean empty() {
      return s.isEmpty();
    }

    public T max() {
      if (!empty()) {
        return s.peek().getSecond();
      }
      throw new RuntimeException("empty stack");
    }

    public T pop() {
      if (empty()) {
        throw new RuntimeException("empty stack");
      }
      return s.pop().getFirst();
    }

    public void push(T x) {
      s.push(new Pair<T, T>(x, Collections.max(Arrays.asList(x, empty() ? x : s
          .peek().getSecond()))));
    }
  }
Evaluate RPN expressions RPN.java  public static int eval(String s) {
    LinkedList<Integer> evalStack = new LinkedList<>();
    String[] symbols = s.split(",");
    for (String symbol : symbols) {
      if (symbol.length() == 1 && "+-*/".contains(symbol)) {
        int y = evalStack.pop();
        int x = evalStack.pop();
        switch (symbol.charAt(0)) {
          case '+':
            evalStack.push(x + y);
            break;
          case '-':
            evalStack.push(x - y);
            break;
          case '*':
            evalStack.push(x * y);
            break;
          case '/':
            evalStack.push(x / y);
            break;
          default:
            throw new IllegalArgumentException("Malformed RPN at :" + symbol);
        }
      } else { // symbol is a number.
        evalStack.push(Integer.parseInt(symbol));
      }
    }
    return evalStack.pop();
  }

Test if parens, brackets, and braces are matched

valid-parentheses.cc ValidParentheses.java
  public static boolean isValidParentheses(String s) {
    LinkedList<Character> leftParens = new LinkedList<>();
    for (int i = 0; i < s.length(); ++i) {
      if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
        leftParens.push(s.charAt(i));
      } else {
        if (leftParens.isEmpty()) {
          return false; // No left paren.
        }
        if ((s.charAt(i) == ')' && leftParens.peek() != '(')
            || (s.charAt(i) == '}' && leftParens.peek() != '{')
            || (s.charAt(i) == ']' && leftParens.peek() != '[')) {
          return false; // Unmatched left paren.
        }
        leftParens.pop();
      }
    }
    return leftParens.isEmpty();
  }

Normalize pathnames NormalizedPathnames.java

public static String normalizedPathNames(String path) {
    LinkedList<String> s = new LinkedList<>(); // Use LinkedList as a stack.
    // Special case: starts with "/", which is an absolute path.
    if (path.startsWith("/")) {
      s.push("/");
    }

    for (String token : path.split("/")) {
      if (token.equals("..")) {
        if (s.isEmpty() || s.peek().equals("..")) {
          s.push(token);
        } else {
          if (s.peek().equals("/")) {
            throw new RuntimeException("Path error");
          }
          s.pop();
        }
      } else if (!token.equals(".") && !token.isEmpty()) { // Name.
        for (char c : token.toCharArray()) {
          if (c != '.' && !Character.isDigit(c) && !Character.isLetter(c)) {
            throw new RuntimeException("Invalid directory name");
          }
        }
        s.push(token);
      }
    }

    StringBuilder normalizedPath = new StringBuilder();
    if (!s.isEmpty()) {
      Iterator<String> it = s.descendingIterator();
      String prev = it.next();
      normalizedPath.append(prev);
      while (it.hasNext()) {
        if (!prev.equals("/")) {
          normalizedPath.append("/");
        }
        prev = it.next();
        normalizedPath.append(prev);
      }
    }
    return normalizedPath.toString();
  }

Print the keys in a BST BSTSortedOrderTemplate.java

  public static <T> void printBSTInSortedOrder(BinarySearchTree<T> n) {
    LinkedList<BinarySearchTree<T>> s = new LinkedList<BinarySearchTree<T>>();
    BinarySearchTree<T> curr = n;

    while (!s.isEmpty() || curr != null) {
      if (curr != null) {
        s.push(curr);
        curr = curr.getLeft();
      } else {
        curr = s.pop();
        System.out.println(curr.getData());
        curr = curr.getRight();
      }
    }
  }

Search a postings list SearchPostingsListRecursive.java  Iterative.java

public static void searchPostingsList(PostingListNode L) {
searchPostingsListHelper(L, 0);
}
private static int searchPostingsListHelper(PostingListNode L, int order) {
if (L != null && L.getOrder() == -1) {
L.setOrder(order++);
order = searchPostingsListHelper(L.getJump(), order);
order = searchPostingsListHelper(L.getNext(), order);
}
return order;
}

  public static void searchPostingsList(PostingListNode L) {
    LinkedList<PostingListNode> s = new LinkedList<>();
    int order = 0;
    s.push(L);
    while (!s.isEmpty()) {
      PostingListNode curr = s.pop();
      if (curr != null && curr.getOrder() == -1) {
        curr.setOrder(order++);
        s.push(curr.getNext());
        s.push(curr.getJump());
      }
    }
  }

Compute buildings with a sunset view ViewSunset.java

  public static LinkedList<Pair<Integer, Integer>>
  examineBuildingsWithSunset(InputStream sin) {
    int idx = 0; // Building's index.
    Integer height;
    // Stores (building_idx, building_height) pair with sunset views.
    LinkedList<Pair<Integer, Integer>> buildingsWithSunset = new LinkedList<>();
    try {
      ObjectInputStream osin = new ObjectInputStream(sin);
      while (true) {
        height = (Integer) osin.readObject();
        while (!buildingsWithSunset.isEmpty()
            && (height.
            compareTo(buildingsWithSunset.getLast().getSecond()) >= 0)) {
          buildingsWithSunset.removeLast();
        }
        buildingsWithSunset.addLast(new Pair<>(idx++, height));
      }
    } catch (ClassNotFoundException e) {
      System.out.println(e.getMessage());
    } catch (IOException e) {
      // Catching when there no more objects in InputStream
    }
    return buildingsWithSunset;
  }

Sort a stack StackSorting.java

  public static void sort(LinkedList<Integer> S) {
    if (!S.isEmpty()) {
      Integer e = S.pop();
      sort(S);
      insert(S, e);
    }
  }

  private static void insert(LinkedList<Integer> S, Integer e) {
    if (S.isEmpty() || S.peek().compareTo(e) <= 0) {
      S.push(e);
    } else {
      Integer f = S.pop();
      insert(S, e);
      S.push(f);
    }
  }

Print a binary tree in order of increasing depth BinaryTreeLevelOrderTemplate.java

  public static <T> void printBinaryTreeLevelOrder(BinarySearchTree<T> n) {
    // Prevent empty tree
    if (n == null) {
      return;
    }

    LinkedList<BinarySearchTree<T>> q = new LinkedList<BinarySearchTree<T>>();
    q.push(n);
    int count = q.size();
    while (!q.isEmpty()) {
      BinarySearchTree<T> front = q.pollLast();
      System.out.print(front.getData() + " ");
      if (front.getLeft() != null) {
        q.push(front.getLeft());
      }
      if (front.getRight() != null) {
        q.push(front.getRight());
      }
      if (--count == 0) {
        System.out.println();
        count = q.size();
      }
    }
  }

Implement a circular queue CircularQueueTemplate.java


Implement a queue API using two stacks  QueueFromStacksTemplate.java

  public static class Queue<T> {
    private LinkedList<T> a = new LinkedList<T>();
    private LinkedList<T> b = new LinkedList<T>();

    public void enqueue(T x) {
      a.push(x);
    }

    public T dequeue() {
      if (b.isEmpty()) {
        while (!a.isEmpty()) {
          b.push(a.pop());
        }
      }
      if (!b.isEmpty()) {
        return b.pop();
      }
      throw new RuntimeException("empty queue");
    }
  }

Test if a binary tree is balanced BalancedBinaryTreeTemplate.java

  private static <T> int getHeight(BinaryTree<T> n) {
    if (n == null) {
      return -1;
    }

    int lHeight = getHeight(n.getLeft());
    if (lHeight == -2) {
      return -2; // left subtree is not balanced.
    }

    int rHeight = getHeight(n.getRight());
    if (rHeight == -2) {
      return -2; // right subtree is not balanced.
    }

    if (Math.abs(lHeight - rHeight) > 1) {
      return -2; // current node n is not balanced.
    }
    return Math.max(lHeight, rHeight) + 1;
  }

  public static <T> boolean isBalancedBinaryTree(BinaryTree<T> n) {
    return getHeight(n) != -2;
  }

Sum the leaves in a binary tree encoding integers SumRootToLeafBinaryTree.java

  public static int sumRootToLeaf(BinaryTree<Integer> root) {
    return preOrderTraversal(root, 0);
  }

  private static int preOrderTraversal(BinaryTree<Integer> root, int num) {
    if (root == null) {
      return 0;
    }

    num = (num * 2) + root.getData();
    if (root.getLeft() == null && root.getRight() == null) { // Leaf.
      return num;
    }
    // Non-leaf.
    return preOrderTraversal(root.getLeft(), num)
           + preOrderTraversal(root.getRight(), num);
  }

Find a root to leaf path with specified sum  PathSumBinaryTree.java

  public static boolean hasPathSum(BinaryTree<Integer> root, int sum) {
    return hasPathSumHelper(root, 0, sum);
  }

  private static boolean hasPathSumHelper(BinaryTree<Integer> root,
                                          int pathsum, int sum) {
    if (root != null) {
      pathsum += root.getData();
      if (root.getLeft() == null && root.getRight() == null) { // Leaf.
        return pathsum == sum;
      }
      // Non-leaf.
      return hasPathSumHelper(root.getLeft(), pathsum, sum)
             || hasPathSumHelper(root.getRight(), pathsum, sum);
    }
    return false;
  }

Compute the k-th node in an inorder traversal KThNodeBinaryTree.java

  public static class BinaryTreeNode<T> {
    public T data;
    public BinaryTreeNode<T> left, right;
    public int size;
  }

  // @include
  public static BinaryTreeNode<Integer> findKthNodeBinaryTree(
      BinaryTreeNode<Integer> root, int k) {
    BinaryTreeNode<Integer> n = root;
    while (n != null) {
      int leftSize = n.left != null ? n.left.size : 0;
      if (leftSize < k - 1) {
        k -= (leftSize + 1);
        n = n.right;
      } else if (leftSize == k - 1) {
        return n;
      } else { // leftSize > k - 1.
        n = n.left;
      }
    }
    throw new RuntimeException("no k-th node in binary tree");
  }

Compute the successor Successor.java

  public static BinaryTree<Integer> findSuccessor(BinaryTree<Integer> node) {
    BinaryTree<Integer> n = node;
    if (n.getRight() != null) {
      // Find the leftmost element in n's right subtree.
      n = n.getRight();
      while (n.getLeft() != null) {
        n = n.getLeft();
      }
      return n;
    }

    // Find the first parent whose left child contains n.
    while (n.getParent() != null && n.getParent().getRight() == n) {
      n = n.getParent();
    }
    // Return nullptr means n does not have successor.
    return n.getParent();
  }

Form a linked list from the leaves of a binary treeConnectLeavesBinaryTreeTemplate.java

  private static <T> void connectLeavesHelper(BinaryTree<T> n,
      ArrayList<BinaryTree<T>> L) {
    if (n != null) {
      if (n.getLeft() == null && n.getRight() == null) {
        L.add(n);
      } else {
        connectLeavesHelper(n.getLeft(), L);
        connectLeavesHelper(n.getRight(), L);
      }
    }
  }

  public static <T> ArrayList<BinaryTree<T>> connectLeaves(BinaryTree<T> n) {
    ArrayList<BinaryTree<T>> L = new ArrayList<BinaryTree<T>>();
    connectLeavesHelper(n, L);
    return L;
  }

Sort an almost-sorted array ApproximateSort.java

  public static void approximateSort(InputStream sin, int k) {
    PriorityQueue<Integer> minHeap = new PriorityQueue<>();
    try {
      ObjectInputStream osin = new ObjectInputStream(sin);
      // Firstly pushes k elements into minHeap.
      for (int i = 0; i < k; ++i) {
        minHeap.add((Integer) osin.readObject());
      }

      // Extracts the minimum one for every incoming element.
      while (true) {
        minHeap.add((Integer) osin.readObject());
        System.out.println(minHeap.remove());
      }
    } catch (IOException e) {
      // Do nothing, was read last element in stream
    } catch (ClassNotFoundException e) {
      System.out.println("ClassNotFoundException: " + e.getMessage());
    }
    // Extracts the remaining elements in minHeap.
    while (!minHeap.isEmpty()) {
      System.out.println(minHeap.remove());
    }
  }

Compute the k closest stars ClosestStars.java

  public static List<Star> findClosestKStars(InputStream sin, int k) {
    // Use maxHeap to find the closest k stars.
    PriorityQueue<Star> maxHeap = new PriorityQueue<>();
    try {
      ObjectInputStream osin = new ObjectInputStream(sin);

      // Record the first k stars.
      while (true) {
        Star s = (Star) osin.readObject();

        if (maxHeap.size() == k) {
          // Compare the top of heap with the incoming star.
          Star farStar = maxHeap.peek();
          // compareTo() method compares the Euclidean distances
          // of s and farStar to the origin (Earth).
          if (s.compareTo(farStar) < 0) {
            maxHeap.remove();
            maxHeap.add(s);
          }
        } else {
          maxHeap.add(s);
        }
      }
    } catch (IOException e) {
      // Do nothing, was read last element in stream.
    } catch (ClassNotFoundException e) {
      System.out.println("ClassNotFoundException: " + e.getMessage());
    }

    // Store the closest k stars.
    List<Star> closestStars = new ArrayList<>();
    while (!maxHeap.isEmpty()) {
      closestStars.add(maxHeap.remove());
    }
    return closestStars;
  }

Find k elements closest to the median ClosestToMedian.java

private static void nthElement(List<Integer> A, int n, Comparator<Integer> c) {
    Collections.sort(A, c);
  }

  private static void nthElement(List<Integer> A, int n) {
    nthElement(A, n, new Comparator<Integer>() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
      }
    });
  }

  // @include
  public static List<Integer> findKClosestToMedian(List<Integer> a, int k) {
    // Find the element i where |a[i] - median| is k-th smallest.
    final double m = findMedian(a);
    nthElement(a, k - 1, new Comparator<Integer>() {
      @Override
      public int compare(Integer a, Integer b) {
        return Double.valueOf(Math.abs(a - m)).compareTo(Math.abs(b - m));
      }
    });
    return new ArrayList<>(a.subList(0, k));
  }

  private static class Data {
    public int larger;
    public int equal;
  }

Test if x is bigger than the k-th largest element CompareKthLargestInHeap.java

  // -1 means smaller, 0 means equal, and 1 means larger.
  public static int compareKthLargestHeap(List<Integer> maxHeap, int k, int x) {
    Data data = new Data();
    data.larger = 0;
    data.equal = 0;
    compareKthLargestHeapHelper(maxHeap, k, x, 0, data);
    return data.larger >= k ? 1 : (data.larger + data.equal >= k ? 0 : -1);
  }

  private static void compareKthLargestHeapHelper(List<Integer> maxHeap, int k,
                                                  int x, int idx, Data data) {
    if (data.larger >= k || idx >= maxHeap.size() || maxHeap.get(idx) < x) {
      return;
    } else if (maxHeap.get(idx) == x) {
      if (++data.equal >= k) {
        return;
      }
    } else { // max_heap[idx] > x.
      ++data.larger;
    }
    compareKthLargestHeapHelper(maxHeap, k, x, (idx * 2) + 1, data);
    compareKthLargestHeapHelper(maxHeap, k, x, (idx * 2) + 2, data);
  }

Find the min and max simultaneously FindingMinMax.java

  public static Pair<Integer, Integer> findMinMax(ArrayList<Integer> A) {
    if (A.size() <= 1) {
      return new Pair<>(A.get(0), A.get(0));
    }

    // Initializes the min and max pair.
    Pair<Integer, Integer> minMaxPair = Pair.minmax(A.get(0), A.get(1));
    for (int i = 2; i + 1 < A.size(); i += 2) {
      Pair<Integer, Integer> localPair = Pair.minmax(A.get(i), A.get(i + 1));
      minMaxPair = new Pair<>(
          Math.min(minMaxPair.getFirst(), localPair.getFirst()), 
          Math.max(minMaxPair.getSecond(), localPair.getSecond()));
    }
    // Special case: If there is odd number of elements in the array, we still
    // need to compare the last element with the existing answer.
    if ((A.size() & 1) != 0) {
      minMaxPair = new Pair<>(
          Math.min(minMaxPair.getFirst(), A.get(A.size() - 1)),
          Math.max(minMaxPair.getSecond(), A.get(A.size() - 1)));
    }
    return minMaxPair;
  }

Find the missing IP address MissingElement.java

  public static int findMissingElement(InputStream ifs) throws IOException {
    int[] counter = new int[1 << 16];
    ifs.mark(Integer.MAX_VALUE);
    Scanner s = new Scanner(ifs);
    while (s.hasNextInt()) {
      ++counter[s.nextInt() >> 16];
    }

    for (int i = 0; i < counter.length; ++i) {
      // Finds one bucket contains less than (1 << 16) elements.
      if (counter[i] < (1 << 16)) {
        BitSet bitVec = new BitSet(1 << 16);
        ifs.reset();
        s = new Scanner(ifs);
        while (s.hasNext()) {
          int x = s.nextInt();
          if (i == (x >> 16)) {
            bitVec.set(((1 << 16) - 1) & x); // Gets the lower 16 bits of x.
          }
        }
        ifs.close();

        for (int j = 0; j < (1 << 16); ++j) {
          if (!bitVec.get(j)) {
            return (i << 16) | j;
          }
        }
      }
    }
    throw new RuntimeException("no missing element");
  }

Find the duplicate and missing elements

FindMissingAndDuplicate.java
  public static Pair<Integer, Integer> findDuplicateMissing(List<Integer> A) {
    int sum = 0, squareSum = 0;
    for (int i = 0; i < A.size(); ++i) {
      sum += i - A.get(i);
      squareSum += i * i - A.get(i) * A.get(i);
    }
    return new Pair<>((squareSum / sum - sum) / 2, (squareSum / sum + sum) / 2);
  }
FindMissingAndDuplicateXOR.java
  public static Pair<Integer, Integer> findDuplicateMissing(List<Integer> A) {
    int missXORDup = 0;
    for (int i = 0; i < A.size(); ++i) {
      missXORDup ^= i ^ A.get(i);
    }

    // We need to find a bit that's set to 1 in missXORDup. This assignment
    // sets all of bits in differBit to 0 except for the least significant
    // bit in missXORDup that's 1.
    int differBit = missXORDup & (~(missXORDup - 1));

    int missOrDup = 0;
    for (int i = 0; i < A.size(); ++i) {
      if ((i & differBit) != 0) {
        missOrDup ^= i;
      }
      if ((A.get(i) & differBit) != 0) {
        missOrDup ^= A.get(i);
      }
    }

    for (int ai : A) {
      if (ai == missOrDup) { // Find duplicate.
        return new Pair<>(missOrDup, missOrDup ^ missXORDup);
      }
    }
    // missOrDup is the missing element.
    return new Pair<>(missOrDup ^ missXORDup, missOrDup);
  }

Find an element that appears only once

FindElementAppearsOnce.java
  public static int findElementAppearsOnce(List<Integer> A) {
    int ones = 0, twos = 0;
    int nextOnes, nextTwos;
    for (int i : A) {
      nextOnes = (~i & ones) | (i & ~ones & ~twos);
      nextTwos = (~i & twos) | (i & ones);
      ones = nextOnes;
      twos = nextTwos;
    }
    return ones;
  }

Test if an anonymous letter is constructible AnonymousLetter.java

  public static boolean anonymousLetter(String L, String M) {
    Map<Character, Integer> hash = new HashMap<>();
    // Inserts all chars in L into a hash table.
    for (char c : L.toCharArray()) {
      if (!hash.containsKey(c)) {
        hash.put(c, 1);
      } else {
        hash.put(c, hash.get(c) + 1);
      }
    }

    // Checks characters in M that could cover characters in a hash table.
    for (char c : M.toCharArray()) {
      if (hash.containsKey(c)) {
        hash.put(c, hash.get(c) - 1);
        if (hash.get(c) == 0) {
          hash.remove(c);
          if (hash.isEmpty()) {
            return true;
          }
        }
      }
    }
    // No entry in hash means L can be covered by M.
    return hash.isEmpty();
  }

Implement mergesort in-place MergeTwoSortedArraysInPlace.java

  public static void mergeTwoSortedArrays(int A[], int m, int B[], int n) {
    int a = m - 1, b = n - 1, tar = m + n - 1;
    while (a >= 0 && b >= 0) {
      A[tar--] = (A[a] > B[b]) ? A[a--] : B[b--];
    }
    while (b >= 0) {
      A[tar--] = B[b--];
    }
  }

Pre-Sort

Count the frequencies of characters in a sentence CountOccurrencesInSentence.java

  public static void countOccurrences(String s) {
    char[] a = s.toCharArray();
    Arrays.sort(a);

    int count = 1;
    for (int i = 1; i < a.length; ++i) {
      if (a[i] == a[i - 1]) {
        ++count;
      } else {
        System.out.print("(" + a[i - 1] + "," + count + "),");
        count = 1;
      }
    }
    System.out.println("(" + a[a.length - 1] + ',' + count + ")");
  }

Find unique elements  EliminateDuplicate.java

  public static void eliminateDuplicate(ArrayList<Integer> a) {
    Collections.sort(a); // makes identical elements become neighbors.
    // C++ unique-like algorithm on indexes
    if (a.size() < 2) {
      return;
    }
    int result = 0;
    for (int first = 1; first < a.size(); first++) {
      if (!a.get(first).equals(a.get(result))) {
        a.set(++result, a.get(first));
      }
    }
    // shrink array size
    a.subList(++result, a.size()).clear();
  }

Compute an optimum assignment of tasks TaskAssignment.java

  public static List<Pair<Integer, Integer>> taskAssignment(
      List<Integer> A) {
    Collections.sort(A);
    List<Pair<Integer, Integer>> P = new ArrayList<>();
    for (int i = 0, j = A.size() - 1; i < j; ++i, --j) {
      P.add(new Pair<>(A.get(i), A.get(j)));
    }
    return P;
  }
Team photo day---1 TeamPhoto1.java

Implement a fast sorting algorithm for listsSortList.java

  public static Node<Integer> sortList(Node<Integer> L) {
    // Base case. L has 0 or 1 node.
    if (L == null || L.next == null) {
      return L;
    }

    // Finds the middle point of L.
    Node<Integer> preSlow = null, slow = L, fast = L;
    while (fast != null && fast.next != null) {
      preSlow = slow;
      fast = fast.next.next;
      slow = slow.next;
    }

    preSlow.next = null; // Splits the list into two lists.
    return MergeSortedLists.mergeTwoSortedLinkedLists(sortList(L),
                                                      sortList(slow));
  }
UnconstructableChange
  public static int NonconstructibleChange(List<Integer> A) {
    Collections.sort(A);
    int sum = 0;
    for (int a : A) {
      if (a > sum + 1) {
        break;
      }
      sum += a;
    }
    return sum + 1;
  }

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts