Skip to content

Instantly share code, notes, and snippets.

public class DetectCycle {
int time;
public boolean hasCycle(List <Node> nodes) {
time = 0;
for (Node node: nodes) {
if (node.color.equals(Color.White)) {
if (dfsVisit(node)) {
return true;
class Node {
char c;
Set <Node> children;
}
class PrefixGrouper {
ArrayList <String> result = new ArrayList<String>();
public ArrayList<String> prefixWith(Node root, String prefix) {
result.clear();
public boolean isValid(char [][]board) {
for (int i = 0; i < 9; i++) {
if (!isValid(board, 0, i, 9, 1) || !isValid(board, i, 0, 1, 9)) {
return false;
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (!isValid(board, 3*i, 3*j, 3, 3)) {
return false;
class Node {
int val;
Node left;
Node right;
}
public String serialize(Node root) {
StringBuilder sb = new StringBuilder();
serialize(root, sb);
return sb.toString();
class Median {
MaxHeap maxHeap;
MinHeap minHeap;
// maintain invariant size of maxHeap equals to or greater than size of minHeap by 1
public void add(int x) {
maxHeap.add(x);
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.add(maxHeap.remove());
}
char unique (String str) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
Set<Character> set = new SortedHashSet<Character>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
set.remove(c);
} else {
public class StringToLong {
public long stringToLong(String s) {
return stringToLong(s, true, true, true);
}
public long stringToLong(
String s,
boolean allowHeadingTailingSpaces, // allow spaces in the begin/end of string
boolean allowNonDigit, // allow non digit char in the end, will only parse all digits
import java.util.LinkedList;
import java.util.Queue;
public class TrinaryTree {
private TrinaryNode root;
public TrinaryTree insert(int []ary) {
for (int i: ary) {
insert(i);
}
// first version
float eval(String str) {
String [] tokens = str.split(" ");
Stack <Float> stack = new Stack<Float>();
for (String token: tokens) {
if (!isOp(token)) {
} else {
float right = stack.remove();
float left = stack.remove();
public int minCut(String s) {
final int N = s.length();
char []str = s.toCharArray();
// build palindrome
boolean [][] palindrome = new boolean[N][N];
for (int i = N - 1; i >= 0; --i) {
for (int j = i; j < N; j++) {
if (i == j ||
(str[i] == str[j] && (j - i == 1 || palindrome[i + 1][j - 1]))) {