repo stringclasses 1k values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 6 values | commit_sha stringclasses 1k values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-four-trees-and-graphs/CreateBinarySearchTree.java | cracking-the-coding-interview/chapter-four-trees-and-graphs/CreateBinarySearchTree.java | /* given a sorted (increasing order) array with unique integer elements, write an algorithm
* to create a binary search tree with minimal height */
public class CreateBinarySearchTree {
TreeNode createMinimalBST(int arr[], int start, int end) {
if(end < start) {
return null;
}
int mid = (start + end) / 2;
TreeNode n = new TreeNode(arr[mid]);
n.left = createMinimalBST(arr, start, mid - 1);
n.right = createMinimalBST(arr, mid + 1, end);
return n;
}
TreeNode createMinimalBST(int array[]) {
return createMinimalBST(array, 0, array.length - 1);
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-four-trees-and-graphs/BinaryTreeIsBalanced.java | cracking-the-coding-interview/chapter-four-trees-and-graphs/BinaryTreeIsBalanced.java | /* implement a function to check if a binary tree is balanced. For the purpose of this
* question, a balanced tree is defined to be a tree such that the heights of the two
* subtrees of any node never differ by more than one */
public class BinaryTreeIsBalanaced {
public static int getHeight(TreeNode root) {
if(root == null) {
return 0; //base case
}
return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}
public static boolean isBalanced(TreeNode root) {
if(root == null) { //base case
return true;
}
int heightDiff = getHeight(root.left) - getHeight(root.right);
if(Math.abs(heightDiff) > 1) {
return false;
}
else { //recurse
return isBalanced(root.left) && isBalanced(root.right);
}
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-four-trees-and-graphs/CreateLinkedListForEachLevel.java | cracking-the-coding-interview/chapter-four-trees-and-graphs/CreateLinkedListForEachLevel.java | /* given a binary tree, design an algorithm which creates a linked list of all the nodes
* at each depth (e.g., if you have a tree with depth D, you'll have D linked lists) */
public class CreateLinkedListForEachLevel {
ArrayList<LinkedList<TreeNode>> createLinkedList(TreeNode root) {
ArrayList<LinkedList<TreeNode>> result = new ArrayList<LinkedList<TreeNode>>();
/* "visit" the root */
LinkedList<TreeNode> current = new LinkedList<TreeNode>();
if(root != null) {
current.add(root);
}
while(current.size() > 0) {
result.add(current); //add previous level
LinkedList<TreeNode> parents = current; //go to next level
current = new LinkedList<TreeNode>();
for(TreeNode parent : parents) {
/* visit the children */
if(parent.left != null) {
current.add(parrent.left);
}
if(parent.right != null) {
current.add(parent.right);
}
}
}
return result;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-four-trees-and-graphs/ValidBinarySearchTree.java | cracking-the-coding-interview/chapter-four-trees-and-graphs/ValidBinarySearchTree.java | /* implement a function to check if a binary tree is a binary search tree */
public class ValidBinarySearchTree {
boolean checkBST(TreeNode n) {
return checkBST(n, null, null);
}
boolean checkBST(TreeNode n, Integer min, Integer max) {
if(n == null) {
return true;
}
if((min != null && n.data <= min) || (max != null && n.data > max)) {
return false;
}
if(!checkBST(n.left, min, n.data) || !checkBST(n.right, n.data, max)) {
return false;
}
return true;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-four-trees-and-graphs/PrintPaths.java | cracking-the-coding-interview/chapter-four-trees-and-graphs/PrintPaths.java | /* you are given a binary tree in which each ndoe contains an integer value (which might be positive
* or negative). Design an algorithm to print all paths which sum to a given value. The path does not need
* to start or end at the root or a leaf, but it must go in a straight line */
public class PrintPaths {
void findSum(TreeNode node, int sum, int[] path, int level) {
if(node == null) {
return;
}
/* insert current node into path */
path[level] = node.data;
/* look for paths with a sum that ends at this node */
int t = 0;
for(int i = level; i >= 0; i--) {
t += path[i];
if(t == sum) {
print(path, i, level);
}
}
/* search nodes beneath this one */
findSum(node.left, sum, path, level + 1);
findSum(node.right, sum, path, level + 1);
/* remove current node from path. Not strictly necessary, since
* we would ignore this value, but it's good practice */
path[level] = Integer.MIN_VALUE;
}
void findSum(TreeNode node, int sum) {
int depth = depth(node);
int[] path = new int[depth];
findSum(node, sum, path, 0);
}
void print(int[] path, int start, int end) {
for(int i = start; i <= end; i++) {
System.out.print(path[i] + " ");
}
System.out.println();
}
int depth(TreeNode node) {
if(node == null) {
return 0;
}
else {
return 1 + Math.max(depth(node.left), depth(node.right));
}
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-four-trees-and-graphs/FindPath.java | cracking-the-coding-interview/chapter-four-trees-and-graphs/FindPath.java | /* give a directed graph, design an algorithm to find out whether there is a route between two nodes */
public class FindPath {
public enum State {
Unvisited, Visited, Visiting;
}
public static boolean search(Graph g, Node start, Node end) {
if(start == end) return true;
//operates as Queue
LinkedList<Node> q = new LinkedList<Node>();
for(Node u : g.getNodes()) {
u.state = State.Unvisited;
}
start.state = State.Visiting;
q.add(start);
Node u;
while(!q.isEmpty()) {
u = q.removeFirst(); //i.e., dequeue()
if(u != null) {
for(Node v : u.getAdjacent()) {
if(v.state == State.Unvisited) {
if(v == end) {
return true;
}
else {
v.state = State.Visiting;
q.add(v);
}
}
}
}
u.state = State.Visited;
}
return false;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-three-stacks-and-queues/QueueUsingTwoStacks.java | cracking-the-coding-interview/chapter-three-stacks-and-queues/QueueUsingTwoStacks.java | /* implement a MyQueue class which implements a queue using two stacks */
public class QueueUsingTwoStacks {
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-three-stacks-and-queues/StackWithMin.java | cracking-the-coding-interview/chapter-three-stacks-and-queues/StackWithMin.java | //How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop, and min should all operate in O(1) time
public class StackWithMin extends Stack<NodeWithMin> {
public void push(int value) {
int newMin = Math.min(value, min());
super.push(new NodeWithMin(value, newMin));
}
public int min() {
if(this.isEmpty()) {
return Integer.MAX_VALUE; //error value
}
else {
return peek().min;
}
}
}
class NodeWithMin {
public int value;
public int min;
public NodeWithMin(int v, int min) {
this.value = v;
this.min = min;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-three-stacks-and-queues/MyQueue.java | cracking-the-coding-interview/chapter-three-stacks-and-queues/MyQueue.java | /* implement a MyQueue class which implements a queue using two stacks */
public class MyQueue<T> {
Stack<T> stackNewest, stackOldest;
public MyQueue() {
stackNewest = new Stack<T>();
stackOldest = new Stack<T>();
}
public int size() {
return stackNewest.size() + stackOldest.size();
}
public void add(T value) {
/* push onto stackNewest, which always has the newest
* elements on top */
stackNewest.push(value);
}
/* Move elements from stackNewest into stackOldest. This
* is usually done so that we can do operations on stackOldest */
private void shiftStacks() {
if(stackOldest.isEmpty()) {
while(!stackNewest.isEmpty()) {
stackOldest.push(stackNewest.pop());
}
}
}
public T peek() {
shiftStacks(); //ensure stackOldest has the current elements
return stackOldest.peek(); //retrieve the oldest item
}
public T remove() {
shiftStacks(); //ensure stackOldest has the current elements
return stackOldest.pop();
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-three-stacks-and-queues/ThreeStacks.java | cracking-the-coding-interview/chapter-three-stacks-and-queues/ThreeStacks.java | //Describe how you could use a single array to implement three stacks
public class ThreeStacks {
int stackSize = 100;
int[] buffer = new int[stackSize * 3];
int[] stackPointer = {-1, -1, -1}; //pointers to track top element
void push(int stackNum, int value) throws Exception {
/* check if we have space */
if(stackPointer[stackNum] + 1 >= stackSize) { //last element
throw new FullStackException();
}
/* increment stack pointer and then update top value */
stackPointer[stackNum]++;
buffer[absTopOfStack(stackNum)] = value;
}
int pop(int stackNum) throws Exception {
if(isEmpty(stackNum)) {
throw new EmptyStackException();
}
int value = buffer[absTopOfStack(stackNum)]; //get top
buffer[absTopOfStack(stackNum)] = 0; //clear index
stackPointer[stackNum]--; //decrement pointer
return value;
}
int peek(int stackNum) {
if(isEmpty(stackNum)) {
throw new EmptyStackException();
}
int index = absTopOfStack(stackNum);
return buffer[index];
}
boolean isEmpty(int stackNum) {
return stackPointer[stackNum] == -1;
}
/* returns index of top of stack "stackNum", in absolute terms */
int absTopOfStack(int stasckNum) {
return stackNum * stackSize + stackPointer[stackNum];
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-three-stacks-and-queues/MyQUeue.java | cracking-the-coding-interview/chapter-three-stacks-and-queues/MyQUeue.java | /* implement a MyQueue class which implements a queue using two stacks */
public class MyQueue<T> {
Stack<T> stackNewest, stackOldest;
public MyQueue() {
stackNewest = new Stack<T>();
stackOldest = new Stack<T>();
}
public int size() {
return stackNewest.size() + stackOldest.size();
}
public void add(T value) {
/* push onto stackNewest, which always has the newest
* elements on top */
stackNewest.push(value);
}
/* Move elements from stackNewest into stackOldest. This
* is usually done so that we can do operations on stackOldest */
private void shiftStacks() {
if(stackOldest.isEmpty()) {
while(!stackNewest.isEmpty()) {
stackOldest.push(stackNewest.pop());
}
}
}
public T peek() {
shiftStacks(); //ensure stackOldest has the current elements
return stackOldest.peek(); //retrieve the oldest item
}
public T remove() {
shiftStacks(); //ensure stackOldest has the current elements
return stackOldest.pop();
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-three-stacks-and-queues/TowersOfHanoi.java | cracking-the-coding-interview/chapter-three-stacks-and-queues/TowersOfHanoi.java | /* in the classic problem of the Towers of Hanoi, you have 3 towers and N disks of
* different sizes which can slide onto any tower. The puzzle starts with disks sorted
* in ascending order of size from top to bottom (i.e. each disk sits on top of an even
* larger one). You have the following constraints:
* (1) Only one disk can be moved at a time
* (2) A disk is slid off the top of one tower onto the next rod
* (3) A disk can only be placed on top of a larger disk
* Write a program to move the disks from the first tower to the last tower using Stacks */
public class TowersOfHanoi {
public static void main(String args[]) {
int n = 3;
Tower[] towers = new Tower[n];
for(int i = 0; i < 3; i++) {
towers[i] = new Tower(i);
}
for(int i = n - 1; i >= 0; i--) {
towers[0].add(i);
}
towers[0].moveDisks(n, towers[2], towers[1]);
}
}
public class Tower {
private Stack<Integer> disks;
private int index;
public Tower(int i) {
disks = new Stack<Integer>();
index = i;
}
public int index() {
return index;
}
public void add(int d) {
if(!disks.isEmpty() && disks.peek() <= d) {
System.out.println("Error placing disk " + d);
}
else {
disks.push(d);
}
}
public void moveTopTo(Tower t) {
int top = disks.pop();
t.add(top);
System.out.println("Move disk " + top + " from " + index() + " to " + t.index());
}
public void moveDisks(int n, Tower destination, Tower buffer) {
if(n > 0) {
moveDisks(n - 1, buffer, destination);
moveTopTo(destination);
buffer.moveDisks(n - 1, destination, this);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-three-stacks-and-queues/BinaryTreeIsBalanced.java | cracking-the-coding-interview/chapter-three-stacks-and-queues/BinaryTreeIsBalanced.java | /* implement a function to check if a binary tree is balanced. For the purpose of this
* question, a balanced tree is defined to be a tree such that the heights of the two
* subtrees of any node never differ by more than one */
public class BinaryTreeIsBalanaced {
public static int getHeight(TreeNode root) {
if(root == null) {
return 0; //base case
}
return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}
public static boolean isBalanced(TreeNode root) {
if(root == null) { //base case
return true;
}
int heightDiff = getHeight(root.left) - getHeight(root.right);
if(Math.abs(heightDiff) > 1) {
return false;
}
else { //recurse
return isBalanced(root.left) && isBalanced(root.right);
}
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-three-stacks-and-queues/SortStack.java | cracking-the-coding-interview/chapter-three-stacks-and-queues/SortStack.java | /* write a program to sort a stack in ascending order (with biggest items on top).
* you may use at most one additional stack to hold items, but you may not copy the
* elements into any other data strcuture (such as an array). The stack supports the
* folowing operations: push, pop, peek, and isEmpty */
public class SortStack {
public static Stack<Integer> sort(Stack<Integer> s) {
Stack<Integer> r = new Stack<Integer>();
while(!s.isEmpty()) {
int tmp = s.pop(); //step 1
while(!r.isEmpty() && r.peek() > tmp) { //step 2
s.push(r.pop());
}
r.push(tmp); //step 3
}
return r;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-three-stacks-and-queues/SetOfStacks.java | cracking-the-coding-interview/chapter-three-stacks-and-queues/SetOfStacks.java | /* imagine a (literal) stack of plates. If the stack gets too high, it might topple.
* Therefore, in real life, we would likely start a new stack when the previous stack
* exceeds some threshold. Implement a data structure SetOfStacks that mimics this.
* SetOfStacks should be composed of several stacks and should create a new stack once
* the previous one exceeds capacity. SetOfStacks.push() and SetOfStacks.pop() should
* behave identically to a single stack (that is, pop() should return the same values as
* it would if there were just a single stack) */
//in this problem, we've been told what our data structure should look like:
public class SetOfStacks {
ArrayList<Stack> stacks = new ArrayList<Stack>();
//public void push(int v) {...}
//public int pop() {...}
public void push(int v) {
Stack last = getLastStack();
if(last != null && !last.isFull()) { //add to the last stack
last.push(v);
}
else { //must create new stack
Stack stack = new Stack(capacity);
stack.push(v);
stacks.add(stack);
}
}
public void pop() {
Stack last = getLastStack();
int v = last.pop();
if(last.size == 0) {
stacks.remove(stacks.size() - 1);
}
return v;
}
public Stack getLastStack() {
if(stacks.size() == 0) {
return null;
}
return stacks.get(stacks.size() - 1);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/AllPermutations.java | cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/AllPermutations.java | /* write a method to compute all permutations of a string of unique characters */
public class AllPermutations {
public static ArrayList<String> getPerms(String str) {
if(str == null) {
return null;
}
ArrayList<String> permutations = new ArrayList<String>();
if(str.length() == 0) { //base case
permutations.add("");
return permutations;
}
char first = str.charAt(0); //get the first character
String remainder = str.substring(1); //remove the 1st character
ArrayList<String> words = getPerms(remainder);
for(String word : words) {
for(int j = 0; j <= word.length(); j++) {
String s = insertCharAt(word, first, j);
permutations.add(s);
}
}
return permutations;
}
public static String insertCharAt(String word, char c, int i) {
String start = word.substring(0, i);
String end = word.substring(i);
return start + c + end;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/Staircase.java | cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/Staircase.java | /* a child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps
* at a time. Implement a method to count how many possible ways the child can run up the stairs */
public class Staircase {
public static int countWaysDP(int n, int[] map) {
if(n < 0) {
return 0;
}
else if(n == 0) {
return 1;
}
else if(map[n] > -1) {
return map[n];
}
else {
map[n] = countWaysDP(n - 1, map) +
countWaysDP(n - 2, map) +
countWaysDP(n - 3, map);
return map[n];
}
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/AllSubsets.java | cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/AllSubsets.java | /* write a method to return all subsets of a set */
public class AllSubsets {
ArrayList<ArrayList<Integer>> getSubsets(ArrayList<Integer> set, int index) {
ArrayList<ArrayList<Integer>> allsubsets;
if(set.size() == index) { //base case - add empty set
allsubsets = new ArrayList<ArrayList<Integer>>();
allsubsets.add(new ArrayList<Integer>()); //empty set
}
else {
allsubsets = getSubsets(set, index + 1);
int item = set.get(index);
ArrayList<ArrayList<Integer>> moresubsets = new ArrayList<ArrayList<Integer>>();
for(ArrayList<Integer> subset : allsubsets) {
ArrayList<Integer> newsubset = new ArrayList<Integer>();
newsubset.addAll(subset);
newsubset.add(item);
moresubsets.add(newsubset);
}
allsubsets.addAll(moresubsets);
}
return allsubsets;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/EightQueens.java | cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/EightQueens.java | /* write an algorithm to print all ways of arranging eight queens on an 8x8 chess board so that none of them
* share the same row, column or diagonal. In this case, "diagonal" means all diagonals, not just the two
* that bisect the board */
public class EightQueens {
public static final int GRID_SIZE = 8;
void placeQueens(int row, Integer[] columns, ArrayList<Integer[]> results) {
if(row == GRID_SIZE) { //found valid placement
results.add(columns.clone());
}
else {
for(int col = 0; col < GRID_SIZE; col++) {
if(checkValid(columns, row, col)) {
columns[row] = col; //place queen
placeQueens(row + 1, columns, results);
}
}
}
}
/* check if (row1, column1) is a valid spot for a queen by checking if there
* is a queen in the same column or diagonal. We don't need to check it for
* queens in the same row because the calling placeQueen only attempts to
* place one queen at a time. We know thi srow is empty */
boolean checkValid(Integer[] columns, int row1, int column1) {
for(int row2 = 0; row2 < row1; row2++) {
int column2 = columns[row2];
/* check if (row2, column2) invalides (row1, column1) as a queen spot */
/* check if rows have a queen in the same column */
if(column1 == column2) {
return false;
}
/* check diagonals: if the distance between the columns equals the distance
* between the rows, then they're in the same diagonal */
int columnDistance = Math.abs(column2 - column1);
/* row1 > row2, so no need for abs */
int rowDistance = row1 - row2;
if(columnDistance == rowDistance) {
return false;
}
}
return true;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/RepresentingNCents.java | cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/RepresentingNCents.java | /* given an infinite number of quars (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent),
* write code to calculate the number of ways of representing n cents */
public class RepresentingNCents {
int makeChange(int n) {
int[] denoms = {25, 10, 5, 1};
int[][] map = new int[n + 1][denoms.length]; //precomputed vals
return makeChange(n, denoms, 0, map);
}
int makeChange(int amount, int[] denoms, int index, int[][] map) {
if(map[amount][index] > 0) { //retrieve value
return map[amount][index];
}
if(index >= denoms.length - 1) return 1; //one denom remaining
int denomAmount = denoms[index];
int ways = 0;
for(int i = 0; i * denomAmount <= amount; i++) {
//go to next denom, assuming i coints of denomAmount
int amountRemaining = amount - i * denomAmount;
ways += makeChange(amountRemaining, denoms, index + 1, map);
}
map[amount][index] = ways;
return ways;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/MagicIndex.java | cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/MagicIndex.java | /* a magic index is an array A[1...n - 1] is defined to be an index such that A[i] = i. Given a sorted
* array of distinct integers, write a method to find a magic index, if one exists, in array A */
public class MagicIndex {
public static int magicFast(int[] array, int start, int end) {
if(end < start || start < 0 || end >= array.length) {
return -1;
}
int mid = (start + end) / 2;
if(array[mid] == mid) {
return mid;
}
else if(array[mid] > mid) {
return magicFast(array, start, mid - 1);
}
else {
return magicFast(array, mid + 1, end);
}
}
public static int magicFast(int[] array) {
return magicFast(array, 0, array.length - 1);
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/StackBoxes.java | cracking-the-coding-interview/chapter-nine-recursion-and-dynamic-programming/StackBoxes.java | /* you have a stack of n boxes, with widths wi, heights hi, and depths di. The boxes cannot be rotated
* and can only be stacked on top of one another if each box in the stack is strictly larger than the
* the box above it in width, height, and depth. Implement a method to build the tallest stack possible,
* where the height of a stack is the sum of the heights of each box */
public class StackBoxes {
public ArrayList<Box> createStackDP(Box[] boxes, Box bottom, HashMap<Box, ArrayList<Box>> stack_map) {
if(bottom != null && stack_map.containsKey(bottom)) {
return (ArrayList<Box>) stack_map.get(bottom).clone();
}
int max_height = 0;
ArrayList<Box> max_stack = null;
for(int i = 0; i < boxes.length; i++) {
if(boxes[i].canBeAbove(bottom)) {
ArrayList<Box> new_stack = createStackDP(boxes, boxes[i], stack_map);
int new_height = stackHeight(new_stack);
if(new_height > max_height) {
max_stack = new_stack;
max_height = new_height;
}
}
}
if(max_stack == null) {
max_stack = new ArrayList<Box>();
}
if(bottom != null) {
max_stack.add(0, bottom);
}
stack_map.put(bottom, max_stack);
return max_stack;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-five-bit-manipulation/BinaryRepresentation.java | cracking-the-coding-interview/chapter-five-bit-manipulation/BinaryRepresentation.java | /* given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print
* the binary representation. If the number cannot be represented accurately in binary
* with at most 32 characters, print "ERROR" */
public class BinaryRepresentation {
public static String printBinary(double num) {
if(num >= 1 || num <= 0) {
return "ERROR";
}
StrinBuilder binary = new StringBuilder();
binary.append(".");
while(num > 0) {
/* setting a limit on length: 32 characters */
if(binary.length() >= 32) {
return "ERROR";
}
double r = num * 2;
if(r >= 1) {
binary.append(1);
num = r - 1;
}
else {
binary.append(0);
num = r;
}
}
return binary.toString();
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-five-bit-manipulation/InsertMIntoN.java | cracking-the-coding-interview/chapter-five-bit-manipulation/InsertMIntoN.java | /* you are given two 32-bit numbers, N and M, are two bit positions, i and j. Write
* a method to insert M into N such that M starts at bit j and ends at bit i. You can
* assume that the bits j through i have enough space to fit all of M. That is, if M = 10011,
* you can assume that there are at least 5 bits between j and i. You would not, for example,
* have j = 3 and i = 2, because M could not fully bit between bit 3 and bit 2.
EXAMPLE:
Input: N = 10000000000, m = 10011, i = 2, j = 6
Output: N = 10001001100 */
public class InsertMIntoN {
int updateBits(int n, int m, int i, int j) {
/* create a mask to clear bits i through j in n
* EXAMPLE: i = 2, j = 4. Result should be 11100011.
* For simplicity, we'll just use 8 bits for the example.
*/
int allones = ~0; //wil equal sequence of all 1s
//1s before position j, then 0s. Left = 11100000
int left = allOnes << (j + 1);
//1s after position i. Right = 00000011
int right = ((1 << i) - 1);
//all 1s, except for 0s between i and j. Mask = 11100011
int mask = left | right;
/* clear bits j through i then put m in there */
int n_cleared = n & mask; //clear bits j through i
int m_shifted = m << i; //move m into correct position
return n_cleared | m_shifted; //OR them, and we're done!
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-five-bit-manipulation/SwapBits.java | cracking-the-coding-interview/chapter-five-bit-manipulation/SwapBits.java | /* write a program to swap odd and even bits in an integer with as few instructions as
* possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on) */
public class SwapBits {
public int swapOddEvenBits(int x) {
return ( ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1) );
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-five-bit-manipulation/FindMissingInteger.java | cracking-the-coding-interview/chapter-five-bit-manipulation/FindMissingInteger.java | /* An array A contains all the integers from 0 through n, except for one number which is
* missing. In this problem, we cannot access an entire integer in A with a single operation.
* The elements of A are represented in binary, and the only operation we can use to acces them
* is "fetch the jth bit of A[i]," which takes constant time. Write code to find the missing
* integer. Can you do it in O(n) time? */
public class FindMissingInteger {
public int findMissing(ArrayList<BigInteger> array) {
/* start from the least significant bit, and work our way up */
return findMissing(array, 0);
}
public int findMissing(ArrayList<BigInteger> input, int column) {
if(column >= BigInteger.INTEGER_SIZE) { //we're done!
return 0;
}
ArrayList<BigInteger> oneBits = new ArrayList<BigInteger>(input.size() / 2);
ArrayList<BigInteger> zeroBits = new ArrayList<BigInteger>(input.size() / 2);
for(BigInteger t : input) {
if(t.fetch(column) == 0) {
zeroBits.add(t);
}
else {
oneBits.add(t);
}
}
if(zeroBits.size() <= oneBits.size()) {
int v = findMissing(zeroBits, column + 1);
return (v << 1) | 0;
}
else {
int v = findMissing(oneBits, column + 1);
return (v << 1) | 1;
}
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-one-arrays-and-strings/IsRotation.java | cracking-the-coding-interview/chapter-one-arrays-and-strings/IsRotation.java | // Assume you have a method isSubstring which checks if one word is a isSubstring of another.
// Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only
// one call to isSubstring(e.g., "waterbottle" is a rotation of "erbottlewat").
public class IsRotation {
public boolean isRotation(String s1, String s2) {
int len = s1.length();
/*check that s1 and s2 are equal length and not empty */
if(len == s2.length() && len > 0) {
/* concatenate s1 and s1 within new buffer */
String s1s1 = s1 + s1;
return isSubstring(s1s1, s2);
}
return false;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-one-arrays-and-strings/IsUniqueChars.java | cracking-the-coding-interview/chapter-one-arrays-and-strings/IsUniqueChars.java | //Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
public class IsUniqueChars {
public boolean isUniqueChars(String str) {
int checker = 0;
for(int i = 0; i < str.length(); i++) {
int val = str.charAt(i) - 'a';
if((checker & (1 << val)) > 0) {
return false;
}
checker |= (1 << val);
}
return true;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-one-arrays-and-strings/ReplaceSpaces.java | cracking-the-coding-interview/chapter-one-arrays-and-strings/ReplaceSpaces.java | // Write a method to replace all spaces in a string with '%20.' You may assume that the string
// has sufficient space at the end of the string to hold the additional characters, and that you
// are given the "true" length of the string. (Note: if implementing in Java, please use a characters
// array so that you can perform this operation in place)
public class ReplaceSpaces {
public void replaceSpaces(char[] str, int length) {
int spaceCount = 0, newLength;
for(int i = 0; i < length; i++) {
if(str[i] == ' ') {
spaceCount++;
}
}
newLength = length + spaceCount * 2;
str[newLength] = '\0';
for(int i = length - 1; i >= 0; i--) {
if(str[i] == ' ') {
str[newLength - 1] = '0';
str[newLength - 2] = '2';
str[newLength - 3] = '%';
newLength = newLength - 3;
}
else {
str[newLength - 1] = str[i];
newLength = newLength - 1;
}
}
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-one-arrays-and-strings/NthToLast.java | cracking-the-coding-interview/chapter-one-arrays-and-strings/NthToLast.java | //Implement an algorithm to find the kth to last element of a single linked list
public class NthToLast {
LinkedListNode nthToLast(LinkedListNode head, int k) {
if(k <= 0) return null;
LinkedListNode p1 = head;
LinkedListNode p2 = head;
//move p2 forward k nodes into the list
for(int i = 0; i < k - 1; i++) {
if(p2 == null) return null; //error check
p2 = p2.next;
}
if(p2 == null) return null;
/* now, move p1 and p2 at the same speed. When p2 hits the end,
* p1 will be at the right element */
while(p2.next != null) {
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-one-arrays-and-strings/Permutation.java | cracking-the-coding-interview/chapter-one-arrays-and-strings/Permutation.java | // Given two strings, write a method to decide if one is a permutation of the other
public class Permutation {
public boolean permutation(String s, String t) {
if(s.length() != t.length()) {
return false;
}
int[] letters = new int[256];
char[] s_array = s.toCharArray();
for(char c : s_array) {
letters[c]++;
}
for(int i = 0; i < t.length(); i++) {
int c = (int)t.charAt(i);
if(--letters[c] < 0) {
return false;
}
}
return true;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-one-arrays-and-strings/DeleteDups.java | cracking-the-coding-interview/chapter-one-arrays-and-strings/DeleteDups.java | //Write code to remove duplicates from an unsorted linked list
public class RemoveDups {
void deleteDups(LinkedListNode n) {
HashSet<Integer> set = new HashSet<Integer>();
LinkedListNode previous = null;
while(n != null) {
if(set.contains(n.data)) {
previous.next = n.next;
}
else {
set.add(n.data);
previous = n;
}
n = n.next;
}
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-seven-mathematics-and-probability/Operations.java | cracking-the-coding-interview/chapter-seven-mathematics-and-probability/Operations.java | /* write methods to implement the multiply, subtract, and divide operations for integers. Use only the add operator */
public class Operations {
/* flip a positive sign to negative or negative sign to positive */
public static int negate(int a) {
int neg = 0;
int d = a < 0 ? 1 : -1;
while(a != 0) {
neg += d;
a += d;
}
return neg;
}
/* subtract two numbers by negating b and adding them */
public static int minus(int a, int b) {
return a + negate(b);
}
/* multiply a by b by adding a to itself b times */
public static int multiply(int a, int b) {
if(a < b) {
return multiply(b, a); //algorithm is faster is b < a
}
int sum = 0;
for(int i = abs(b); i > 0; i--) {
sum += a;
}
if(b < 0) {
sum = negate(sum);
}
return sum;
}
/* return absolute value */
public static int abs(int a) {
if(a < 0) {
return negate(a);
}
else {
return a;
}
}
public int divide(int a, int b) throws ArithmeticException {
if(b == 0) {
throw new java.lang.ArithmeticException("ERROR");
}
int absa = abs(a);
int absb = abs(b);
int product = 0;
int x = 0;
while(product + absb <= absa) { //don't go past a
product += absb;
x++;
}
if((a < 0 && b < 0) || (a > 0 && b > 0)) {
return x;
}
else {
return negate(x);
}
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-seven-mathematics-and-probability/WouldIntersect.java | cracking-the-coding-interview/chapter-seven-mathematics-and-probability/WouldIntersect.java | /* give two lines on a Cartesian plane, determine whether the two lines would intersect */
public class WouldIntersect {
//placeholder for class name
}
class Line {
static double epsilon = 0.000001;
public double slope;
public double yintercept;
public Line(double s, double y) {
this.slope = s;
this.yintercept = y;
}
public boolean Intersect(Line line2) {
return Math.abs(this.slope - line2.slope) > epsilon || Math.abs(this.yintercept - line2.yintercept) < epsilon;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-two-linked-lists/Partition.java | cracking-the-coding-interview/chapter-two-linked-lists/Partition.java | //Write code to partition a linked list around a value x, such that
//all nodes less than x come before all nodes greater than or equal to x.
public class Partition {
LinkedListNode partition(LinkedListNode node, int x) {
LinkedListNode head = node;
LinkedListNode tail = node;
while(node != null) {
LinkedListNode next = node.next;
if(node.data < x) {
/* insert node at head */
node.next = head;
head = node;
}
else {
/* insert node at tail */
tail.next = node;
tail = node;
}
node = next;
}
tail.next = null;
//the head has changed, so we need to return it to the user
return head;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-two-linked-lists/FindBeginning.java | cracking-the-coding-interview/chapter-two-linked-lists/FindBeginning.java | //Given a circular linked list, implement an algorithm which returns
//the node at the beginning of the loop
public class FindBeginning {
LinkedListNode findBeginning(LinkedListNode head) {
LinkedListNode slow = head;
LinkedListNode fast = head;
/* find meeting point. This will be LOOP_SIZE - k
* steps int othe linked list */
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(fast == slow) {
break;
}
}
/* error checking - no meeting point, and therefore no loop */
if(fast == null || fast.next == null) {
return null;
}
/* move slow to head. Keep fast at meeting point. Each are k
* steps from the loop start. If they move at the same pace,
* they must meet at the loop start */
slow = head;
while(slow != fast) {
slow = slow.next;
fast = fast.next;
}
/* both now point to the start of the loop */
return fast;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-two-linked-lists/DeleteNode.java | cracking-the-coding-interview/chapter-two-linked-lists/DeleteNode.java | //Implement an algorithm to delete a node in the middle of a singly linked list, give only access to that node
public class DeleteNode {
public static boolean deleteNode(LinkedListNode n) {
if(n == null || n.next == null) {
return false;
}
LinkedListNode next = n.next;
n.data = next.data;
n.next = next.next;
return true;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-two-linked-lists/IsPalindrome.java | cracking-the-coding-interview/chapter-two-linked-lists/IsPalindrome.java | //Implement a function to check if a linked list is a palindrome
//don't forget import statements!
public class IsPalindrome {
boolean isPalindrome(LinkedListNode head) {
LinkedListNode fast = head;
LinkedListNode slow = head;
Stack<Integer> stack = new Stack<Integer>();
/* push elements from first half of linked list onto stack.
* When fast runner (which is moving at 2x speed) reaches the
* end of the linked list, then we know we're at the middle */
while(fast != null && fast.next != null) {
stack.push(slow.data);
slow = slow.next;
fast = fast.next.next;
}
/*has odd number of elements, so skip the middle element */
if(fast != null) {
slow = slow.next;
}
while(slow != null) {
int top = stack.pop().intValue();
/* if values are different, then it's not a palindrome */
if(top != slow.data) {
return false;
}
slow = slow.next;
}
return true;
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-two-linked-lists/NthToLast.java | cracking-the-coding-interview/chapter-two-linked-lists/NthToLast.java | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false | |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-two-linked-lists/DeleteDups.java | cracking-the-coding-interview/chapter-two-linked-lists/DeleteDups.java | //Write code to remove duplicates from an unsorted linked list
public class RemoveDups {
void deleteDups(LinkedListNode n) {
HashSet<Integer> set = new HashSet<Integer>();
LinkedListNode previous = null;
while(n != null) {
if(set.contains(n.data)) {
previous.next = n.next;
}
else {
set.add(n.data);
previous = n;
}
n = n.next;
}
}
} | java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/CountAndSay.java | leetcode/string/CountAndSay.java | // The count-and-say sequence is the sequence of integers beginning as follows:
// 1, 11, 21, 1211, 111221, ...
// 1 is read off as "one 1" or 11.
// 11 is read off as "two 1s" or 21.
// 21 is read off as "one 2, then one 1" or 1211.
// Given an integer n, generate the nth sequence.
// Note: The sequence of integers will be represented as a string.
public class CountAndSay {
public String countAndSay(int n) {
String s = "1";
for(int i = 1; i < n; i++) {
s = helper(s);
}
return s;
}
public String helper(String s) {
StringBuilder sb = new StringBuilder();
char c = s.charAt(0);
int count = 1;
for(int i = 1; i < s.length(); i++) {
if(s.charAt(i) == c) {
count++;
} else {
sb.append(count);
sb.append(c);
c = s.charAt(i);
count = 1;
}
}
sb.append(count);
sb.append(c);
return sb.toString();
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/DecodeWays.java | leetcode/string/DecodeWays.java | // A message containing letters from A-Z is being encoded to numbers using the following mapping:
// 'A' -> 1
// 'B' -> 2
// ...
// 'Z' -> 26
// Given an encoded message containing digits, determine the total number of ways to decode it.
// For example,
// Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
// The number of ways decoding "12" is 2.
public class DecodeWays {
public int numDecodings(String s) {
int n = s.length();
if(n == 0) {
return 0;
}
int[] dp = new int[n + 1];
dp[n] = 1;
dp[n - 1] = s.charAt(n - 1) != '0' ? 1 : 0;
for(int i = n - 2; i >= 0; i--) {
if(s.charAt(i) == '0') {
continue;
} else {
dp[i] = (Integer.parseInt(s.substring(i, i + 2)) <= 26) ? dp[i + 1] + dp[i + 2] : dp[i + 1];
}
}
return dp[0];
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/EditDistance.java | leetcode/string/EditDistance.java | // Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
// You have the following 3 operations permitted on a word:
// a) Insert a character
// b) Delete a character
// c) Replace a character
public class EditDistance {
public int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();
int[][] dp = new int[m + 1][n + 1];
for(int i = 0; i <= m; i++) {
dp[i][0] = i;
}
for(int i = 0; i <= n; i++) {
dp[0][i] = i;
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(word1.charAt(i) == word2.charAt(j)) {
dp[i + 1][j + 1] = dp[i][j];
} else {
int a = dp[i][j];
int b = dp[i][j + 1];
int c = dp[i + 1][j];
dp[i + 1][j + 1] = Math.min(a, Math.min(b, c));
dp[i + 1][j + 1]++;
}
}
}
return dp[m][n];
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/OneEditDistance.java | leetcode/string/OneEditDistance.java | // Given two strings S and T, determine if they are both one edit distance apart.
public class OneEditDistance {
public boolean isOneEditDistance(String s, String t) {
//iterate through the length of the smaller string
for(int i = 0; i < Math.min(s.length(), t.length()); i++) {
//if the current characters of the two strings are not equal
if(s.charAt(i) != t.charAt(i)) {
//return true if the remainder of the two strings are equal, false otherwise
if(s.length() == t.length()) {
return s.substring(i + 1).equals(t.substring(i + 1));
} else if(s.length() < t.length()) {
//return true if the strings would be the same if you deleted a character from string t
return s.substring(i).equals(t.substring(i + 1));
} else {
//return true if the strings would be the same if you deleted a character from string s
return t.substring(i).equals(s.substring(i + 1));
}
}
}
//if all characters match for the length of the two strings check if the two strings' lengths do not differ by more than 1
return Math.abs(s.length() - t.length()) == 1;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/FirstUniqueCharacterInAString.java | leetcode/string/FirstUniqueCharacterInAString.java | //Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
//
//Examples:
//
//s = "leetcode"
//return 0.
//
//s = "loveleetcode",
//return 2.
//Note: You may assume the string contain only lowercase letters.
class FirstUniqueCharacterInAString {
public int firstUniqChar(String s) {
HashMap<Character, Integer> characters = new HashMap<Character, Integer>();
for(int i = 0; i < s.length(); i++) {
char current = s.charAt(i);
if(characters.containsKey(current)) {
characters.put(current, -1);
} else {
characters.put(current, i);
}
}
int min = Integer.MAX_VALUE;
for(char c: characters.keySet()) {
if(characters.get(c) > -1 && characters.get(c) < min) {
min = characters.get(c);
}
}
return min == Integer.MAX_VALUE ? -1 : min;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/PalindromicSubstrings.java | leetcode/string/PalindromicSubstrings.java | //Given a string, your task is to count how many palindromic substrings in this string.
//The substrings with different start indexes or end indexes are counted as different substrings
//even they consist of same characters.
//Example 1:
//Input: "abc"
//Output: 3
//Explanation: Three palindromic strings: "a", "b", "c".
//Example 2:
//Input: "aaa"
//Output: 6
//Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
//Note:
//The input string length won't exceed 1000.
class PalindromicSubstrings {
int result = 0;
public int countSubstrings(String s) {
if(s == null || s.length() == 0) {
return 0;
}
for(int i = 0; i < s.length(); i++) {
extendPalindrome(s, i, i);
extendPalindrome(s, i, i + 1);
}
return result;
}
public void extendPalindrome(String s, int left, int right) {
while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
result++;
left--;
right++;
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/ReverseWordsInAString.java | leetcode/string/ReverseWordsInAString.java | //Given an input string, reverse the string word by word.
//For example,
//Given s = "the sky is blue",
//return "blue is sky the".
public class ReverseWordsInAString {
public String reverseWords(String s) {
String[] words = s.trim().split("\\s+");
String result = "";
for(int i = words.length - 1; i > 0; i--) {
result += words[i] + " ";
}
return result + words[0];
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/IntegerToEnglishWords.java | leetcode/string/IntegerToEnglishWords.java | // Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
// For example,
// 123 -> "One Hundred Twenty Three"
// 12345 -> "Twelve Thousand Three Hundred Forty Five"
// 1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
public class IntegerToEnglishWords {
private final String[] LESS_THAN_20 = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
private final String[] TENS = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
private final String[] THOUSANDS = { "", "Thousand", "Million", "Billion" };
public String numberToWords(int num) {
if(num == 0) {
return "Zero";
}
int i = 0;
String words = "";
while(num > 0) {
if(num % 1000 != 0) {
words = helper(num % 1000) + THOUSANDS[i] + " " + words;
}
num /= 1000;
i++;
}
return words.trim();
}
private String helper(int num) {
if(num == 0) {
return "";
} else if(num < 20) {
return LESS_THAN_20[num] + " ";
} else if(num < 100) {
return TENS[num / 10] + " " + helper(num % 10);
} else {
return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/GenerateParentheses.java | leetcode/string/GenerateParentheses.java | //Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
//
//For example, given n = 3, a solution set is:
//
//[
//"((()))",
//"(()())",
//"(())()",
//"()(())",
//"()()()"
//]
class GenerateParentheses {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
generateParenthesisRecursive(result, "", 0, 0, n);
return result;
}
public void generateParenthesisRecursive(List<String> result, String current, int open, int close, int n) {
if(current.length() == n * 2) {
result.add(current);
return;
}
if(open < n) {
generateParenthesisRecursive(result, current + "(", open + 1, close, n);
}
if(close < open) {
generateParenthesisRecursive(result, current + ")", open, close + 1, n);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/LongestCommonPrefix.java | leetcode/string/LongestCommonPrefix.java | class LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) {
return "";
}
String s = strs[0];
for(int i = 0; i < s.length(); i++) {
char current = s.charAt(i);
for(int j = 1; j < strs.length; j++) {
if(i >= strs[j].length() || strs[j].charAt(i) != current) {
return s.substring(0, i);
}
}
}
return s;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/PalindromePermutation.java | leetcode/string/PalindromePermutation.java | public class PalindromePermutation {
public boolean canPermutePalindrome(String s) {
char[] characters = new char[256];
for(int i = 0; i < s.length(); i++) {
characters[s.charAt(i)]++;
}
int oddCount = 0;
for(int i = 0; i < characters.length; i++) {
if(!(characters[i] % 2 == 0)) {
oddCount++;
if(oddCount > 1) {
return false;
}
}
}
return true;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/MultiplyStrings.java | leetcode/string/MultiplyStrings.java | // Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
// Note:
// The length of both num1 and num2 is < 110.
// Both num1 and num2 contains only digits 0-9.
// Both num1 and num2 does not contain any leading zero.
// You must not use any built-in BigInteger library or convert the inputs to integer directly.
public class MultiplyStrings {
public String multiply(String num1, String num2) {
int m = num1.length();
int n = num2.length();
int[] pos = new int[m + n];
for(int i = m - 1; i >= 0; i--) {
for(int j = n - 1; j >= 0; j--) {
int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
int p1 = i + j;
int p2 = i + j + 1;
int sum = mul + pos[p2];
pos[p1] += sum / 10;
pos[p2] = (sum) % 10;
}
}
StringBuilder sb = new StringBuilder();
for(int p : pos) if(!(sb.length() == 0 && p == 0)) {
sb.append(p);
}
return sb.length() == 0 ? "0" : sb.toString();
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/ValidParentheses.java | leetcode/string/ValidParentheses.java | // Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
// The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
public class ValidParentheses {
public boolean isValid(String s) {
if(s.length() % 2 == 1) {
return false;
}
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
stack.push(s.charAt(i));
} else if(s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == ')') {
stack.pop();
} else if(s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == ']') {
stack.pop();
} else if(s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '}') {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/RomanToInteger.java | leetcode/string/RomanToInteger.java | // Given a roman numeral, convert it to an integer.
// Input is guaranteed to be within the range from 1 to 3999
public class RomanToInteger {
public int romanToInt(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
int total = 0;
for(int i = 0; i < s.length() - 1; i++) {
if(map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) {
total -= map.get(s.charAt(i));
} else {
total += map.get(s.charAt(i));
}
}
total += map.get(s.charAt(s.length() - 1));
return total;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/MinimumWindowSubstring.java | leetcode/string/MinimumWindowSubstring.java | // Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
// For example,
// S = "ADOBECODEBANC"
// T = "ABC"
// Minimum window is "BANC".
// Note:
// If there is no such window in S that covers all characters in T, return the empty string "".
// If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
public class MinimumWindowSubstring {
public String minWindow(String s, String t) {
HashMap<Character, Integer> map = new HashMap<>();
for(char c : s.toCharArray()) {
map.put(c, 0);
}
for(char c : t.toCharArray()) {
if(map.containsKey(c)) {
map.put(c, map.get(c)+ 1);
} else {
return "";
}
}
int start = 0;
int end = 0;
int minStart = 0;
int minLength = Integer.MAX_VALUE;
int counter = t.length();
while(end < s.length()) {
char c1 = s.charAt(end);
if(map.get(c1) > 0) {
counter--;
}
map.put(c1, map.get(c1) - 1);
end++;
while(counter == 0) {
if(minLength > end - start) {
minLength = end - start;
minStart = start;
}
char c2 = s.charAt(start);
map.put(c2, map.get(c2) + 1);
if(map.get(c2) > 0) {
counter++;
}
start++;
}
}
return minLength == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLength);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/LongestSubstringWithAtMostKDistinctCharacters.java | leetcode/string/LongestSubstringWithAtMostKDistinctCharacters.java | // Given a string, find the length of the longest substring T that contains at most k distinct characters.
// For example, Given s = “eceba” and k = 2,
// T is "ece" which its length is 3.
public class LongestSubstringWithAtMostKDistinctCharacters {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int[] count = new int[256]; // there are 256 ASCII characters in the world
int i = 0; // i will be behind j
int num = 0;
int res = 0;
for (int j = 0; j < s.length(); j++) {
if (count[s.charAt(j)] == 0) { // if count[s.charAt(j)] == 0, we know that it is a distinct character
num++;
}
count[s.charAt(j)]++;
while (num > k && i < s.length()) { // sliding window
count[s.charAt(i)]--;
if (count[s.charAt(i)] == 0){
num--;
}
i++;
}
res = Math.max(res, j - i + 1);
}
return res;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/LongestPalindromicSubstring.java | leetcode/string/LongestPalindromicSubstring.java | //Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
//Example:
//Input: "babad"
//Output: "bab"
//Note: "aba" is also a valid answer.
//Example:
//Input: "cbbd"
//Output: "bb"
class LongestPalindromicSubstring {
public String longestPalindrome(String s) {
if(s == null || s.length() == 0) {
return "";
}
String longestPalindromicSubstring = "";
for(int i = 0; i < s.length(); i++) {
for(int j = i + 1; j <= s.length(); j++) {
if(j - i > longestPalindromicSubstring.length() && isPalindrome(s.substring(i, j))) {
longestPalindromicSubstring = s.substring(i, j);
}
}
}
return longestPalindromicSubstring;
}
public boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while(i <= j) {
if(s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/JudgeRouteCircle.java | leetcode/string/JudgeRouteCircle.java | //Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
//
//The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.
//
//Example 1:
//Input: "UD"
//Output: true
//Example 2:
//Input: "LL"
//Output: false
class JudgeRouteCircle {
public boolean judgeCircle(String moves) {
int UD = 0;
int LR = 0;
for(int i = 0; i < moves.length(); i++) {
if(moves.charAt(i) == 'U') {
UD++;
} else if(moves.charAt(i) == 'D') {
UD--;
} else if(moves.charAt(i) == 'L') {
LR++;
} else if(moves.charAt(i) == 'R') {
LR--;
}
}
return UD == 0 && LR == 0;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/ReverseVowelsOfAString.java | leetcode/string/ReverseVowelsOfAString.java | // Write a function that takes a string as input and reverse only the vowels of a string.
// Example 1:
// Given s = "hello", return "holle".
// Example 2:
// Given s = "leetcode", return "leotcede".
// Note:
// The vowels does not include the letter "y".
public class ReverseVowelsOfAString {
public String reverseVowels(String s) {
if(s == null || s.length() == 0) {
return s;
}
String vowels = "aeiouAEIOU";
char[] chars = s.toCharArray();
int start = 0;
int end = s.length() - 1;
while(start < end) {
while(start < end && !vowels.contains(chars[start] + "")) {
start++;
}
while(start < end && !vowels.contains(chars[end] + "")) {
end--;
}
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
return new String(chars);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/LongestPalindrome.java | leetcode/string/LongestPalindrome.java | public class LongestPalindrome {
public int longestPalindrome(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int count = 0;
for(int i = 0; i < s.length(); i++) {
if(!map.containsKey(s.charAt(i))) {
map.put(s.charAt(i), (int)(s.charAt(i)));
} else {
map.remove(s.charAt(i));
count++;
}
}
return map.isEmpty() ? count * 2 : count * 2 + 1;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/AddBinary.java | leetcode/string/AddBinary.java | // Given two binary strings, return their sum (also a binary string).
// For example,
// a = "11"
// b = "1"
// Return "100"
public class AddBinary {
public String addBinary(String a, String b) {
StringBuilder result = new StringBuilder();
int carry = 0;
int i = a.length() - 1;
int j = b.length() - 1;
while(i >= 0 || j >= 0) {
int sum = carry;
if(i >= 0) {
sum += a.charAt(i--) - '0';
}
if(j >= 0) {
sum += b.charAt(j--) - '0';
}
result.append(sum % 2);
carry = sum / 2;
}
if(carry != 0) {
result.append(carry);
}
return result.reverse().toString();
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/string/ValidPalindrome.java | leetcode/string/ValidPalindrome.java | public class ValidPalindrome {
public boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while(left < right) {
while(!Character.isLetterOrDigit(s.charAt(left)) && left < right) {
left++;
}
while(!Character.isLetterOrDigit(s.charAt(right)) && right > left) {
right--;
}
if(Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/backtracking/GenerateParentheses.java | leetcode/backtracking/GenerateParentheses.java | //Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
//
//For example, given n = 3, a solution set is:
//
//[
//"((()))",
//"(()())",
//"(())()",
//"()(())",
//"()()()"
//]
class GenerateParentheses {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
generateParenthesisRecursive(result, "", 0, 0, n);
return result;
}
public void generateParenthesisRecursive(List<String> result, String current, int open, int close, int n) {
if(current.length() == n * 2) {
result.add(current);
return;
}
if(open < n) {
generateParenthesisRecursive(result, current + "(", open + 1, close, n);
}
if(close < open) {
generateParenthesisRecursive(result, current + ")", open, close + 1, n);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/backtracking/LetterCombinationsOfAPhoneNumber.java | leetcode/backtracking/LetterCombinationsOfAPhoneNumber.java | // Given a digit string, return all possible letter combinations that the number could represent.
// A mapping of digit to letters (just like on the telephone buttons) is given below.
// 2 - abc
// 3 - def
// 4 - ghi
// 5 - jkl
// 6 - mno
// 7 - pqrs
// 8 - tuv
// 9 - wxyz
// Input:Digit string "23"
// Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class LetterCombinationsOfAPhoneNumber {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
if(digits == null || digits.length() == 0) {
return result;
}
String[] mapping = {
"0",
"1",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
letterCombinationsRecursive(result, digits, "", 0, mapping);
return result;
}
public void letterCombinationsRecursive(List<String> result, String digits, String current, int index, String[] mapping) {
if(index == digits.length()) {
result.add(current);
return;
}
String letters = mapping[digits.charAt(index) - '0'];
for(int i = 0; i < letters.length(); i++) {
letterCombinationsRecursive(result, digits, current + letters.charAt(i), index + 1, mapping);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/backtracking/AndroidUnlockPatterns.java | leetcode/backtracking/AndroidUnlockPatterns.java | // Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock patterns of the Android lock screen, which consist of minimum of m keys and maximum n keys.
// Rules for a valid pattern:
// Each pattern must connect at least m keys and at most n keys.
// All the keys must be distinct.
// If the line connecting two consecutive keys in the pattern passes through any other keys, the other keys must have previously selected in the pattern. No jumps through non selected key is allowed.
// The order of keys used matters.
// Explanation:
// | 1 | 2 | 3 |
// | 4 | 5 | 6 |
// | 7 | 8 | 9 |
// Invalid move: 4 - 1 - 3 - 6
// Line 1 - 3 passes through key 2 which had not been selected in the pattern.
// Invalid move: 4 - 1 - 9 - 2
// Line 1 - 9 passes through key 5 which had not been selected in the pattern.
// Valid move: 2 - 4 - 1 - 3 - 6
// Line 1 - 3 is valid because it passes through key 2, which had been selected in the pattern
// Valid move: 6 - 5 - 4 - 1 - 9 - 2
// Line 1 - 9 is valid because it passes through key 5, which had been selected in the pattern.
// Example:
// Given m = 1, n = 1, return 9.
public class AndroidUnlockPatterns {
public int numberOfPatterns(int m, int n) {
//initialize a 10x10 matrix
int skip[][] = new int[10][10];
//initialize indices of skip matrix (all other indices in matrix are 0 by default)
skip[1][3] = skip[3][1] = 2;
skip[1][7] = skip[7][1] = 4;
skip[3][9] = skip[9][3] = 6;
skip[7][9] = skip[9][7] = 8;
skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip [7][3] = skip[6][4] = skip[4][6] = 5;
//initialize visited array
boolean visited[] = new boolean[10];
//initialize total number to 0
int totalNumber = 0;
//run DFS for each length from m to n
for(int i = m; i <= n; ++i) {
totalNumber += DFS(visited, skip, 1, i - 1) * 4; //1, 3, 7, and 9 are symmetric so multiply this result by 4
totalNumber += DFS(visited, skip, 2, i - 1) * 4; //2, 4, 6, and 8 are symmetric so multiply this result by 4
totalNumber += DFS(visited, skip, 5, i - 1); //do not multiply by 4 because 5 is unique
}
return totalNumber;
}
int DFS(boolean visited[], int[][] skip, int current, int remaining) {
//base cases
if(remaining < 0) {
return 0;
}
if(remaining == 0) {
return 1;
}
//mark the current node as visited
visited[current] = true;
//initialize total number to 0
int totalNumber = 0;
for(int i = 1; i <= 9; ++i) {
//if the current node has not been visited and (two numbers are adjacent or skip number has already been visited)
if(!visited[i] && (skip[current][i] == 0 || visited[skip[current][i]])) {
totalNumber += DFS(visited, skip, i, remaining - 1);
}
}
//mark the current node as not visited
visited[current] = false;
//return total number
return totalNumber;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/backtracking/GeneralizedAbbreviation.java | leetcode/backtracking/GeneralizedAbbreviation.java | // Write a function to generate the generalized abbreviations of a word.
// Example:
// Given word = "word", return the following list (order does not matter):
// ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
public class GeneralizedAbbreviation {
public List<String> generateAbbreviations(String word) {
List<String> result = new ArrayList<String>();
backtrack(result, word, 0, "", 0);
return result;
}
void backtrack(List result, String word, int position, String current, int count) {
if(position == word.length()) {
if(count > 0) {
current += count;
}
result.add(current);
} else {
backtrack(result, word, position + 1, current, count + 1);
backtrack(result, word, position + 1, current + (count > 0 ? count : "") + word.charAt(position), 0);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/backtracking/Permutations.java | leetcode/backtracking/Permutations.java | //Given a collection of distinct 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],
//[3,2,1]
//]
class Permutations {
public List<List<Integer>> permute(int[] nums) {
LinkedList<List<Integer>> result = new LinkedList<List<Integer>>();
result.add(new ArrayList<Integer>());
for (int n: nums) {
int size = result.size();
while(size > 0) {
List<Integer> current = result.pollFirst();
for (int i = 0; i <= current.size(); i++) {
List<Integer> temp = new ArrayList<Integer>(current);
temp.add(i, n);
result.add(temp);
}
size--;
}
}
return result;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/breadth-first-search/PacificAtlanticWaterFlow.java | leetcode/breadth-first-search/PacificAtlanticWaterFlow.java | // Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.
// Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
// Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
// Note:
// The order of returned grid coordinates does not matter.
// Both m and n are less than 150.
// Example:
// Given the following 5x5 matrix:
// Pacific ~ ~ ~ ~ ~
// ~ 1 2 2 3 (5) *
// ~ 3 2 3 (4) (4) *
// ~ 2 4 (5) 3 1 *
// ~ (6) (7) 1 4 5 *
// ~ (5) 1 1 2 4 *
// * * * * * Atlantic
// Return:
// [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
public class PacificAtlanticWaterFlow {
public List<int[]> pacificAtlantic(int[][] matrix) {
List<int[]> result = new LinkedList<>();
//error checking
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
int n = matrix.length;
int m = matrix[0].length;
boolean[][] pacific = new boolean[n][m];
boolean[][] atlantic = new boolean[n][m];
for(int i = 0; i < n; i++) {
dfs(matrix, pacific, Integer.MIN_VALUE, i, 0);
dfs(matrix, atlantic, Integer.MIN_VALUE, i, m - 1);
}
for(int i = 0; i < m; i++) {
dfs(matrix, pacific, Integer.MIN_VALUE, 0, i);
dfs(matrix, atlantic, Integer.MIN_VALUE, n - 1, i);
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(pacific[i][j] && atlantic[i][j]) {
result.add(new int[] {i, j});
}
}
}
return result;
}
public void dfs(int[][] matrix, boolean[][] visited, int height, int x, int y) {
int n = matrix.length;
int m = matrix[0].length;
if(x < 0 || x >= n || y < 0 || y >= m || visited[x][y] || matrix[x][y] < height) {
return;
}
visited[x][y] = true;
dfs(matrix, visited, matrix[x][y], x + 1, y);
dfs(matrix, visited, matrix[x][y], x - 1, y);
dfs(matrix, visited, matrix[x][y], x, y + 1);
dfs(matrix, visited, matrix[x][y], x, y - 1);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/breadth-first-search/CloneGraph.java | leetcode/breadth-first-search/CloneGraph.java | // Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
// OJ's undirected graph serialization:
// Nodes are labeled uniquely.
// We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
// As an example, consider the serialized graph {0,1,2#1,2#2,2}.
// The graph has a total of three nodes, and therefore contains three parts as separated by #.
// First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
// Second node is labeled as 1. Connect node 1 to node 2.
// Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
// Visually, the graph looks like the following:
// 1
// / \
// / \
// 0 --- 2
// / \
// \_/
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class CloneGraph {
public HashMap<Integer, UndirectedGraphNode> map = new HashMap<Integer, UndirectedGraphNode>();
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null) {
return null;
}
if(map.containsKey(node.label)) {
return map.get(node.label);
}
UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
map.put(newNode.label, newNode);
for(UndirectedGraphNode neighbor : node.neighbors) {
newNode.neighbors.add(cloneGraph(neighbor));
}
return newNode;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/breadth-first-search/ShortestDistanceFromAllBuildings.java | leetcode/breadth-first-search/ShortestDistanceFromAllBuildings.java | // You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:
// Each 0 marks an empty land which you can pass by freely.
// Each 1 marks a building which you cannot pass through.
// Each 2 marks an obstacle which you cannot pass through.
// For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2):
// 1 - 0 - 2 - 0 - 1
// | | | | |
// 0 - 0 - 0 - 0 - 0
// | | | | |
// 0 - 0 - 1 - 0 - 0
// The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7.
// Note:
// There will be at least one building. If it is not possible to build such house according to the above rules, return -1.
public class Shortest {
public int shortestDistance(int[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) {
return -1;
}
final int[] shift = {0, 1, 0, -1, 0};
int rows = grid.length;
int columns = grid[0].length;
int[][] distance = new int[rows][columns];
int[][] reach = new int[rows][columns];
int numberOfBuildings = 0;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
if(grid[i][j] == 1) {
numberOfBuildings++;
Queue<int[]> queue = new LinkedList<int[]>();
queue.offer(new int[] {i, j});
boolean[][] visited = new boolean[rows][columns];
int relativeDistance = 1;
while(!queue.isEmpty()) {
int qSize = queue.size();
for(int q = 0; q < qSize; q++) {
int[] current = queue.poll();
for(int k = 0; k < 4; k++) {
int nextRow = current[0] + shift[k];
int nextColumn = current[1] + shift[k + 1];
if(nextRow >= 0 && nextRow < rows && nextColumn >= 0 && nextColumn < columns && grid[nextRow][nextColumn] == 0 && !visited[nextRow][nextColumn]) {
distance[nextRow][nextColumn] += relativeDistance;
reach[nextRow][nextColumn]++;
visited[nextRow][nextColumn] = true;
queue.offer(new int[] {nextRow, nextColumn});
}
}
}
relativeDistance++;
}
}
}
}
int shortest = Integer.MAX_VALUE;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
if(grid[i][j] == 0 && reach[i][j] == numberOfBuildings) {
shortest = Math.min(shortest, distance[i][j]);
}
}
}
return shortest == Integer.MAX_VALUE ? -1 : shortest;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/breadth-first-search/SymmetricTree.java | leetcode/breadth-first-search/SymmetricTree.java | // Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
// For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
// 1
// / \
// 2 2
// / \ / \
// 3 4 4 3
// But the following [1,2,2,null,3,null,3] is not:
// 1
// / \
// 2 2
// \ \
// 3 3
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class SymmetricTree {
public boolean isSymmetric(TreeNode root) {
if(root == null) {
return true;
}
return helper(root.left, root.right);
}
public boolean helper(TreeNode left, TreeNode right) {
if(left == null && right == null) {
return true;
}
if(left == null || right == null || left.val != right.val) {
return false;
}
return helper(left.right, right.left) && helper(left.left, right.right);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/breadth-first-search/WallsAndGates.java | leetcode/breadth-first-search/WallsAndGates.java | // You are given a m x n 2D grid initialized with these three possible values.
// -1 - A wall or an obstacle.
// 0 - A gate.
// INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
// Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.
// For example, given the 2D grid:
// INF -1 0 INF
// INF INF INF -1
// INF -1 INF -1
// 0 -1 INF INF
// After running your function, the 2D grid should be:
// 3 -1 0 1
// 2 2 1 -1
// 1 -1 2 -1
// 0 -1 3 4
public class Solution {
public void wallsAndGates(int[][] rooms) {
//iterate through the matrix calling dfs on all indices that contain a zero
for(int i = 0; i < rooms.length; i++) {
for(int j = 0; j < rooms[0].length; j++) {
if(rooms[i][j] == 0) {
dfs(rooms, i, j, 0);
}
}
}
}
void dfs(int[][] rooms, int i, int j, int distance) {
//if you have gone out of the bounds of the array or you have run into a wall/obstacle, return
// room[i][j] < distance also ensure that we do not overwrite any previously determined distance if it is shorter than our current distance
if(i < 0 || i >= rooms.length || j < 0 || j >= rooms[0].length || rooms[i][j] < distance) {
return;
}
//set current index's distance to distance
rooms[i][j] = distance;
//recurse on all adjacent neighbors of rooms[i][j]
dfs(rooms, i + 1, j, distance + 1);
dfs(rooms, i - 1, j, distance + 1);
dfs(rooms, i, j + 1, distance + 1);
dfs(rooms, i, j - 1, distance + 1);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/breadth-first-search/RemoveInvalidParentheses.java | leetcode/breadth-first-search/RemoveInvalidParentheses.java | // Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
// Note: The input string may contain letters other than the parentheses ( and ).
// Examples:
// "()())()" -> ["()()()", "(())()"]
// "(a)())()" -> ["(a)()()", "(a())()"]
// ")(" -> [""]
public class RemoveInvalidParentheses {
public List<String> removeInvalidParentheses(String s) {
List<String> result = new ArrayList<>();
remove(s, result, 0, 0, new char[]{'(', ')'});
return result;
}
public void remove(String s, List<String> result, int last_i, int last_j, char[] par) {
for (int stack = 0, i = last_i; i < s.length(); i++) {
if (s.charAt(i) == par[0]) {
stack++;
}
if (s.charAt(i) == par[1]) {
stack--;
}
if (stack >= 0) {
continue;
}
for (int j = last_j; j <= i; j++) {
if (s.charAt(j) == par[1] && (j == last_j || s.charAt(j - 1) != par[1])) {
remove(s.substring(0, j) + s.substring(j + 1, s.length()), result, i, j, par);
}
}
return;
}
String reversed = new StringBuilder(s).reverse().toString();
if (par[0] == '(') {
// finished left to right
remove(reversed, result, 0, 0, new char[]{')', '('});
} else {
// finished right to left
result.add(reversed);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/breadth-first-search/BinaryTreeLevelOrderTraversal.java | leetcode/breadth-first-search/BinaryTreeLevelOrderTraversal.java | // Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
// For example:
// Given binary tree [3,9,20,null,null,15,7],
// 3
// / \
// 9 20
// / \
// 15 7
// return its level order traversal as:
// [
// [3],
// [9,20],
// [15,7]
// ]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinarySearchTreeLevelOrderTraversal {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
List<Integer> tempList = new ArrayList<Integer>();
tempList.add(root.val);
result.add(tempList);
while(!queue.isEmpty()) {
Queue<TreeNode> currentLevel = new LinkedList<TreeNode>();
List<Integer> list = new ArrayList<Integer>();
while(!queue.isEmpty()) {
TreeNode current = queue.remove();
if(current.left != null) {
currentLevel.add(current.left);
list.add(current.left.val);
}
if(current.right != null) {
currentLevel.add(current.right);
list.add(current.right.val);
}
}
if(list.size() > 0) {
result.add(list);
}
queue = currentLevel;
}
return result;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/sort/MeetingRoomsII.java | leetcode/sort/MeetingRoomsII.java | // Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.
// For example,
// Given [[0, 30],[5, 10],[15, 20]],
// return 2.
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class MeetingRoomsII {
public int minMeetingRooms(Interval[] intervals) {
int[] starts = new int[intervals.length];
int[] ends = new int[intervals.length];
for(int i=0; i<intervals.length; i++) {
starts[i] = intervals[i].start;
ends[i] = intervals[i].end;
}
Arrays.sort(starts);
Arrays.sort(ends);
int rooms = 0;
int endsItr = 0;
for(int i=0; i<starts.length; i++) {
if(starts[i]<ends[endsItr]) {
rooms++;
} else {
endsItr++;
}
}
return rooms;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/sort/MeetingRooms.java | leetcode/sort/MeetingRooms.java | // Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.
// For example,
// Given [[0, 30],[5, 10],[15, 20]],
// return false.
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class MeetingRooms {
public boolean canAttendMeetings(Interval[] intervals) {
if(intervals == null) {
return false;
}
// Sort the intervals by start time
Arrays.sort(intervals, new Comparator<Interval>() {
public int compare(Interval a, Interval b) { return a.start - b.start; }
});
for(int i = 1; i < intervals.length; i++) {
if(intervals[i].start < intervals[i - 1].end) {
return false;
}
}
return true;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/trie/WordSquares.java | leetcode/trie/WordSquares.java | // Given a set of words (without duplicates), find all word squares you can build from them.
// A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).
// For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically.
// b a l l
// a r e a
// l e a d
// l a d y
// Note:
// There are at least 1 and at most 1000 words.
// All words will have the exact same length.
// Word length is at least 1 and at most 5.
// Each word contains only lowercase English alphabet a-z.
public class WordSquares {
public List<List<String>> wordSquares(String[] words) {
List<List<String>> ret = new ArrayList<List<String>>();
if(words.length==0 || words[0].length()==0) {
return ret;
}
Map<String, Set<String>> map = new HashMap<>();
int squareLen = words[0].length();
// create all prefix
for(int i=0;i<words.length;i++){
for(int j=-1;j<words[0].length();j++){
if(!map.containsKey(words[i].substring(0, j+1))) {
map.put(words[i].substring(0, j+1), new HashSet<String>());
}
map.get(words[i].substring(0, j+1)).add(words[i]);
}
}
helper(ret, new ArrayList<String>(), 0, squareLen, map);
return ret;
}
public void helper(List<List<String>> ret, List<String> cur, int matched, int total, Map<String, Set<String>> map){
if(matched == total) {
ret.add(new ArrayList<String>(cur));
return;
}
// build search string
StringBuilder sb = new StringBuilder();
for(int i=0;i<=matched-1;i++) {
sb.append(cur.get(i).charAt(matched));
}
// bachtracking
Set<String> cand = map.get(sb.toString());
if(cand==null) {
return;
}
for(String str:cand){
cur.add(str);
helper(ret, cur, matched+1, total, map);
cur.remove(cur.size()-1);
}
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/trie/AddAndSearchWordDataStructureDesign.java | leetcode/trie/AddAndSearchWordDataStructureDesign.java | // Design a data structure that supports the following two operations:
// void addWord(word)
// bool search(word)
// search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
// For example:
// addWord("bad")
// addWord("dad")
// addWord("mad")
// search("pad") -> false
// search("bad") -> true
// search(".ad") -> true
// search("b..") -> true
// Note:
// You may assume that all words are consist of lowercase letters a-z.
public class AddAndSearchWordDataStructure {
public class TrieNode {
public TrieNode[] children = new TrieNode[26];
public String item = "";
}
private TrieNode root = new TrieNode();
public void addWord(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.children[c - 'a'] == null) {
node.children[c - 'a'] = new TrieNode();
}
node = node.children[c - 'a'];
}
node.item = word;
}
public boolean search(String word) {
return match(word.toCharArray(), 0, root);
}
private boolean match(char[] chs, int k, TrieNode node) {
if (k == chs.length) {
return !node.item.equals("");
}
if (chs[k] != '.') {
return node.children[chs[k] - 'a'] != null && match(chs, k + 1, node.children[chs[k] - 'a']);
} else {
for (int i = 0; i < node.children.length; i++) {
if (node.children[i] != null) {
if (match(chs, k + 1, node.children[i])) {
return true;
}
}
}
}
return false;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/trie/ImplementTrie.java | leetcode/trie/ImplementTrie.java | // Implement a trie with insert, search, and startsWith methods.
// Note:
// You may assume that all inputs are consist of lowercase letters a-z.
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
class TrieNode {
HashMap<Character, TrieNode> map;
char character;
boolean last;
// Initialize your data structure here.
public TrieNode(char character) {
this.map = new HashMap<Character, TrieNode>();
this.character = character;
this.last = false;
}
}
public class ImplementTrie {
private TrieNode root;
public Trie() {
root = new TrieNode(' ');
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
current.map.put(c, new TrieNode(c));
}
current = current.map.get(c);
}
current.last = true;
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
if(current.last == true) {
return true;
} else {
return false;
}
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode current = root;
for(char c : prefix.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
return true;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/math/EncodeAndDecodeTinyURL.java | leetcode/math/EncodeAndDecodeTinyURL.java | //TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
//and it returns a short URL such as http://tinyurl.com/4e9iAk.
//
//Design the encode and decode methods for the TinyURL service. There is no restriction on how your
//encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL
//and the tiny URL can be decoded to the original URL.
public class EncodeAndDecodeTinyURL {
HashMap<String, String> map = new HashMap<String, String>();
String characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int count = 1;
public String getKey() {
String key = "";
while(count > 0) {
count--;
key += characters.charAt(count);
count /= characters.length();
}
return key;
}
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String key = getKey();
map.put(key, longUrl);
count++;
return "http://tinyurl.com/" + key;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return map.get(shortUrl.replace("http://tinyurl.com/", ""));
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/math/PlusOne.java | leetcode/math/PlusOne.java | //Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
//
//The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
//
//You may assume the integer does not contain any leading zero, except the number 0 itself.
//
//Example 1:
//
//Input: [1,2,3]
//Output: [1,2,4]
//Explanation: The array represents the integer 123.
//Example 2:
//
//Input: [4,3,2,1]
//Output: [4,3,2,2]
//Explanation: The array represents the integer 4321.
class Solution {
public int[] plusOne(int[] digits) {
for(int i = digits.length - 1; i >= 0; i--) {
if(digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] result = new int[digits.length + 1];
result[0] = 1;
return result;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/math/BulbSwitcher.java | leetcode/math/BulbSwitcher.java | //There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.
//Example:
//Given n = 3.
//At first, the three bulbs are [off, off, off].
//After first round, the three bulbs are [on, on, on].
//After second round, the three bulbs are [on, off, on].
//After third round, the three bulbs are [on, off, off].
//So you should return 1, because there is only one bulb is on.
class BulbSwitcher {
public int bulbSwitch(int n) {
return (int)Math.sqrt(n);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/math/AddDigits.java | leetcode/math/AddDigits.java | //Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
//For example:
//Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
//Follow up:
//Could you do it without any loop/recursion in O(1) runtime?
class AddDigits {
public int addDigits(int num) {
while(num >= 10) {
int temp = 0;
while(num > 0) {
temp += num % 10;
num /= 10;
}
num = temp;
}
return num;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/math/PoorPigs.java | leetcode/math/PoorPigs.java | //There are 1000 buckets, one and only one of them contains poison, the rest are filled with water.
//They all look the same. If a pig drinks that poison it will die within 15 minutes. What is the
//minimum amount of pigs you need to figure out which bucket contains the poison within one hour.
//Answer this question, and write an algorithm for the follow-up general case.
//Follow-up:
//If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x)
//you need to figure out the "poison" bucket within p minutes? There is exact one bucket with poison.
class PoorPigs {
public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
int numPigs = 0;
while (Math.pow(minutesToTest / minutesToDie + 1, numPigs) < buckets) {
numPigs++;
}
return numPigs;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/math/PowerOfTwo.java | leetcode/math/PowerOfTwo.java | //Given an integer, write a function to determine if it is a power of two.
//
//Example 1:
//
//Input: 1
//Output: true
//Example 2:
//
//Input: 16
//Output: true
//Example 3:
//
//Input: 218
//Output: false
class PowerOfTwo {
public boolean isPowerOfTwo(int n) {
long i = 1;
while(i < n) {
i <<= 1;
}
return i == n;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/math/PalindromeNumber.java | leetcode/math/PalindromeNumber.java | //Determine whether an integer is a palindrome. Do this without extra space.
class PalindromeNumber {
public boolean isPalindrome(int x) {
if(x < 0) {
return false;
}
int num = x;
int reversed = 0;
while(num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
return x == reversed;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/binary-search/ClosestBinarySearchTreeValue.java | leetcode/binary-search/ClosestBinarySearchTreeValue.java | // Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
// Note:
// Given target value is a floating point.
// You are guaranteed to have only one unique value in the BST that is closest to the target.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class ClosestBinarySearchTreeValue {
public int closestValue(TreeNode root, double target) {
int value = root.val;
TreeNode child = root.val < target ? root.right : root.left;
if(child == null) {
return value;
}
int childValue = closestValue(child, target);
return Math.abs(value - target) < Math.abs(childValue - target) ? value : childValue;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/binary-search/GuessNumberHigherOrLower.java | leetcode/binary-search/GuessNumberHigherOrLower.java | // We are playing the Guess Game. The game is as follows:
// I pick a number from 1 to n. You have to guess which number I picked.
// Every time you guess wrong, I'll tell you whether the number is higher or lower.
// You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
// -1 : My number is lower
// 1 : My number is higher
// 0 : Congrats! You got it!
// Example:
// n = 10, I pick 6.
// Return 6.
public class GuessNumberHigherOrLower extends GuessGame {
public int guessNumber(int n) {
int left = 1;
int right = n;
while(left <= right) {
int mid = left + (right - left) / 2;
if(guess(mid) == 0) {
return mid;
} else if(guess(mid) > 0) {
left = mid + 1;
} else {
right = mid;
}
}
return -1;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/binary-search/FirstBadVersion.java | leetcode/binary-search/FirstBadVersion.java | // You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
// Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
// You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class FirstBadVersion extends VersionControl {
public int firstBadVersion(int n) {
int start = 1;
int end = n;
while(start < end) {
int mid = start + (end - start) / 2;
if(!isBadVersion(mid)) {
start = mid + 1;
} else {
end = mid;
}
}
return start;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/binary-search/SquareRootX.java | leetcode/binary-search/SquareRootX.java | // Implement int sqrt(int x).
// Compute and return the square root of x.
public class Solution {
public int mySqrt(int x) {
if(x == 0) {
return 0;
}
int left = 1;
int right = x;
while(left <= right) {
int mid = left + (right - left) / 2;
if(mid == x / mid) {
return mid;
} else if(mid > x / mid) {
right = mid - 1;
} else if(mid < x / mid) {
left = mid + 1;
}
}
return right;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/binary-search/PowerOfXToTheN.java | leetcode/binary-search/PowerOfXToTheN.java | // Implement pow(x, n).
public class PowerOfXToTheN {
public double myPow(double x, int n) {
if(n == 0) {
return 1;
}
if(Double.isInfinite(x)) {
return 0;
}
if(n < 0) {
n = -n;
x = 1 / x;
}
return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/linked-list/LinkedListCycle.java | leetcode/linked-list/LinkedListCycle.java | //Given a linked list, determine if it has a cycle in it.
//Follow up:
//Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null && fast != slow) {
slow = slow.next;
fast = fast.next.next;
}
return fast == slow;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/linked-list/ReverseLinkedList.java | leetcode/linked-list/ReverseLinkedList.java | // Reverse a singly linked list.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
if(head == null) {
return head;
}
ListNode newHead = null;
while(head != null) {
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/linked-list/MergeKSortedLists.java | leetcode/linked-list/MergeKSortedLists.java | // Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class MergeKSortedLists {
public ListNode mergeKLists(ListNode[] lists) {
if (lists==null||lists.length==0) {
return null;
}
PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>(){
@Override
public int compare(ListNode o1,ListNode o2){
if (o1.val<o2.val) {
return -1;
} else if (o1.val==o2.val) {
return 0;
} else {
return 1;
}
}
});
ListNode dummy = new ListNode(0);
ListNode tail=dummy;
for (ListNode node:lists) {
if (node!=null) {
queue.add(node);
}
}
while (!queue.isEmpty()){
tail.next=queue.poll();
tail=tail.next;
if (tail.next!=null) {
queue.add(tail.next);
}
}
return dummy.next;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/linked-list/PlusOneLinkedList.java | leetcode/linked-list/PlusOneLinkedList.java | // Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.
// You may assume the integer do not contain any leading zero, except the number 0 itself.
// The digits are stored such that the most significant digit is at the head of the list.
// Example:
// Input:
// 1->2->3
// Output:
// 1->2->4
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class PlusOneLinkedList {
public ListNode plusOne(ListNode head) {
if(plusOneRecursive(head) == 0) {
return head;
} else {
ListNode newHead = new ListNode(1);
newHead.next = head;
return newHead;
}
}
private int plusOneRecursive(ListNode head) {
if(head == null) {
return 1;
}
int carry = plusOneRecursive(head.next);
if(carry == 0) {
return 0;
}
int value = head.val + 1;
head.val = value % 10;
return value/10;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/linked-list/AddTwoNumbers.java | leetcode/linked-list/AddTwoNumbers.java | // You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
// You may assume the two numbers do not contain any leading zero, except the number 0 itself.
// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
// Output: 7 -> 0 -> 8
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class AddTwoNumbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode current1 = l1;
ListNode current2 = l2;
ListNode head = new ListNode(0);
ListNode currentHead = head;
int sum = 0;
while(current1 != null || current2 != null) {
sum /= 10;
if(current1 != null) {
sum += current1.val;
current1 = current1.next;
}
if(current2 != null) {
sum += current2.val;
current2 = current2.next;
}
currentHead.next = new ListNode(sum % 10);
currentHead = currentHead.next;
}
if(sum / 10 == 1) {
currentHead.next = new ListNode(1);
}
return head.next;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/linked-list/DeleteNodeInALinkedList.java | leetcode/linked-list/DeleteNodeInALinkedList.java | // Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
// Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class DeleteNodeInALinkedList {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/linked-list/PalindromeLinkedList.java | leetcode/linked-list/PalindromeLinkedList.java | /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class PalindromeLinkedList {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) {
return true;
}
Stack<Integer> stack = new Stack<Integer>();
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null) {
stack.push(slow.val);
fast = fast.next.next;
slow = slow.next;
}
if(fast != null) {
slow = slow.next;
}
while(slow != null) {
if(stack.pop() != slow.val) {
return false;
}
slow = slow.next;
}
return true;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/bit-manipulation/HammingDistance.java | leetcode/bit-manipulation/HammingDistance.java | // The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
// Given two integers x and y, calculate the Hamming distance.
// Note:
// 0 ≤ x, y < 2^31.
// Example:
// Input: x = 1, y = 4
// Output: 2
// Explanation:
// 1 (0 0 0 1)
// 4 (0 1 0 0)
// ↑ ↑
// The above arrows point to positions where the corresponding bits are different.
public class HammingDistance {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
kdn251/interviews | https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/leetcode/bit-manipulation/CountingBits.java | leetcode/bit-manipulation/CountingBits.java | // Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
// Example:
// For num = 5 you should return [0,1,1,2,1,2].
public class CountingBits {
public int[] countBits(int num) {
int[] bits = new int[num + 1];
bits[0] = 0;
for(int i = 1; i <= num; i++) {
bits[i] = bits[i >> 1] + (i & 1);
}
return bits;
}
}
| java | MIT | 03fdcb2703ce72dc0606748733d0c13f09d41d21 | 2026-01-04T14:45:56.686758Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.