Latest Data Structures
Latest Data Structures
com/questions/16958390/difference-between-head-and-head-
pointers-in-c
sSelection Sort has O(n2) time complexity making it inefficient on large lists
}
}
Find the minimum element in the remainder of the array for this we do swap outside the inner
loop
public class BubbleSort {
}
}
Sum of digits
While(n!=0)
Remainder = n % 10
Sum = sum + remainder
N = n / 10
Balancing Paranthesis
https://www.youtube.com/watch?v=QZOLb0xHB_Q
import java.util.Stack;
}
Associativity happens when both the operators of same precedence are
there we evaluate from left to right
}
public void pop() {
top = top-1;
}
To return the top element arr[top]
To check if stack is empty if(top == -1) empty
Cannot pop if top ==-1
Bubble Sort
for (int i = 0 ; i <a.length-1 ; i++){
for (int j =i+1 ; j <a.length ; j++){
if(a[j] < a[i] ) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
Selection Sort
for(i=0;i<a.length-1;i++) {
int min = i ;
for ( j = i+1 ; j<a.length; j++){
if (a[j] < a[min]){
min = j;
}
}
if (min !=i) {
int temp = a[i];
a[i] = a[min];
a[min]= temp;
}
}
Deferencing of pointer
*p returns the value at the address it is pointing to .
Int a = 5
Int *p
P = &a
Print *p // Value at address of a = 5
P address
*p = value at address
Int a = 10
Int *p = &a; // p = address
*p = value at address returns 10
Call by value
void increment(int x) {
x = x+1;
}
int main() {
int x = 20;
increment(x);
printf("value of a %d\n",x);
}
int x = 20;
increment(&x); // Passing address of x
printf("value of a %d\n",x);
}
}
}
Sum of digits
While(n!=0)
Remainder = remainder % 10
Sum = sum + remainder
N = n / 10
}
public void pop() {
top = top-1;
}
To return the top element arr[top]
To check if stack is empty if(top == -1) empty
Cannot pop if top ==-1
Bubble Sort
for (int i = 0 ; i <a.length-1 ; i++){
for (int j =i+1 ; j <a.length ; j++){
if(a[j] < a[i] ) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
Selection Sort
for(i=0;i<a.length-1;i++) {
int min = i ;
for ( j = i+1 ; j<a.length; j++){
if (a[j] < a[min]){
min = j;
}
}
if (min !=i) {
int temp = a[i];
a[i] = a[min];
a[min]= temp;
}
}
Counting Change
public class CountingChange {
return val;
}
}
http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-
palindromic-subsequence/
Overlapping subproblems
Time Complexity of DP O(n^2)
Dynamic Programming
http://ajeetsingh.org/2013/11/12/find-longest-palindrome-sub-
sequence-in-a-string/
public class LongestPalindromeSubstring {
String s = "forgeeksskeegfor";
char[] c = s.toCharArray();
LongestPalindromeSubstring lps = new LongestPalindromeSubstring();
System.out.println(lps.lps(c,0 ,c.length-1));
}
Dynamic Programming
public static int getLongestPalindromicSubSequenceSize(String source){
int n = source.length();
int[][] LP = new int[n][n];
The worst-case running time of any correct algorithm must be at least O(N), where N is the length of
the string. This is because the algorithm cannot be correct unless it can verify whether the entire
string is a palindrome (because in that case it is itself the longest palindromic substring), and it is not
possible to conclude that a string is palindromic unless every character is examined.
http://stevekrenzel.com/articles/longest-palnidrome
For odd length palindrome fix a center at the middle .
For even length palindrome fix two centers low and high and expand
in both directions
.
Suffix tree is compressed trie of all the suffixes as keys and their
positions as values .
http://www.geeksforgeeks.org/pattern-searching-set-8-suffix-tree-
introduction/
A generalized suffix tree is a suffix tree made for a set of words instead of only for a
single word. It represents all suffixes from this set of words. Each word must be
terminated by a different termination symbol or word.
else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}
https://www.youtube.com/watch?v=P-mMvhfJhu8
#include<stdio.h>
int fib(int n)
{
/* Declare an array to store fibonacci numbers. */
int f[n+1];
int i;
return f[n];
}
int main ()
{
int n = 9;
printf("%d", fib(n));
getchar();
return 0;
}
http://web.engr.illinois.edu/~jeffe/teaching/algorithms/notes/05-
dynprog.pdf
towers of Hanoi
1) Move n-1 disks from Origin to intermediate
Permutations
public class Permuatitions {
} else {
for(int j = k;j<n;j++) { // Fixing the first spot
swap(k,j);
perm(a,k+1,n);
swap(k,j); // swap undo so that the elements remain
same for next iteration
}
}
return n;
}
public void swap(int k ,int n) {
char temp = a[k];
a[k]=a[n];
a[n]=temp;
}
http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html
http://learnprogramming.machinesentience.com/java_permutations_recursion/
Queue
1) Push or Enqueue
2) Pop or dequeue
3) Is empty
4) Full
5) Peek or Front
Insertion and deletion should happen at opposite ends . Insert and rear and remove at front
Time complexity is O(1)
}
public void enQueue(int x) {
if (isFull()==true ) return ;
else if (isEmpty() == true) {
rear = front = 0;
} else {
rear = rear+1;
}
a[rear] =x;
public void deQueue() {
if (isEmpty() == true) return;
else if (front == rear ) {
rear = front = -1;
} else {
front = front+1;
}
}
q.enQueue(6);
q.enQueue(7);
q.enQueue(8);
q.deQueue();
System.out.println("rear " + rear + front);
q.enQueue(10);
for(int i=0;i<5;i++ )
System.out.println(a[i]);
}
Binary tree is a tree that is has zero nodes or at the most every node has at the most two
children
The maximum number of nodes in a binary tree of depth k is 2^k-1
Binary search tree is a binary tree . It may be empty . When it is not empty , it has to satisfy
three conditions :-
Tmp2 = malloc
Tmp2->next = tmp->next
Tmp->next = tmp2
if (n==1) {
head = temp1->next;
free (temp1);
else {
for (int i = 0; i<n-2;i++){
temp1 = temp1->next;
}
Struct node *temp2 = malloc
temp2 = temp1->next;
temp1->next = temp2->next;
free(temp2);
}
if(temp->next==NULL) {
temp->prev->next=NULL;
} else {
temp->next->prev=temp->prev;
temp->prev->next=temp->next;
} free(temp);
Top ;
Temp = malloc
Temp->data = 5
Temp->next = top
Top = temp // Update top
Delete Last Node in a Linked List ( De Queue )
http://www.mytechinterviews.com/singly-linked-list-delete-node
You are given a pointer to a node (not the tail node) in a singly linked list. Delete that node from the
linked list
Insert in a DLL :-
While(tmp!=null) {
tmp = tmp->next
}
Tmp2 = malloc
Tmp2->data = data
Tmp2->next = tmp->next
Tmp2->prev = tmp
Tmp->next->prev = tmp2
Tmp->next = tmp2
Circular Linked List : http://codepad.org/XkdvFimF
Here :-
while(tmp->next!=head) {
tmp = tmp->next;
}
Last = tmp->next;
Last = malloc;
Last->data = data
Last->next = head // If insert at end
head = last // Update head if insert in the beginning
tmp->next = head // Update address of last node to head create link between last
and head
if (head->data == key) {
struct node* temp = head;
head= head->next;
free(temp);
}
else {
n[hole] = n[hole-1];
hole = hole-1;
}
n[hole] = temp;
}
for(int i=0 ; i<=5 ; i++)
System.out.println(n[i]);
}
Mergre Sort :-
int l = left.length;
int r = right.length;
int v = a.length;
}
while ( j < r ) {
a[k] = right[j];
k++;
j++;
int n = length;
if(n < 2) return;
int mid = n/2;
Merge(right,n-mid);
Merge(left,mid);
MergeSort(a, left, right);
O(n logn) Time complexity of Merge Sort Worst Case . Space Complexity O(n)
{Not IN Place algorithm}
Quick Sort
http://www.algolist.net/Al gorithms/Sorting/Quicksort
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
return i;
}
Heap is a nearly complete binary tree . Nearly complete binary tree is at the
lowest level not completely filled
Parent = floor[i/2]
Left = 2i ; right = 2i+1
Max heap If A[Parent] >= A[i] . Root will have max value in Max Heap
Min Heap If A[Parent] <= A[i] . min element is ROOT in min head
Heapify:-
http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Sorting/heapSort.ht
m
Heap Sort :-
1) Create a max heap tree
2) Replace the root node with the leaf element and add the root element to the
array
http://www.sanfoundry.com/java-program-implement-heap-sort/
public static void maxheap(int arr[], int i)
{
int left = 2*i ;
int right = 2*i + 1;
int max = i;
if (left <= N && arr[left] > arr[i])
max = left;
if (right <= N && arr[right] > arr[max])
max = right;
if (max != i)
{
swap(arr, i, max);
maxheap(arr, max);
}
}
public static void heapify(int arr[])
{
N = arr.length-1;
for (int i = N/2; i >= 0; i--)
maxheap(arr, i);
}
Build Heap
For(int i=n;i>1;i++)
Swap(a[1],a[n])
N=n-1;
maxheap(arr,1)
https://www.youtube.com/watch?v=18_91wFdcW8
for i -> n
stack.push(a[i]
for i->n
a[i] = stack.top
stack.pop
Reverse recursively
if(node->next == null) {
return head = node;
}
reverse(node->next);
curr = node->next;
curr->next = node;
node->next = null;
Reverse a Linked List Using stack
while(curr != NULL)
{
Traverse linked list using two pointers. Move one pointer by one and other pointer by
two. When the fast pointer reaches end slow pointer will reach middle of the linked
list.
if (head!=NULL)
{
while (fast_ptr != NULL && fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
slow_ptr = slow_ptr->next;
}
printf("The middle element is [%d]\n\n", slow_ptr->data);
}
}
http://stackoverflow.com/questions/10275587/finding-loop-in-a-singly-linked-list
Shell Sort is same as Insertion sort but go back (i.e hole--) by h-sort
Huffman Coding :
It uses Lossless Data Compression
Variable Length Encoding Frequently appearing characters are given shorter code
and less frequent are given larger code
Prefix free coding
Each ASCII character takes 8 bits to represent so to reduce that size we use
Huffman Encoding
1) Select the words with lowest frequency first and form a binary tree
2) Mark the elements on the left side as 0 and right as 1
3) No code should be prefix of other code
1.1.1 Problem :-
Get the maximum value without exceeding the total weight W
return K[n][W];
https://www.youtube.com/watch?v=1fDAOvgK11s
http://www.geeksforgeeks.org/dynamic-programming-set-10-0-1-knapsack-problem/
https://dzone.com/articles/knapsack-problem
N Queens
http://introcs.cs.princeton.edu/java/23recursion/Queens.java
if((a[i]==a[pos])||((abs(a[i]-a[pos])==abs(i-pos)))) //
Backtracking
if(a[i]==j)
printf("Q\t");
else
printf("*\t");
http://www.c-program-example.com/2011/10/c-program-to-solve-n-queens-problem.html
Time Complexity of Search in Binary Tree is O(logn) and also its same for
insertion and deletion
https://gist.github.com/mycodeschool/44e1a9183ab0e931f729
if(root = NULL)
root-> data = data
root-> left = root->right = NULL
} else if(data <= root->data) {
Tmp = malloc;
root->left = tmp
tmp->left=tmp->right= NULL
} else (data > root->data) {
Tmp = malloc;
root->right = tmp;
tmp->left = tmp->right = data
root = root->left
}
return root->data
The process of visiting the node exactly once in any order is called Tree
Traversal
http://algorithmsandme.blogspot.in/2014/02/tree-traversal-without-recursion-
using.html#.VD5Q5vmSwTA
if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left);
Iterative PreOrder
if (root == NULL)
return;
/* Note that right child is pushed first so that left is processed first */
while (nodeStack.empty() == false)
{
// Pop the top item from stack and print it
struct node *node = nodeStack.top();
printf ("%d ", node->data);
nodeStack.pop();
Stack.push(root)
while (!isEmpty(s1))
{
// Pop an item from s1 and push it to s2
node = stack.top();
stack.pop();
stack2.push( node);
InOrder Stack
void inorder_stack(Node * root){
stack ms;
ms.top = -1;
Node * temp = root;
while(!is_empty(ms) || temp){
if(temp!=NULL){
stack.push( temp);
temp = temp->left;
}
else {
temp = stack.top();
stack.pop();
printf("%d ", temp->value);
temp = temp->right;
}
}
}
ListNode p1 = l1;
ListNode p2 = l2;
p = p.next;
}
if(p1 != null)
p.next = p1;
if(p2 != null)
p.next = p2;
return fakeHead.next;
}
}
Append the last n nodes of a linked list to the beginning of the list
eg: 1->2->3->4->5->6
if n=2
5->6->1->2->3->4
node *prepend(node * root, int k)
{
node *prev, *curr;
curr = root;
for (int i = 0; i < k; i++) {
curr = curr->next;
if (curr == NULL)
return NULL;
}
prev = root;
while (curr->next != NULL) {
curr = curr->next;
prev = prev->next;
}
curr->next = root;
root = prev->next;
prev->next = NULL;
return root;
}
Boundary Traversal
http://www.geeksforgeeks.org/boundary-traversal-of-binary-tree/
Temp = malloc
temp->data = root->data
temp->left = mirror(root->right)
temp->right = mirror(root->left)
return temp
/* base case */
if(root == NULL)
return true;
return res;
}
return false;
}
http://www.geeksforgeeks.org/foldable-binary-trees/
/*
Given two trees, return true if they are
structurally identical.
*/
int sameTree(struct node* a, struct node* b) {
// 1. both empty -> true
if (a==NULL && b==NULL) return(true);
____________________________________________
int isBST2(struct node* node) {
return(isBSTUtil(node, INT_MIN, INT_MAX));
}
/*
Returns true if the given tree is a BST and its
values are >= min and <= max.
*/
int isBSTUtil(struct node* node, int min, int max) {
if (node==NULL) return(true);
TC - O(n)
if(node->data > min && node->data < max && isbst(node->left,min,node->data) &&
isBST(node->right,node->data,max))
return true
Write a function to find 5th element from a singly linked List from the end(not from the head) in
one pass.
Take 2 pointers- move the first one past 5 nodes from the head and then start the second one at
the head. Keep advancing both the pointers one step at a time until the first pointer reaches the
last node when which the second will be pointing to the 5th node from the last.
Code :- Same as Append
node *prepend(node * root)
{
node *prev, *curr;
curr = root;
for (int i = 0; i < 5; i++) {
curr = curr->next;// Pointer will reach 5th element
if (curr == NULL)
return NULL;
}
prev = root;
while (curr->next != NULL) {
curr = curr->next;
prev = prev->next;
}
prev->data // data at 5th element
return root;
}
10->30->50->70->NULL
You are given pointer to node 50 and a new node having value 40. Can you inserte node 40
correctly in the list maintaining the ascending order?
pNew->next = p->next;
p->next = pNew;
p->val = 40; // pnew->val
pNew->val = 50; //p->val
Sorted:-
http://www.geeksforgeeks.org/remove-duplicates-from-a-sorted-linked-list/
while(curr->next!=NULL){
if(curr->next->data == curr->data) {
temp = curr->next->next;
curr->next = temp;
free(temp)
} else {
curr = curr->next
}
}
Tc :o(n)
http://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/
struct node *reverse (struct node *head, int k)
{
struct node* current = head;
struct node* next = NULL;
struct node* prev = NULL;
int count = 0;
}
Reverse every alternate K nodes in Linked List
if(head != NULL)
head->next = current;
http://www.dsalgo.com/2013/02/print-nodes-of-given-level.html
privatestaticvoidprintLevelofDepth(Nodea,intdepth)
{
if(a==null)
return;
if(depth==1)
{
System.out.println(a.value);
return;
}
printLevelofDepth(a.left,depth1);
printLevelofDepth(a.right,depth1);
}
{
if (root == NULL) return; // NULL check
http://www.careercup.com/question?id=22355666
x
https://www.cs.umd.edu/class/fall2009/cmsc451/lectures/Lec08-inversions.pdf
Time complexity
of n matrix multiplication is O(n^3) .
C[i][j] = c[i][j]+a[i][k]*b[k][j]
http://www.geeksforgeeks.org/strassens-matrix-multiplication/
FromMaster'sTheorem,timecomplexityofabovemethodisO(N3)
whichisunfortunatelysameastheabovenaivemethod.
http://prismoskills.appspot.com/lessons/Dynamic_Programming/Ch
apter_11__Egg_dropping_puzzle.jsp
So, we can find max droppings on each floor and find
minimum among them to arrive programatically at our
answer.
http://datagenetics.com/blog/july22012/index.html
/* If root->data is smaller than k2, then only we can get o/p keys
in right subtree */
if ( k2 > root->data )
Print(root->right, k1, k2);
}
O(NlogN) - space 2N
Assuming you have a binary tree which stores integers, count the
number of nodes whose value is lower than the value of its upper
nodes.
int[] a = { 1, 2, 3, 4, 0, 19, 1, 1, 2, 2, 3, 3, 2 };
int count = 1, max = 1;
for (int i = 1; i < a.length; i++) {
if (a[i] >= a[i - 1]) {
count++;
} else {
if (count > max) {
max = count;
}
count = 1;
}
}
System.out.println(max);
Here, count is the number of contiguous and sorted elements. We
increment it while we're on a continuous/increasing streak. Once this
streak breaks (else clause), we check if count is greater than max, our
variable for storing the maximum count: if it is, we set max to count. We
then set count back to 1, since in the else clause we know our streak has
ended and we'll need to start over.
}
//incase all numbers are unique.
if(freqValue == -1 && a.length>;0)
return a[0];
return freqValue;
}
1. add to map with number as the key and its frequency as the value O(n)
2. get the values from the map as list and do kth select algorithm O(log n);
Given an unsorted array of integers find a minimum number which is not present in array.
e.g -1 ,4, 5, -23,24 is array then answer should be -22.
O(n) complexity:-
int products_above[N];
p=1;
for(int i=N-1;i>=0;--i) {
products_above[i]=p;
p*=a[i];
}
Children-Sum Property
http://www.geeksforgeeks.org/check-for-children-sum-property-in-a-
binary-tree/
int isSumProperty(struct node* node)
{
/* left_data is left child data and right_data is for right child data*/
int left_data = 0, right_data = 0;
if(s.length() <= 1) {
continue;
}
if(isPalindrome(s)) {
System.out.println(s);
}
}
}
//System.out.println("IsPalindrome:" + s + "?");
StringBuilder sb = new StringBuilder(s);
String reverse = sb.reverse().toString();
//System.out.println("IsPalindrome Reverse:" + reverse + "?");
return reverse.equals(s)
O(n^3) complexity
Can also use Manachers algorithm
Design a system for finding the costliest element always
whenever we pick up an element from a box.(concept of
Max Heap)
while (!stack.isEmpty()) {
GraphNode curr = stack.pop();
// mark it as visited
set.add(curr);
}
if(node.right)
Queue.push(node.right);
}
}
return height;
Use two stacks . s1 and s2. For enqueue directly push into s1.
For dequeue , if s1 is not empty and s2 is empty pop elements from
s1 into s2 and pop the top element in s2
http://www.geeksforgeeks.org/queue-using-stacks/
Implement Stack using Queues
push(s,x)
1)Enqueuextoq1(assumingsizeofq1isunlimited).
pop(s)
1)Onebyonedequeueeverythingexceptthelastelement
fromq1andenqueuetoq2.
2)Dequeuethelastitemofq1,thedequeueditemis
result,storeit.
3)Swapthenamesofq1andq2
4)Returntheitemstoredinstep2.
//Swappingofnamesisdonetoavoidonemoremovementofall
elements
//fromq2toq1.
q.push(root)
q.push(null) // Null is pushed to mark end of level
maxSum=currSum=maxLevel=level=0
while (!q.isEmpty) {
temp = q.pop();
if (temp == null) {
if(currSum > maxSum) {
maxSum=currSum;
maxLevel=level;
}
currSum = 0;
if (!q.isEmpty) {
q.push(null);
level++
}
} else {
currSum += temp->data;
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);
}
Find max element in a binary tree
For searching an element if (data==temp->data) return 1;
Number of leaves in binary tree
if(!root->left && !root->right) count++;
Number of full nodes
if(root->left && root->right) count++;
Number of half nodes
If(!root->left && root->right || !root->right && root->left) count++
Sum of all nodes in binary tree
Sum += curr->data;
Return(root->data+Sum(root->left)+Sum(root+right));
If two tree traversals are given and one of them is Inorder then a
unique binary tree can be constructed.
Same BFS using queue , just push the element popped from queue into
stack
For that node delete left and right nodes and delete the root
Void deleteBinaryTree(node)
if (root == null) { return null;}
deleteroot(root->left);
deleteroot(root->righ
free(root);
MaxSumfromRoottoleaf
public void maxSum(Node root, int sum){
if(root!=null){
sum=sum+root.data;
if(sum>maxSum && root.left==null && root.right==null){
maxLeaf = root;
maxSum = sum;
}
// System.out.println("Sum " + sum);
maxSum(root.left,sum);
maxSum(root.right,sum);
}
Find existence of a path with a given sum :O(n) TC and sc
printArray(path, pathLen);
}
else {
// otherwise try both subtrees
printPathsRecur(node->left, path, pathLen);
printPathsRecur(node->right, path, pathLen);
Start with the root. Push root node to stack.
while(stack not empty) //i'll take top=top_of_stack
mark top as visited
if(top.left_node exists AND not_visited)
push(top.left_node)
else if(top.right_node exists AND not_visited)
push(top.right_node)
else //Leaf node
print stack
pop
http://cslibrary.stanford.edu/110/BinaryTrees.html
printLeaves(root->right);
}
}
Go to mid node
Reverse the right half
Compare it with the left half
return tNode;
}
buildTree(in,pre,0,n-1);
int search(char arr[], int strt, int end, char value)
{
int i;
for(i = strt; i <= end; i++)
{
if(arr[i] == value)
return i;
}
}
Radix Sort first mod by 10 and by 1 amd mod by 100 and by 10 till the max integer
value
Node at K distance
void printKDistant(node *root , int k)
{
if(root == NULL)
return;
if( k == 0 )
{
printf( "%d ", root->data );
return ;
}
else
{
printKDistant( root->left, k-1 ) ;
printKDistant( root->right, k-1 ) ;
}
Given a sorted array with only 0's and 1's.Count the
number of 0's. e.g: 0 0 0 0 1 1 Ans: 4.
if(high >=low) {
int mid = (low+high)/2;
//System.out.println(mid);
if(mid == 0 && a[mid]==0) {
return mid+1;
}
if((mid == 0 || a[mid-1]==0)&& a[mid]==1) {
return mid;
}
if (a[mid]==1) {
return returnCount(arr,low,mid-1);
} else {
return returnCount(arr,mid+1,high);
}
}
return -1;
}
if(count != 0) {
for(int j=0;j<count;j++) {
System.out.println(b[i] + " ");
}
}
map.remove(b[i]);
}
}
}
Given a sorted and rotated array, find if there is a pair with a given sum
l=0;
r=length-1
while (l != r)
{
// If we find a pair with sum x, we return true
if (arr[l] + arr[r] == x)
l++;
r--;
return true;
else if (arr[i] == 0)
{
max_ending_here = 1;
min_ending_here = 1;
}
else
{
int temp = max_ending_here;
max_ending_here = max (min_ending_here * arr[i], 1);
min_ending_here = temp * arr[i];
}
http://www.geeksforgeeks.org/maximum-product-subarray/
}
System.out.println(high_prod_3);
http://www.geeksforgeeks.org/find-the-element-that-appears-once-in-a-sorted-array/ - Ologn
http://ideone.com/Mos8Kl
http://www.geeksforgeeks.org/majority-element/ - O(n)
int maj_index = 0, count = 1;
int i;
for(i = 1; i < size; i++)
{
if(a[maj_index] == a[i])
count++;
else
count--;
if(count == 0)
{
maj_index = i;
count = 1;
}
}
Given an array of size n-1 whose entries are integers in the range [1,
n], find an integer that is missing. Use only O(1) space and treat the
input as read-only.
/* XOR the new bits with previous 'ones' to get all bits
appearing odd number of times
/* The common bits are those bits which appear third time
So these bits should not be there in both 'ones' and 'twos'.
common_bit_mask contains all these bits as 0, so that the bits can
be removed from 'ones' and 'twos'
/* Remove common bits (the bits that appear third time) from 'ones'
/* Remove common bits (the bits that appear third time) from 'twos'
return ones;
}
http://www.geeksforgeeks.org/find-the-element-that-appears-once/
A number is POT
n > 0 && (n & (n - 1) == 0)
Reverse A string
for(int i=0;i<a.length;i++) {
arr[a.length-i-1] = a[i]; }
Another way to reverse is swap first and last element and then increment pointer from starting
index and decrement pointer from last index
int i=0;
int j=n-1;
while (i<j) {
String temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
for(int k=0;k<=a.length-1;k++) {
System.out.println(a[k]);
}
http://www.geeksforgeeks.org/reverse-words-in-a-given-string/ - O(n)
while( *temp )
{
temp++;
if (*temp == '\0')
{
reverse(word_begin, temp-1);
}
else if(*temp == ' ')
{
reverse(word_begin, temp-1);
word_begin = temp+1;
}
}
/*STEP 2 of the above algorithm */
reverse(s, temp-1)
int count=0;
int i=0,j;
int l = str.length();
while(i<l)
{
count=1;
j=i;
count++;
j++;
i=j+1;
return 0;
Smallest Number
Remove characters from the first string which are present in the
second string
http://www.crazyforcode.com/algorithm/
http://www.geeksforgeeks.org/find-union-and-intersection-of-two-unsorted-arrays/
http://www.geeksforgeeks.org/find-a-fixed-point-in-a-given-array/
int count=0;
int n=100;
for(int i=5;i<=n;i=i*5) {
count += n/i;
}
The total distance form root to leaf in heap sort in O(logn) . So heap sort is O(nlogn) O(n)
Is from Build_Max_heap
ReturnMaxElementfromHeapSort
Max=a[1]
a[1]=a[length]
length=length1
max_heapify(array,1)
IncreaseKey
A[i]=key
While(I > 1 && a[i/2] < a[i] ) // Parent is less than he node
Swap(a[i],a[i/2])
I=i/2
TC =O(logn)
MAX-HEAP-INSERT(A, key)
heap-size[A] heap-size[A] + 1
A[heap-size[A]]
HEAP-INCREASE-KEY(A, heap-size[A], key)
DecreaeKey Replace key and call max_heapify
Find min -> All the mimimum elements will be in the leaf nodes .
SO leaf nodes are from n/2+1 to n . So iterate and find min O(n) or create a min heapify
with those leaf nodes and get the root node O(1)
n! permutations are possible and there are no more than 2^h leaves
n! <= l <= 2^h => log(n1) Sterling Approximation nlogn
The length of the longest path from the root of a decision tree to any of its reachable
leaves represents the worst-case number of comparisons that the corresponding
sorting algorithm performs. Consequently, the worst-case number of comparisons
for a given comparison sort algorithm equals the height of its decision tree
http://www.gatecse.org/best-video-lectures-for-gate-in-cse/
http://www.bowdoin.edu/~ltoma/teaching/cs231/fall07/Lectures/sortLB.pdf
http://www.dsalgo.com/2013/02/BinaryTreeSumChildNodes.php.html
// Recursively call for left and right subtrees and store the sum as
// new value of this node
node->data = toSumTree(node->left) + toSumTree(node->right);
// Return the sum of values of nodes in left and right subtrees and
// old_value of this node
return node->data + old_val;
}
http://qa.geeksforgeeks.org/978/questions-linked-geeksforgeeks-almost-everything-
linked
http://qa.geeksforgeeks.org/1536/questions-binary-geeksforgeeks-almost-everything-
binary
} else {
new_array[count] = alices_array[j];
j++;
}
count++;
}
for(int k=0;k<length;k++) {
System.out.println(new_array[k]);
http://gatecse.in/wiki/Best_video_lectures_for_CSE
http://www.geeksforgeeks.org/how-to-check-if-a-given-array-represents-a-binary-heap/
http://articles.leetcode.com/2010/11/stack-that-supports-push-pop-and-getmin.html
http://prismoskills.appspot.com/lessons/Arrays/Next_largest_element_for_each_ele
ment.jsp
3) Fix one pointer to the head and another to kth node from head.
4) Move both pointers at the same pace, they will meet at loop starting node.
5) Get pointer to the last node of loop and make next of it as NULL.
Another method is
1) Detect loop
2) Set p1 = head , p2 = same point
3) While(p2->next != p1) {
P1=p1->next
P2=p2->next
}
P2->next = null;
What are the minimum and maximum numbers of elements in a heap of height h?
Since a heap is an almost-complete binary tree (complete at all levels except possibly the
lowest), it has at most 1+2+22 +23 ++2h =2h+1-1 elements (if it is complete) and at least
2h -1+1=2h elements
Height of a tree
The number of edges on a simple downward path from a root to a leaf. Note that the height of a tree
with n node is lg n which is (lgn). This implies that an n-element heap has height lg n
In order to show this let the height of the n-element heap be h. From the bounds obtained on maximum
and minimum number of elements in a heap, we get
-2h n 2h+1-1
2h n 2h+1
h lgn h +1
// If the popped item has a right child and the right child is not
// processed yet, then make sure right child is processed before root
if (root->right && peek(stack) == root->right)
{
pop(stack); // remove right child from stack
push(stack, root); // push root back to stack
root = root->right; // change root so that the right
// child is processed next
}
else // Else print root's data and set root as NULL
{
printf("%d ", root->data);
root = NULL;
}
} while (!isEmpty(stack));
}
1. A binary tree is balanced if for each node it holds that the number of inner nodes in the left
subtree and the number of inner nodes in the right subtree differ by at most 1.
2. A binary tree is balanced if for any two leaves the difference of the depth is at most 1.
http://www.crazyforcode.com/passing-car-east-west-codility/
http://www.crazyforcode.com/find-minimum-distance-numbers/
int minDistance(int *input, int n1, int n2, int length)
{
int pos1 = INT_MAX;
int pos2 = INT_MAX;
int distance = length+1;
int newDistance;
pos1 = pos2 = distance = length;
Max = a[length-1]
For(I = length -2 -> 0)
If(a[i] > max )
Print a[i]
Max = a[i]
http://www.crazyforcode.com/leaders-array/
vector<int> intersection;
int n1 = A.size();
int n2 = B.size();
int i = 0, j = 0;
j++;
i++;
} else {
I*ntersection.push_back(A[i]);
i++;
j++;
This can also be done by taking element in one array and searching in 2 nd array using binary search
O(m*logn) approach
Merge Intervals
http://www.programcreek.com/2012/12/leetcode-merge-intervals/
return root;
}
https://github.com/mission-
peace/interview/blob/master/src/com/interview/tree/FenwickTree.java
Get Parent .
2s complement AND and Subtract
Get Next-
2s complement AND and Add
http://www.programcreek.com/2014/05/leetcode-implement-trie-prefix-tree-
java/
http://www.geeksforgeeks.org/longest-prefix-matching-a-trie-based-solution-in-
java/
N Steps Problem
Nth step can be reached from either n-1th step or n-2th step
Y(n) = y(n-1)+y(n-2)
Y(n)=F(n+1)
http://ms.appliedprobability.org/data/files/Articles%2033/33-1-5.pdf
https://web.stevens.edu/ssm/nov13.pdf
We have a 10 step staircase. One can climb up 1,2, or 3 stairs at a time. How many ways are
there to climb up the stairs? Lets let Nk denote the number of ways to climb k stairs in the
manner described. (So were looking for N10.) Notice that for k 4 there are 3 moves one
can do for your first step: you can climb 1,2, or 3 stairs. If you climb 1 stair then there are
Nk1 ways to finish; if you climb 2 stairs there are Nk2 ways to finish; and if you climb 3
stairs there are Nk3 ways to finish. Thus: Nk = Nk1 + Nk2 + Nk3
Well, its pretty easy to see that for the k < 4 we have N1 = 1, N2 = 2 and N3 = 4, so using
the above we can calculate N10 using brute force.
N4 = N3 + N2 + N1 = 4 + 2 + 1 = 7
N5 = N4 + N3 + N2 = 7 + 4 + 2 = 13
N6 = N5 + N4 + N3 = 13 + 7 + 4 = 24
N7 = N6 + N5 + N4 = 24 + 13 + 7 = 44
N8 = N7 + N6 + N5 = 44 + 24 + 13 = 81
N9 = N8 + N7 + N6 = 81 + 44 + 24 = 149
N10 = N9 + N8 + N7 = 149 + 81 + 44 = 274
There are 274 ways to climb the stairs
Palindrome Number
n = num;
rev = 0;
while (num > 0)
{
dig = num % 10;
rev = rev * 10 + dig;
num = num / 10;
}
If n == rev then num is a palindrome:
O(nlogn)= log(n!)
https://www.nayuki.io/page/next-lexicographical-permutation-algorithm
Find the highest index i such that s[i] < s[i+1]. If no such index exists, the permutation is
the last permutation.
Find the highest index j > i such that s[j] > s[i]. Such a j must exist, since i+1 is such an
index.
Swap s[i] with s[j].
Reverse all the order of all of the elements after index i
http://www.ardendertat.com/2012/01/02/programming-interview-questions-24-find-next-higher-number-
with-same-digits/
i=n-2
while( a[i] > a[i+1]) i-
j=n-1
while( a[i] > a[j] ) j-
swap(a[i],a[j] )
reverse(i+1,n)
/* Function to calculate x raised to the power y in O(logn)*/
int power(int x, unsigned int y)
{
int temp;
if( y == 0)
return 1;
temp = power(x, y/2);
if (y%2 == 0)
return temp*temp;
else
return x*temp*temp;
}
The space complexity of recursive tree traversal is O(h) h is height of the tree
Pigeonhole Principle
IF there are n boxes and k holes then atleast one box will have n/k
http://www.careercup.com/question?id=14990323
Given An Array with N integer with values ranging from 1 to N. there is only one
duplicate in the Array.
Find out Duplicate value.
i.e.
A = { 10,6,3,4,7,5,2,4,9,1}
http://www.geeksforgeeks.org/find-the-maximum-element-in-an-array-which-is-first-increasing-and-then-
decreasing/
Maximum Element
while(l <= h) {
int mid = (l+h)/2;
if(a[mid] > a[mid-1] && a[mid] > a[mid+1]) {
System.out.println(a[mid]);
}
if( a[mid] < a[mid+1] && a[mid] > a[mid-1]) {
System.out.println("entered here");
l = mid+1;
} else { // a[mid] > next && a[mid] < prev
h=mid-1;
}
}
Egg Dropping
http://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/
https://leetcode.com/discuss/56350/straight-forward-c-solution-with-explaination
When there is an array first think about length . What happens when it has odd length or even length
or null
sumArray[0] = arr[0];
for(int i=0;i<sumArray.length;i++){
for(int j = i+1; j<sumArray.length;j++){
if(sumArray[i] == sumArray[j] || sumArray[j] == 0){
print(i,j,arr);
}
}
}
}
This algorithm will find all subarrays with sum 0 and it can be easily modified to find the minimal
one or to keep track of the start and end indexes. This algorithm is O(n).
Given an int[] input array, you can create an int[] tmp array where tmp[i] = tmp[i - 1] + input[i];
Each element of tmp will store the sum of the input up to that element.
Now if you check tmp, you'll notice that there might be values that are equal to each other. Let's
say that this values are at indexes j an k with j < k, then the sum of the input till j is equal to
the sum till k and this means that the sum of the portion of the array between j and k is 0!
Specifically the 0 sum subarray will be from index j + 1 to k.
Algo:-
let the array be arr
1.Create An array sum as below
sum[i]=arr[0]+arr[1]+...arr[i];
Cycle Start and end edges are same and no other vertices or edges are repeated
A graph with no cycle is Acyclic graph
A tree is undirected acyclic graph
Space Complexity of graphs = O(no.of edges+no.of vertex)
A Binomial Tree of order 0 has 1 node. A Binomial Tree of order k can be constructed by taking two
binomial trees of order k-1, and making one as leftmost child of other.
A Binomial Tree of order k has following properties.
a) It has exactly 2^k nodes.
b) It has depth as k.
c) There are exactly kCi nodes at depth i for i = 0, 1, . . . , k.
d) The root has degree k and children of root are themselves Binomial Trees with order k-1, k-2,.. 0
from left to right.
Kruskals
MST-KRUSKAL(G,w)
1A
2 for each vertex v V[G]
3 do MAKE-SET(v)
4 sort the edges of E into nondecreasing order by weight w
5 for each edge (u, v) E, taken in nondecreasing order by weight
6 do if FIND-SET(u) != FIND-SET(v)
7 then A A {(u, v)}
8 UNION(u, v)
9 return A
SC = O(E+V)
TC = O(ELogE)
https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/KruskalMST.java
tree is augmented at each step with an edge that
Prims Algorithm is Greedy because
contributes the minimum amount possible to the trees weight.
MST-PRIM(G,w, r)
1 for each u V[G]
2 do key[u]
3 [u] NIL -> Parent
4 key[r] 0
5 Q V[G]
6 while Q !=
7 do u EXTRACT-MIN(Q)
8 for each v Adj[u]
9 do if v Q and w(u, v) < key[v]
10 then [v] u
11 key[v] w(u, v)
In Prim's, you always keep a connected component, starting with a single
vertex. You look at all edges from the current component to other vertices
and find the smallest among them. You then add the neighbouring vertex
to the component, increasing its size by 1. In N-1 steps, every vertex
would be merged to the current one if we have a connected graph.
In Kruskal's, you do not keep one connected component but a forest. At
each stage, you look at the globally smallest edge that does not create a
cycle in the current forest. Such an edge has to necessarily merge two
trees in the current forest into one. Since you start with N single-vertex
trees, in N-1 steps, they would all have merged into one if the graph was
connected.
Djikstras
No negative edge lengths allowed in Djikstras algorithm. Directed
weighted graph
O(ELogV)=OE+vlogv
if a[i] > a[j] then all values from a[i+1] to a[mid] are greater than a[j] so
count = count+mid-i
https://github.com/mission-
peace/interview/blob/master/src/com/interview/dynamic/LongestIncreasin
gSubsequence.java
https://github.com/mission-
peace/interview/blob/master/src/com/interview/array/LongestIncreasingSu
bSequenceOlogNMethod.java
Partition Array into two halves such that sum of differenes in mimimum-
Greedy- O(n^2)
1. Find the neartest neighbor with mimumum distance for I . Mark both as visited
2. If sum of I < sum of J then partition[l++] = max (a[i],a[j]) partition[r++] = min . else vice versa
For(coins 1-n)
For(sum 1-n)
If(coins > sum )
T[c][s] = T[c-1][s]
Else T[c][s] = T[c-1][s]+T[c][Sum-Coin]
TC = O(Coins * Sum)
for (int i = 1; i <= v.length; i++) {
for (int j = 1; j <= amount; j++) {
// check if the coin value is less than the amount needed
if (v[i - 1] <= j) {
// reduce the amount by coin value and
// use the subproblem solution (amount-v[i]) and
// add the solution from the top to it
solution[i][j] = solution[i - 1][j]
+ solution[i][j - v[i - 1]];
} else {
// just copy the value from the top
solution[i][j] = solution[i - 1][j];
}
}
}
return solution[v.length][amount];
}
Partitioning Problem is A set can be divided into two sets such that sum of S1 = sum of S2 .
O(nN) N= total sum of array
http://algorithmsandme.in/2014/04/balanced-partition-problem/
int T[10240];
int partition(int C[], int size){
//computethe total sum
int N= 0;
for(int i= 0;i<n;i++) N+=C[i];
//initialize the table
T[0]=true;
for(int i=1;i<=N;i++)T[i]= false;
if (k > maxLength)
{
start = i;
maxLength = k;
}
}
}
}
Cutting Rod
Max= min_int
For(i=0->n) // Cuts
For(j=0->i) // Value for cuts
Max = Math.max(max,valueForTheCut[j]+solution[i-j]) // Value at that cut + value of the cuts
before it get the max)
Solution[i] = max;
Return solution[n];
if (word.equals(word1)) {
posA = i;
} else if (word.equals(word2)) {
posB = i;
}
if (word1.equals(word2)) {
posB = posA;
}
}
return minDistance;
}
}
Given a sorted and rotated array, find if there is a pair with a given sum
l=0;
r=length-1
while (l != r)
{
// If we find a pair with sum x, we return true
if (arr[l] + arr[r] == x)
l++;
r--;
return true;
http://www.geeksforgeeks.org/find-a-pair-with-the-given-difference/
http://codercareer.blogspot.com/2013/02/no-42-three-increasing-elements-in-array.html
Subset Sum Running Time O(sum * N)
If a[i] < t,
S(i,t) = S(i - 1,t - a[i]) OR S(i - 1, t)
Else: S(i, t) = S(i - 1, t)
To print
If(S[i-1][j] == true ) print
Else (s[i-1][j-A[i]) if its true print this number
We can check by excluding the ith element in the subset and we check if we can get the sum
by j by including ith by checking if the sum j-A[i] exists without the ith element
curr.add(candidates[i]);
combinationSum(candidates, target - candidates[i], i, curr, result);
curr.remove(curr.size()-1);
}
}
Wiggle Sort
A[0] <= A[1] >= A[2] <= A[3] >= A[4] <= A[5]
So we could actually observe that there is pattern that
A[even] <= A[odd],
A[odd] >= A[even].
public class Solution {
public void wiggleSort(int[] nums) {
if (nums == null || nums.length <= 1) {
return;
}
for (int i = 0; i < nums.length - 1; i++) {
if (i % 2 == 0) {
if (nums[i] > nums[i + 1]) {
swap(nums, i, i + 1);
}
} else {
if (nums[i] < nums[i + 1]) {
swap(nums, i, i + 1);
http://algorithms.tutorialhorizon.com/construct-a-binary-tree-from-given-inorder-
and-postorder-traversal/
BST to DLL
static node* prev = NULL;
void BinaryTree2DoubleLinkedList(node *root, node **head)
{
// Base case
if (root == NULL) return;
// Recursively convert left subtree
BinaryTree2DoubleLinkedList(root->left, head);
}
http://introcs.cs.princeton.edu/java/42sort/LRS.java.html
Here's a simple algorithm for building a suffix array:
Construct all the suffixes of the string in time (m2 ).
Sort those suffixes using heapsort or mergesort. Makes O(m log m) comparisons, but
each comparison takes O(m) time. Time required: O(m2 log m).
Total time: O(m^2 log m)
http://www.geeksforgeeks.org/suffix-array-set-1-introduction/
Step 2: Balance the heaps (after this step heaps will be either balanced or
one of them will contain 1 more item)
a[0] = 1;
b[0] = 1;
Edit Distance
public int dynamicEditDistance(char[] str1, char[] str2){
int temp[][] = new int[str1.length+1][str2.length+1];
http://www.geeksforgeeks.org/dynamic-programming-set-32-word-break-problem/
Find Minimum Window in S with all elements in T
string preProcess(string s) {
int n = s.length();
if (n == 0) return "^$";
string ret = "^";
for (int i = 0; i < n; i++)
ret += "#" + s.substr(i, 1);
ret += "#$";
return ret;
}
string longestPalindrome(string s) {
string T = preProcess(s);
int n = T.length();-
int *P = new int[n];
int C = 0, R = 0;
for (int i = 1; i < n-1; i++) {
int i_mirror = 2*C-i; // equals to i' = C - (i-C)
return result;
}
-
Topological Sort O(V+E)-
https://github.com/IDeserve/learn/blob/master/topologicalSort.java
Shortest Path in DAG First topological sort and then Djikstras algorithm
Aaabc abaca
1. Create character count
2. If count of an element is greater than n/2+1 then return
3. Iterate over each element and take its count
4. J=0 - If j> str.length j=1
5. output[j]=string[i] j=j+2;
http://js-interview.tutorialhorizon.com/2015/10/19/rearrange-characters-in-
a-string-so-that-no-character-repeats-twice/
function createFrequencyAnalysis(str) {
var charFrequency = {};
Array.prototype.forEach.call(str, function(ch) {
charFrequency[ch] ? charFrequency[ch]++ : charFrequency[ch] = 1;
});
return charFrequency;
}
var i = 0;
var j = 0;
var k = 0;
var charFreq = 0;
var numberOfChar = characters.length;
output[j] = characters[i];
j += 2;
}
}
return output.join('');
}
Find Number of 1s in a Binary Representation of a Number
int rst = 0 ;
while (n != 0) {
n = n & (n - 1);
rst++;}
temp.add(num[i]);
getCombination(num, i+1, target-num[i], temp, result);
temp.remove(temp.size()-1);
}
}
}
Given an array of size n. It contains numbers in the range 1 to N. Each number is present at least
once except for 2 numbers. Find the missing numbers.
Write a program to remove duplicate elements from array
for(int i=0;i<b.length;i++) {
if(b[Math.abs(b[i])] >= 0) {
b[Math.abs(b[i])] = -b[Math.abs(b[i])];
} else {
System.out.println(Math.abs(b[i]));
}
}
Find the Occurrence in O(n) tc and O(1) space complexity
// Function to find counts of all elements present in
// arr[0..n-1]. The array elements must be range from
// 1 to n
void printfrequency(int arr[],int n)
{
// Subtract 1 from every element so that the elements
// become in range from 0 to n-1
for (int j =0; j<n; j++)
arr[j] = arr[j]-1;
// Use every element arr[i] as index and add 'n' to
// element present at arr[i]%n to keep track of count of
// occurrences of arr[i]
for (int i=0; i<n; i++)
arr[arr[i]%n] = arr[arr[i]%n] + n;
// To print counts, simply print the number of times n
// was added at index corresponding to every element
for (int i =0; i<n; i++)
cout << i + 1 << " -> " << arr[i]/n << endl;
}
Quick Sort SC = O(logn) Because stack frame is created by reducing the search space based on index
for(int i=0;i<k;i++) {
while(!q.isEmpty && a[i] > q.back()) {
q.pop_back();
}
q.push_back(i);
}
for(int i=k;i <a.length;i++) {
list.add(a[q.front()]);
while(!q.isEmpty && a[i] > q.back()) {
q.pop_back();
}
if(!q.isEmpty && q.front() <=i-k) {
q.pop_front();
}
q.push_back(i);
}
list.add(a[q.front()]);
return list;
}
http://www.geeksforgeeks.org/find-zeroes-to-be-flipped-so-that-number-of-consecutive-1s-is-maximized/
http://www.geeksforgeeks.org/largest-subarray-with-equal-number-of-0s-and-1s/
1<<x Power of 2
x>>1 divide by power of 2
AXORB = (AXORB & (AXORB - 1)) ^ AXORB; //find the different bit
for(int i = 0; i<nums.length; i++){
if((AXORB & nums[i]) == 0)
A ^= nums[i];
else
B ^= nums[i];
}
return new int[]{A, B};
}
}
http://traceformula.blogspot.com/2015/09/single-number-iii-leetcode.html
Find the non-repeating number where each number repeats 3 times
http://traceformula.blogspot.com/2015/08/single-number-ii-how-to-come-up-with.html
Deadlock
http://javarevisited.blogspot.sg/2010/10/what-is-deadlock-in-java-how-to-fix-it.html
Variables that are marked as volatile get only visible to other threads once the
constructor of the object has finished its execution completely.
Thread.join() Wait for the thread to die before continuing execution.
A field may be declared volatile, in which case the Java Memory Model ensures that all
threads see a consistent value for the variable
LRU Cache
http://www.programcreek.com/2013/03/leetcode-lru-cache-java/
IsPowerOfThree
public class Solution {
public boolean isPowerOfThree(int n) {
if (n < 1) {
return false;
}
while (n % 3 == 0) {
n /= 3;
}
return n == 1;
}
http://www.programcreek.com/2014/02/leetcode-longest-common-prefix-java/
Contains Duplicate
Given an array of integers and an integer k, find out whether there are two
distinct indices i and j in the array such that nums[i] = nums[j]and the
difference between i and j is at most k.
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nums.length; i++){
if(i > k) set.remove(nums[i-k-1]);
if(!set.add(nums[i])) return true;
}
return false;
Keep a track of min and profit for every element and take maxProfit
int maxprofit = 0;
return maxprofit;
BackTracking
https://discuss.leetcode.com/topic/46161/a-general-approach-to-backtracking-questions-
in-java-subsets-permutations-combination-sum-palindrome-partitioning
http://www.geeksforgeeks.org/find-common-elements-three-sorted-arrays/
Elimination Game
public int lastRemaining(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
int step = 1;
int head = 1;
int remaining = n;
boolean left = true;
while (remaining > 1) {
if (left || remaining % 2 ==1) {
head = head + step;
}
remaining = remaining/2;
step *= 2;
left = !left;
} return head;
Jump Game
public boolean canJump(int[] nums) {
int maxLocation = 0;
for(int i=0; i<nums.length; i++) {
if(maxLocation < i) return false; // if previous maxLocation smaller than i, meaning
we cannot reach location i, thus return false.
maxLocation = (i+nums[i]) > maxLocation ? i+nums[i] : maxLocation; // greedy:
}
return true;
}
http://www.programcreek.com/2013/12/leetcode-solution-of-longest-palindromic-
substring-java/
http://www.ideserve.co.in/learn/print-matrix-diagonally
for (int k = 0; k < rowCount; k++) {
for (row = k, col = 0; row >= 0 && col < columnCount; row--, col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
for (int k = 1; k < columnCount; k++) {
for (row = rowCount - 1, col = k; row >= 0 && col < columnCount; row--, col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
http://www.ideserve.co.in/learn/how-to-recover-a-binary-search-tree-if-two-nodes-are-
swapped
While doing inorder traversal keep a track of prev. Compare prev with curr.
If prev > curr, update firstVariable to prev, lastVariable to curr. Swap after all elements
return maxValue;
}
https://gist.github.com/guolinaileen/4670376
int i = 1;
for(int j=1; j<length; j++)
{
if(A[j]!=A[j-1])
{
A[i]=A[j];
i++;
}
}
http://www.ideserve.co.in/learn/maximum-average-subarray
maximum sum subarray of size k.
int sum = input[0];
for (int i = 1; i < k; i++)
sum += input[i];
// Initialized to first k elements sum
int maxSum = sum;
int maxSumIndex = 0;
int rainwater = 0;
return rainwater;
}
return done;
}
value.push(x);
while(!temp.isEmpty()){
value.push(temp.pop());
}
}
}
PreOrder to BST
Node constructTree(int pre[], int size) {
// Make this greater value as the right child and push it to the stack
if (temp != null) {
temp.right = new Node(pre[i]);
s.push(temp.right);
}
// If the next value is less than the stack's top value, make this value
// as the left child of the stack's top node. Push the new node to stack
else {
temp = s.peek();
temp.left = new Node(pre[i]);
s.push(temp.left);
}
}
return root;
}
Strings Order
private boolean stringsOrder(String s1, String s2) {
int j = 0;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) == s2.charAt(j)) {
j++;
}
}
return j == s2.length() ? true : false;
}
if (node == ptr)
return lev;
http://algorithms.tutorialhorizon.com/find-the-distance-between-two-nodes-of-a-binary-tree/
Min Diff between Max and Min Element after removing an element
https://www.hackerrank.com/contests/101hack43/challenges/max-min-difference
Mini Max
// Sort the array so we know where the maximal and minimal elements will be located
Arrays.sort(a);
// Find the difference between the two largest elements
int maxDifference = a[a.length - 1] - a[a.length - 2];
// Find the difference between the two smallest elements
int minDifference = a[1] - a[0];
https://www.hackerrank.com/contests/university-codesprint/challenges/mini-max-sum
Given five positive integers, find the minimum and maximum values that can be calculated by summing
exactly four of the five integers.
Problem
public boolean wordBreak(String s, Set<String> dict) {
// write your code here
if(s == null || s.length() == 0) {
return true;
}
// Empty string
if(words == null || words.length() == 0) {
return true;
}
int n = words.length();
boolean[] validWords = new boolean[n];
for (int i = 0; i < n; i++) {
if (dictionary.contains(words.substring(0, i + 1))) {
validWords[i] = true;
}
if (validWords[i] == true && (i == n - 1))
return true;
if (validWords[i] == true) {
for (int j = i + 1; j < n; j++) {
if (dictionary.contains(words.substring(i + 1, j + 1))) {
validWords[j] = true;
}
if (j == n - 1 && validWords[j] == true) {
return true;
}
}
}
}
return false;
}
if (s.length() == 1) {
return s;
}
return longest;
}
Implement Trie
https://raw.githubusercontent.com/mission-
peace/interview/master/src/com/interview/suffixprefix/Trie.java
Insert
1. Check if the first character in the word is a child of the root.
2. If not then create a new node and add this character as key and the new node as value to the
map of children of the root
3. Update current = node and at the end of the iteration update endOfWord = true.
TC of Trie = O(nm)
http://techieme.in/word-frequency-in-stream/
http://techieme.in/building-an-autocomplete-system-using-trie/
// 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap
HashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
int max = 0;
int i = 0;
}
while (!stack.isEmpty()) {
//area;
}
for(TreeNode n: root.children()){
int height = getHeight(n);
if(height > tallest ){
tallest = height);
}
}
return tallest + 1;
http://www.geeksforgeeks.org/find-water-in-a-glass/
https://careercup.com/question?id=5704645247762432
http://www.geeksforgeeks.org/find-longest-palindrome-formed-by-removing-or-shuffling-chars-from-
string/
http://www.geeksforgeeks.org/find-longest-palindrome-formed-by-removing-or-shuffling-chars-from-
string/
#Longest Palindrome by deleting or shuffling
chars
public String longestPalindrome(String str) {
int count[] = new int[256];
for (int i = 0; i < str.length(); i++) {
count[str.charAt(i)]++;
}
String start = "";
String mid = "";
String end = "";
for (char ch = 'a'; ch <= 'z'; ch++) {
if (count[ch] % 2 == 1) {
//contains only one character and can be overriden by the next char with //odd frequency
mid = ch;
count[ch]--;
ch--;
} else {
for (int i = 0; i < count[ch]/2; i++) {
start += ch;
}
}
}
end = reverseString(start);
return start + mid + end;
}
public String reverseString(String str) {
char a[] = str.toCharArray();
int i = 0;
int j = a.length - 1;
while (i < j) {
char ch = a[i];
a[i] = a[j];
a[j] = ch;
i++;
j--;
}
return String.valueOf(a);
}
KMP
public int[] failure(String pattern[]) {
int n = pattern.length();
int f[] = new int[n];
int i = 1;
int j = 0;
while (i < n) {
if (pattern.charAt(i) == pattern.charAt(j)) {
f[i] = j + 1;
i++;
j++;
} else {
if (j != 0) {
j = f[j-1];
} else {
f[i] = 0;
i++;
}
}
}
return f;
}
Word Ladder
public int ladderLength(String begin, String endWord, Set<String> wordList) {
Queue<String> queue = new LinkedList<String>();
wordList.add(endWord);
queue.add(begin);
int dist = 1;
while (!queue.isEmpty()) {
for (int size = queue.size(); size > 0; size--) {
String word = queue.remove();
if (endWord.equals(word)) {
return dist;
}
char arr[] = word.toCharArray();
for (int i = 0; i < arr.length; i++) {
char ch = arr[i];
for (char j = 'a'; j <= 'z'; j++) {
arr[i] = j;
word = String.valueOf(arr);
if (wordList.contains(word)) {
queue.add(word);
wordList.remove(word);
}
arr[i] = ch;
}
}
}
dist++;
}
return dist;
}
N Queens
For rows and cols 2nd condition check on upper left and lower left of the current location.
Row++ Col-
and row- and col --
Longest Common Prefix
public String longestCommonPrefix(String[] strs) {
if (strs.length < 1) {
return "";
}
String firstWord = strs[0];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < firstWord.length(); i++) {
char curr = firstWord.charAt(i);
for (int j = 1; j < strs.length; j++) {
String word = strs[j];
int len = word.length();
if (i > len - 1 || curr != word.charAt(i)) {
return sb.toString();
}
}
sb.append(curr);
}
return sb.toString();
}
http://www.geeksforgeeks.org/dynamic-programming-set-27-max-sum-rectangle-in-a-2d-matrix/
#Maximum Sub rectangle of a matrix
Topological Sort
2nd Method using DFS and Stack
Josephus Problem
int josephus(int n, int k) {
if (n == 1)
return 1;
} else {
/* After the k-th person is killed, we're left with a circle of n-1, and we start the next count with
the person whose number in the original problem was (
k%n) + 1
*/
return (josephus(n - 1, k) + k) % n + 1;
}
#Check if T2 is subtree of T1
public boolean checkTree(TreeNode t1, TreeNode t2) {
if (t2 == null) {
return true;
}
return subTree(t1, t2);
}
public boolean subTree(TreeNode t1, TreeNode t2) {
if (t1 == null) {
return false;
}
if (t1.data == t2.data && matchTree(t1.left, t2.left)) {
return true;
}
return subTree(t1.left, t2) || subTree(t1.right, t2);
}
public boolean matchTree(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) {
return true;
}
if (t1 != null && t2 != null) {
return matchTree(t1.left, t2.left) && return matchTree(t1.right, t2.right);
}
return false;
}
if (smaller% 2 == 0) {
return halfProd + halfProd;
} else {
return halfProd + halfProd + bigger;
}
}
#Longest Increasing Subarray in O(max(N/L, L) TC
#Beginning and Ending
public int lis(int a[]) {
int count = 1;
int i = 0;
while (i < a.length) {
isSkip = false;
for (int j = i + count - 1; j >= 0; j--) {
if (A[j] > A[j+1]) {
i = j + 1;
isSkip = true;
break;
}
}
if (!isSkip) {
i = i + count - 1;
while (i + 1 < a.length && a[i] < a[i+1]) {
i++;
count++;
}
int startingIndex = i - count + 1;
int endingIndex = i;
}
}
return startingIndex+endingIndex;
}
#Huffman Decode
void decode(String S, Node root)
{
StringBuilder sb = new StringBuilder();
Node c = root;
for (int i = 0; i < S.length(); i++) {
c = S.charAt(i) == '1' ? c.right : c.left;
if (c.left == null && c.right == null) {
sb.append(c.data);
c = root;
}
}
System.out.print(sb);
}
#Remove b and replace a with dd
public int removeAndReplace(int a[]) {
int count = 0;
int countOfA = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != 'b') {
a[count] = a[i];
}
if (a[i] == 'a') {
countOfA++;
}
}
int currIndex = count;
int newIndex = currIndex + countOfA;
while (currIndex >= 0) {
if (a[currIndex] == 'a') {
a[newIndex] = 'd';
a[newIndex - 1] = 'd';
newIndex = newIndex - 2;
} else {
a[newIndex] = a[currIndex];
newIndex--;
currIndex--;
}
}
Find common elements in two sorted equal arrays O(m+n)
1) Are the arrays of equal length
2) Are the arrays sorted?
#Insert in BST
#Insert in Binary Search Tree
Node insertRec(Node root, int key) {
#Dining philosopher
https://www.youtube.com/watch?v=_ruovgwXyYs
Pick the smaller fork before picking the bigger fork and put down the bigger fork before the smaller
fork to avoid circular wait.
takeLeft(fork[Math.min(I, i+1 mod 5)]);
takeRight(fork[Math.max(I, I+1 mod 5)]);
eat
putRight(fork[i+1 mod 5])
putLeft(fork[i])
#Powerset
public List<List<Integer>> powerSet(List<List<Integer> list, int index) {
List<List<Integer>> allSubsets = new ArrayList<List<Integer>();
if (index = list.size()) {
allSubsets = new ArrayList<List<Integer>>();
allSubsets.add(new ArrayList<List<Integer>());
} else {
allSubsets = powerSet(list, index + 1);
int item = list.get(index);
List<List<Integer>> tempList = new ArrayList<List<Integer>();
for (List<Integer> setSoFar : allSubsets) {
List<Integer> newSet = new ArrayList<Integer>();
newSet.addAll(setSoFar);
newSet.add(item);
tempList.add(newSet);
}
allSubsets.addAll(tempList);
}
return allSubsets;
}
Reconstruct Itinerary
public List<String> findItinerary(String[][] tickets) {
LinkedList<String> list = new LinkedList<String>();
HashMap<String, PriorityQueue<String>> map = new HashMap<String, PriorityQueue<String>>();
for (int i = 0; i < tickets.length; i++) {
String[] ticket = tickets[i];
String origin = ticket[0];
String dest = ticket[1];
if (!map.containsKey(origin)) {
map.put(origin, new PriorityQueue<String>());
}
map.get(origin).add(dest);
}
dfs("JFK", list, map);
return list;
}
public void dfs(String origin, LinkedList<String> list, HashMap<String, PriorityQueue<String>>
map) {
PriorityQueue<String> pq = map.get(origin);
while (pq != null && !pq.isEmpty()) {
dfs(pq.poll(), list, map);
}
list.addFirst(origin);
}
Majority Element II
public List<Integer> majorityElement(int[] nums) {
List<Integer> list = new ArrayList<Integer>();
if (nums.length == 0) {
return list;
}
int num1 = nums[0];
int count1= 0;
int num2 = nums[0];
int count2 = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == num1) {
count1++;
} else if (nums[i] == num2) {
count2++;
} else if (count1 == 0) {
num1 = nums[i];
count1 = 1;
} else if (count2 == 0) {
num2 = nums[i];
count2 = 1;
} else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == num1) {
count1++;
} else if (nums[i] == num2) {
count2++;
}
}
if (count1 > Math.ceil(nums.length/3)) {
list.add(num1);
}
if (count2 > Math.ceil(nums.length/3)) {
list.add(num2);
}
return list;
}
# Find All Numbers Disappeared in an Array
while(!stack.isEmpty()) {
final TreeNode node = stack.pop();
final TreeNode left = node.left;
node.left = node.right;
node.right = left;
if(node.left != null) {
stack.push(node.left);
}
if(node.right != null) {
stack.push(node.right);
}
}
return root;
}
Arranging Coins
The maximum length of sum of consecutive integer <= n
x.(x+1)/2 <= n
public int arrangeCoins(int n) {
int low = 0;
int high = n;
while (low <= high) {
int mid = (low + high)/2;
if ((0.5 * mid * mid + 0.5 * mid ) <= n) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low - 1;
}
Isomorphic Strings
Keep a track of last seen index
public boolean isIsomorphic(String s, String t) {
int arr1[] = new int[256];
int arr2[] = new int[256];
for (int i = 0; i < s.length(); i++) {
if (arr1[s.charAt(i)] != arr2[t.charAt(i)]) {
return false;
}
if (arr1[s.charAt(i)] == 0) {
arr1[s.charAt(i)] = i + 1; // 0 Is default in the array so marking with I + 1;
arr2[t.charAt(i)] = i + 1 ;
}
}
return true;
}
Rectangle Area
Area of two rectangles overlapping area
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
//If overlap
int overlap = 0;
if(right > left && top > bottom)
overlap = (right - left) * (top - bottom);
Shuffle Array
1) Make copy of the array . int[] newArray = Arrays.copyOf(array, array.length);
2) Swap with random index. int swapIndex = rand.nextInt(i + 1)
3) Rand.nextInt gives a rand number from 0 to i.
Binary to gray
num ^ (num >> 1);
Josephus Circle
while (p <= n) {
p = 2 * p; // least pot greater than n
}
int res = (2 * n) - p + 1;
if (str.contains(".")) {
if (len - 1 > longest) {
longest = len - 1;
}
}
stack.push(tempStr.length() + 1);
}
return longest;
}
Wiggle Subsequence
public int wiggleMaxLength(int[] nums) {
if (nums.length <= 1) {
return nums.length;
}
int k = 0;
while (k < nums.length - 1 && nums[k] == nums[k+1]) {
k++;
}
if (k == nums.length - 1) {
return 1;
}
boolean isInc = false;
if (nums[k] < nums[k + 1]) {
isInc = true;
}
int len = 2;
for (int i = k + 1; i < nums.length - 1; i++) {
if (isInc && nums[i] > nums[i + 1]) {
len++;
isInc = !isInc;
}else if (!isInc && nums[i] < nums[i + 1]) {
len++;
isInc = !isInc;
}
}
return len;
}
int left = 0;
int right = citations.length - 1;
while (left <= right) {
int mid = (left + right)/2;
if (citations[mid] == citations.length - mid) {
return citations.length - mid;
} else if (citations[mid] > citations.length - mid) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return citations.length - (right + 1);
}
Path Sum ii
List of paths equal to a sum
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>>ret = new ArrayList<List<Integer>>();
List<Integer> cur = new ArrayList<Integer>();
pathSum(root, sum, cur, ret);
return ret;
}
Gas Station
GasSum > cost sum valid solution. If A cannot reach B then B is the next start station
int gasSum = 0;
int costSum = 0;
int total = 0;
int start = 0;
for (int i = 0; i < gas.length; i++) {
gasSum += gas[i];
costSum += cost[i];
total += gas[i] - cost[i];
if (total < 0) {
start = i + 1;
total = 0;
}
}
if (gasSum < costSum) {
return -1;
} else {
return start; }
return G[n];
}
132 Pattern
public boolean find132pattern(int[] nums) {
Stack<Integer> stack = new Stack<Integer>();
int s3 = Integer.MIN_VALUE;
for (int i = nums.length - 1; i >= 0 ; i--) {
if (nums[i] < s3) {
return true;
} else {
while (!stack.isEmpty() && nums[i] > stack.peek()) {
s3 = stack.pop();
}
}
stack.push(nums[i]);
}
return false;
}
Permutation sequence
public String getPermutation(int n, int k) {
return false;
}
visited[i][j] = true;
if(search(board, word, i-1, j, index+1) ||
search(board, word, i+1, j, index+1) ||
search(board, word, i, j-1, index+1) ||
search(board, word, i, j+1, index+1)){
return true;
}
visited[i][j] = false;
return false;
}
}
Clone Graph
public HashMap<Integer, UndirectedGraphNode> map = new HashMap();
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) {
return null;
}
if (map.containsKey(node.label)) {
return map.get(node.label);
}
UndirectedGraphNode clonedNode = new UndirectedGraphNode(node.label);
map.put(clonedNode.label, clonedNode);
for (int i = 0; i < node.neighbors.size(); i++) {
clonedNode.neighbors.add(cloneGraph(node.neighbors.get(i)));
}
return clonedNode;
}
Missing Range
[0, 1, 3, 50, 75], return [2, 4->49, 51->74, 76->99]
// do a final check
if (next <= hi) res.add(getRange(next, hi));
return res;
}
Summary Range
[0,1,2,4,5,7], return ["0->2","4->5","7"]
}
}
Self Crossing
public boolean isSelfCrossing(int[] x) {
for (int i = 3; i < x.length; i++) {
if (x[i] >= x[i-2] && x[i-1] <= x[i-3]) {
return true;
}
else if (i >=4 && x[i-1] == x[i-3] && x[i] + x[i-4] >= x[i-2]) {
return true;
} else if (i >= 5 && x[i-2] >= x[i-4] && x[i] + x[i-4] >= x[i-2] && x[i-1] + x[i-5] >=
x[i-3] && x[i-1] <= x[i-3]) {
return true;
}
}
return false;
}
}
for (int i = 0; i < len; i++) {
if (nums[i] != i + 1) {
return i + 1;
}
}
return len + 1;
}
Paint Houses
public int minPaintCost(int[][] cost) {
if (cost == null || cost.length == 0) return 0;
int[][] dp = new int[cost.length][3];
dp[0][0] = cost[0][0], dp[0][1] = cost[0][1], dp[0][2] = cost[0][2];
for (int i = 1; i < cost.length; ++i) {
dp[i][0] = cost[i][0] + Math.min(dp[i-1][1], dp[i-1][2]);
dp[i][1] = cost[i][1] + Math.min(dp[i-1][0], dp[i-1][2]);
dp[i][2] = cost[i][2] + Math.min(dp[i-1][0], dp[i-1][1]);
}
return Math.min(dp[dp.length-1][0], Math.min(dp[dp.length-1][1],[dp.length-1][2]));
}
Paint Fences
Factor Combinations
http://buttercola.blogspot.com/2015/08/leetcode-factor-combinations.html
Given unsigned integer 'x', write an algorithm thet returns unsigned integer 'y' such that it has the
same number of bits set as 'x' and is not equal to 'x' and the distance |x-y| is minimized.
Path Sum II - Print the tree having a root to leaf path adding to a target value
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<Integer> list = new ArrayList<Integer>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) {
return result;
}
pathSum(root, sum, list, result);
return result;
}
public void pathSum(TreeNode root, int sum, List<Integer> list, List<List<Integer>> result) {
if (root == null) {
return;
}
list.add(root.val);
if (root.left == null && root.right == null) {
if (sum == root.val) {
result.add(new ArrayList(list));
}
} else {
pathSum(root.left, sum - root.val, list, result);
pathSum(root.right, sum - root.val, list, result);
}
list.remove(list.size() - 1);
}
Finding Celebrity
Letter Combinations of a Phone Number
if (digits.length() == 0) {
return result;
}
HashMap<Character, char[]> map = new HashMap<Character, char[]>();
map.put('2', new char[]{'a','b','c'});
map.put('3', new char[]{'d','e','f'});
map.put('4', new char[]{'g','h','i'});
map.put('5', new char[]{'j','k','l'});
map.put('6', new char[]{'m','n','o'});
map.put('7', new char[]{'p','q','r','s'});
map.put('8', new char[]{'t','u','v'});
map.put('9', new char[]{'w','x','y','z'});
return result;
}
public void letterComb(List<String> result, StringBuilder sb, String digits, int index,
HashMap<Character, char[]> map) {
if (sb.length() >= digits.length()) {
result.add(sb.toString());
return;
}
char ch = digits.charAt(index);
char arr[] = map.get(ch);
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i]);
letterComb(result, sb, digits, index + 1, map);
sb.deleteCharAt(sb.length() - 1);
}
}
Permutations
public void permuate(int[] nums, List<List<Integer>> result, List<Integer> curr) {
if (curr.size() == nums.length) {
result.add(new ArrayList<>(curr));
return;
}
for (int i = 0; i < nums.length; i++) {
if (curr.contains(nums[i])) {
continue;
}
curr.add(nums[i]);
permuate(nums, result, curr);
curr.remove(curr.size() - 1);
}
}
https://discuss.leetcode.com/topic/46162/a-general-approach-to-backtracking-questions-in-java-subsets-
permutations-combination-sum-palindrome-partioning/2
HashSet is not synchronized. So use Collections.synchronizedSet(new HashSet());
Thread safe arraylist is CopyOnWriteArrayList
Subset Powerset
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
backtrack(list, new ArrayList<>(), nums, 0);
return list;
}
private void backtrack(List<List<Integer>> list , List<Integer> tempList, int [] nums, int start){
list.add(new ArrayList<>(tempList));
for(int i = start; i < nums.length; i++){
tempList.add(nums[i]);
backtrack(list, tempList, nums, i + 1);
tempList.remove(tempList.size() - 1);
}
}
Shortest Palindrome
Minimum Insertions to form a Palindrome
Str1
Create reverse of str1.
Take Longest Common Subsequence of str1 and str2.
Length of str1 return of lcs = minimum number of insertions to form a palindrome
Rectangle Overlap
if ((x1 > x4 || x3 >= x2) && (y1 >= y4 || y3 >= y2)) {
System.out.println("no overlap");
} else {
System.out.println("overlap");
}
while(fast!=tail&&fast.next!=tail){
fast = fast.next.next;
slow = slow.next;
}
TreeNode thead = new TreeNode(slow.val);
thead.left = toBST(head,slow);
thead.right = toBST(slow.next,tail);
return thead;
}
Insert Interval
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
List<Interval> list = new ArrayList<Interval>();
int i = 0;
while (i < intervals.size() && intervals.get(i).end < newInterval.start) {
i++;
}
while (i < intervals.size() && intervals.get(i).start <= newInterval.end) {
newInterval.start = Math.min(intervals.get(i).start, newInterval.start);
newInterval.end = Math.max(intervals.get(i).end, newInterval.end);
newInterval = new Interval(newInterval.start, newInterval.end);
intervals.remove(i); // i++
}
intervals.add(i, newInterval); // add to list
// add remaining elements to list for not in-place solution
return intervals;
}
Non-Overlapping Intervals
public int eraseOverlapIntervals(Interval[] intervals) {
int len = intervals.length;
if (len == 0) {
return 0;
}
Arrays.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval a, Interval b) {
return a.end - b.end;
}
});
int count = 1;
int end = intervals[0].end;
for (int i = 1; i < len; i++) {
if (intervals[i].start >= end) {
count++;
end = intervals[i].end;
}
}
return len - count;
}
}
return ' ';
}
Plus One
public int[] plusOne(int[] digits) {
int len = digits.length;
for (int i = len - 1; i >= 0; i--) {
if (digits[i] != 9) {
digits[i]++;
break;
} else {
digits[i] = 0;
}
}
if (digits[0] == 0) {
int res[] = new int[len + 1];
res[0] = 1;
return res;
}
return digits;
}
3Sum
Island Perimeter
public int islandPerimeter(int[][] grid) {
int neighbor = 0;
int island = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
island++;
if (i < grid.length - 1 && grid[i + 1][j] == 1) {
neighbor++;
}
if (j < grid[0].length - 1 && grid[i][j + 1] == 1) {
neighbor++;
}
}
}
}
return island * 4 - neighbor * 2;
}
Min Stack
public void push(int x) {
if (x <= min) {
s1.push(min);
min = x;
}
s1.push(x);
}
Next Permutation
public void nextPermutation(int[] nums) {
if (nums.length <= 1) {
return;
}
int len = nums.length;
int i = len - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i >= 0) {
int j = len - 1;
while (j >= 0 && nums[i] >= nums[j]) {
j--;
}
swap(nums, i, j);
}
reverse(nums, i + 1, len - 1);
}
BattleShips in a Board
public int countBattleships(char[][] board) {
int rowLen = board.length;
int colLen = board[0].length;
int count = 0;
if (rowLen == 0) {
return count;
}
for (int i = 0; i < rowLen; i++) {
for (int j = 0; j < colLen; j++) {
if (board[i][j] == '.') {
continue;
}
if (i < rowLen - 1 && board[i + 1][j] == 'X') {
continue;
}
if (j > 0 && board[i][j - 1] == 'X') {
continue;
}
count++;
}
}
return count;
}
Lexographical Numbers
public List<Integer> lexicalOrder(int n) {
List<Integer> list = new ArrayList<Integer>();
if (n == 0) {
return list;
}
list.add(1);
int curr = 1;
for (int i = 1; i < n; i++) {
if (curr * 10 <= n) {
curr = curr * 10;
} else {
while ((curr % 10 == 9) || curr == n) {
curr = curr / 10;
}
curr++;
}
list.add(curr);
}
return list;
}
Palindrome Partitioning
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<List<String>>();
if (s.length() == 0) {
return result;
}
List<String> curr = new ArrayList<String>();
dfs(s, 0, curr, result);
return result;
}
public void dfs(String s, int index, List<String> curr, List<List<String>> result) {
if (index == s.length()) {
result.add(new ArrayList<>(curr));
return;
}
for (int i = index; i < s.length(); i++) {
if (isPalindrome(s, index, i)) {
curr.add(s.substring(index, i + 1));
dfs(s, i + 1, curr, result);
curr.remove(curr.size() - 1);
}
}
}
public boolean isPalindrome(String s, int start, int end) {
while (start < end) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
public void findSequence(Set<List<Integer>> res, List<Integer> holder, int index, int[] nums) {
if (holder.size() >= 2) {
res.add(new ArrayList(holder));
}
for (int i = index; i < nums.length; i++) {
if(holder.size() == 0 || holder.get(holder.size() - 1) <= nums[i]) {
holder.add(nums[i]);
findSequence(res, holder, i + 1, nums);
holder.remove(holder.size() - 1);
}
}
}
Print kth element in spiral order in a matrix O(c) number of outer circular rings wrt to k
int findK(int A[MAX][MAX], int m, int n, int k)
{
if (n < 1 || m < 1)
return -1;
Union Find
Graph Valid Tree O(k logn)
Course Schedule
public static int root(int arr[], int i) {
while (i != arr[i]) {
arr[i] = arr[arr[i]];
i = arr[i];
}
return i;
}
public boolean validTree(int n, int[][] edges) {
// Write your code here
if (edges.length == 0) {
return true;
}
if (edges.length == 0 && n > 1) {
return false;
}
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = i;
}
for (int i = 0; i < edges.length; i++) {
int x = root(arr, edges[i][0]);
int y = root(arr, edges[i][1]);
if (x == y) { // if( not equal )count- for number of connected components
return false;
}
arr[x] = y;
}
return edges.length == n - 1;
}
Trie Class
class TrieNode {
public char val;
public TrieNode[] children = new TrieNode[26];
public boolean isWord;
public TrieNode() {
}
TrieNode(char ch) {
TrieNode node = new TrieNode();
node.val = ch;
}
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode curr = root;
for (int i = 0; i < prefix.length(); i++) {
char ch = prefix.charAt(i);
if (curr.children[ch - 'a'] == null) {
return false;
}
curr = curr.children[ch - 'a'];
}
return true;
}
}
Surrounded Regions
public class Solution {
public void solve(char[][] board) {
if (board.length == 0 || board[0].length == 0) {
return;
}
if (board.length < 2 || board[0].length < 2) return;
int m = board.length;
int n = board[0].length;
for (int i = 0; i < m; i++) {
if (board[i][0] == 'O') {
dfs(board, i , 0);
}
if (board[i][n - 1] == 'O') {
dfs(board, i, n - 1);
}
}
for (int i = 0; i < n; i++) {
if (board[0][i] == 'O') {
dfs(board, 0, i);
}
if (board[m - 1][i] == 'O') {
dfs(board, m - 1, i);
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
} else if (board[i][j] == '+') {
board[i][j] = 'O';
}
}
}
}
public void dfs(char[][] board, int i, int j) {
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
return;
}
if (board[i][j] == 'O') {
board[i][j] = '+';
}
if (i > 1 && board[i - 1][j] == 'O') {
dfs(board, i - 1, j);
}
if (i < board.length - 2 && board[i + 1][j] == 'O') {
dfs(board, i + 1, j);
}
if (j > 1 && board[i][j - 1] == 'O') {
dfs(board, i, j - 1);
}
if (j < board[i].length - 2 && board[i][j + 1] == 'O') {
dfs(board, i, j + 1);
}
}
}
Word Search II
public class Solution {
public static TrieNode buildTree(String[] words) {
TrieNode root = new TrieNode();
for (String w : words) {
TrieNode p = root;
for (char c : w.toCharArray()) {
int i = c - 'a';
if (p.children[i] == null) p.children[i] = new TrieNode();
p = p.children[i];
}
p.word = w;
}
return root;
}
AutoComplete
do {
tn = temp.children[cArray[index] - 'A'];
// if you reached the end of the string, then no words with this prefix
if (tn == null) {
return null;
}
index++;
temp = tn;
} while (index < cArray.length);
for(TrieNode n : first.children){
if(n != null){
DQ.add(n);
}
}
}
while (true) {
ListNode next = curr.next;
curr.next = prev;
if (next == null || next.next == null) {
prev.next = next;
break;
}
prev.next = next.next;
prev = next;
curr = prev.next;
}
return head;
}
HashMap put
HashMap get
public K put(K key, K value) {
int hash = hash(key);
int index = hash & (table.length - 1);
if (key already present ) {
return oldValue;
}
addToHashTable(hash, key, value, index);
return null;
}
Reservior Sampling
Randomly choose k samples from n elements
public void selectKItems(int stream[], int n, int k) {
Random rand = new Random();
int reservoir[k];
for (int i = 0; i < k; i++) {
reservoir[i] = stream[i];
}
for (int i = k; i < n; i++) {
// Pick a random index from 0 to i.
int j = rand.nextInt(i + 1);
if (j < k) {
reservoir[j] = stream[i];
}
}
}
The probability of ith element going to second position =
(probability that ith element is not picked in previous iteration) x (probability that ith element is
picked in this iteration)
So the probability = ((n-1)/n) x (1/(n-1)) = 1/n
Time Planner
Implement a meeting planner that can schedule meetings between two persons at a time.
public int[] meetingPoint(int[][] timesA, int[][] timesB, int dur) {
if (timesA == 0 || timesB == 0) {
return null;
}
int i = 0;
int j = 0;
int result[] = new int[2];
while (i < timesA.length && j < timesB.length) {
int startA = timesA[i][0];
int endA = timesA[i][1];
int startB = timesB[j][0];
int endB = timesB[j][1];
int maxStart = Math.max(startA, startB);
int minEnd = Math.min(startB, endB);
int diff = minEnd - maxStart;
if (diff >= dur) {
int[0] = maxStart;
int[1] = minEnd;
break;
}
if (endA < endB) {
i++;
} else {
j++;
}
}
return result;
}
visited[i][j] = true;
if (distance < board[i][j]) {
board[i][j] = distance;
}
distance(board, i + 1, j, distance + 1, visited);
distance(board, i - 1, j, distance + 1, visited);
distance(board, i, j - 1, distance + 1, visited);
distance(board, i, j + 1, distance + 1, visited);
visited[i][j] =false;
}
}
base = base * 10 + (str.charAt(i) - '0');
i++;
}
return sign * base;
}
POW
public double myPow(double x, int n) {
if (n == Integer.MIN_VALUE && x == 2.0) {
return 0;
}
if(n == 0)
return 1;
if(n<0){
n = -n;
x = 1/x;
}
return (n%2 == 0) ? myPow(x*x, n/2) : x*myPow(x*x, n/2);
return len;
}
final marks the reference, not the object. You can't make that reference point to a
different hash table. But you can do anything to that object, including adding and
removing things.
Remove minimum number of characters so that two strings become anagram
Students Attendance
public boolean checkRecord(String s) {
int count = 0;
int continous = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == 'A') {
count++;
continous = 0;
} else if (ch == 'L') {
continous++;
} else {
continous = 0;
}
if (count > 1 || continous > 2) {
return false;
}
}
return true;
}
Text Wrap
Word Wrap
Word Justification
private static String textJustify(String[] words, int numOfWords) {
/**
* Find the number of remaining spaces after placing words from i to j in a line
*/
for (int i = 0; i < words.length; i++) {
spaces[i][i] = numOfWords - words[i].length();
for (int j = i + 1; j < words.length; j++) {
spaces[i][j] = spaces[i][j - 1] - words[j].length() - 1;
}
}
/**
* Find the cost it takes to put words from i to j on a line
*/
for (int i = 0; i < words.length; i++) {
for (int j = i; j < words.length; j++) {
if (spaces[i][j] < 0) {
cost[i][j] = Integer.MAX_VALUE;
} else {
cost[i][j] = spaces[i][j] * spaces[i][j];
}
}
}
/**
* Check if i to j words stay on same line.
* If they don't stay, find the word which breaks the lines
*/
int minCost[] = new int[words.length];
int result[] = new int[words.length];
for(int i = words.length - 1; i >= 0 ; i--) {
minCost[i] = cost[i][words.length-1];
result[i] = words.length;
for(int j = words.length - 1; j > i; j--){
if(cost[i][j-1] == Integer.MAX_VALUE){
continue;
}
if(minCost[i] > minCost[j] + cost[i][j-1]){
minCost[i] = minCost[j] + cost[i][j-1];
result[i] = j;
}
}
}
int i = 0;
int j;
return builder.toString();
}
isSubTree
sub tree
public boolean isSubtree(TreeNode s, TreeNode t) {
if (s == null) {
return false;
}
if (isSameTree(s, t)) {
return true;
}
return isSubtree(s.left, t) || isSubtree(s.right, t);
}
public boolean isSameTree(TreeNode s, TreeNode t) {
if (s == null && t == null) {
return true;
}
if (s != null && t != null && s.val == t.val && isSameTree(s.left, t.left) &&
isSameTree(s.right, t.right)) {
return true;
}
return false;
}
Valid Sudoku
public boolean isValidSudoku(char[][] board) {
for (int i = 0; i < 9; i++) {
HashSet<Character> rows = new HashSet<>();
HashSet<Character> cols = new HashSet<>();
HashSet<Character> grid = new HashSet<>();
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.' && !rows.add(board[i][j])) {
return false;
}
if (board[j][i] != '.' && !cols.add(board[j][i])) {
return false;
}
int r = (3 * (i / 3));
int c = (3 * (i % 3)) ;
if (board[r + j / 3][c + j % 3] != '.' && !grid.add(board[r + j / 3][c + j % 3])) {
return false;
}
}
}
return true;
}
for(int x : nums) {
int i = Arrays.binarySearch(dp, 0, len, x);
if(i < 0) i = -(i + 1);
dp[i] = x;
if(i == len) len++;
}
return len;
}
Quick Select
Kth largest/smallest element in an unsorted array O(n) and worst case O(n^2)
public class Solution {
public int findKthLargest(int[] nums, int k) {
int start = 0;
int end = nums.length - 1;
k = nums.length - k;
while (start < end) {
int pivot = partion(nums, start, end);
if (pivot == k) {
return nums[k];
}
if (k < pivot) {
end = pivot - 1;
} else {
start = pivot + 1;
}
}
return nums[start];
}
private int partion(int[] nums, int start, int end) {
int pivot = start;
Game of Life
public void gameOfLife(int[][] board) {
int row = board.length;
int col = board[0].length;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
int lives = getNeighbors(board, i, j);
if (board[i][j] == 1) {
if (lives >= 2 && lives <= 3) {
board[i][j] = 3; // Make the 2nd bit 1: 01 ---> 11
}
} else {
if (lives == 3) {
board[i][j] = 2;
}
}
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
board[i][j] >>= 1;
}
}
}
public int getNeighbors(int board[][], int i, int j) {
int lives = 0;
for(int x = i - 1; x <= i + 1; ++x) {
for(int y = j - 1; y <= j + 1; ++y) {
if(x >= 0 && x < board.length && y >= 0 && y < board[0].length) {
lives += board[x][y] & 1;
}
}
}
lives -= board[i][j] & 1;
return lives;
}
}
#Concatenated Words
/**
1. Create trie for all words in the list;
2. Iterate over the words and check if they are a combination of words
*/
public boolean isConcatenatedWord(String word, int count, TrieNode root) {
if (words == null || words.length() == 0) {
return false;
}
TrieNode curr = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (curr.children[ch - 'a'] == null) {
return false;
}
if (curr.children[ch - 'a'].isWord) {
if (i == word.length() - 1) {
return count >= 1;
}
if (isConcatenatedWord(word.substring(i + 1), count + 1, root) {
return true;
}
}
curr = curr.children[ch - 'a'];
}
return false;
}
Combination Sum 4
public int combinationSum4(int[] nums, int target) {
int[] comb = new int[target + 1];
comb[0] = 1;
for (int i = 1; i < comb.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (i - nums[j] >= 0) {
comb[i] += comb[i - nums[j]];
}
}
}
return comb[target];
}
Not in stable
start = head;
end = head;
while (curr != null) {
ListNode temp = curr.next;
if (curr.val < x) {
start.next = head;
head = start;
} else {
end.next = curr;
tail = curr;
}
curr = temp;
}
tail.next = null;
return head;
}
Num of Islands II
Find O(1), Union O(logn) TC (Nlogn)
public class Solution {
public List<Integer> numIslands2(int m, int n, int[][] positions) {
List<Integer> result = new ArrayList<>();
if (m == 0 || n == 0) {
return null;
}
int dirs[][] = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
int roots[] = new int[m * n];
Arrays.fill(roots, -1);
int count = 0;
for (int pos[] : positions) {
int root = n * pos[0] + pos[1]; // find the root
roots[root] = root;
count++;
}
result.add(count);
}
return result;
}
public int findNeighbors(int[] roots, int i) {
while (i != roots[i]) {
roots[i] = roots[roots[i]];
i = roots[i];
}
return i;
}
}
Alien Dictionary
public class Solution {
int N = 26;
public String alienOrder(String[] words) {
int visited[] = new int[N];
Arrays.fill(visited, -1);
boolean adj[][] = new boolean[N][N];
buildGraph(words, adj, visited);
Palindrome Permutation II
private List<String> list = new ArrayList<>();
}
public String getCode(String s) {
int arr[] = new int[s.length()];
arr[0] = 0;
char ch = s.charAt(0);
for (int i = 1; i < s.length(); i++) {
char curr = s.charAt(i);
arr[i] = curr - ch < 0 ? ((curr - ch) % 26) + 26 : curr - ch;
}
return Arrays.toString(arr);
}
}
Factor Combinations
public List<List<Integer>> getFactors(int n) {
List<List<Integer>> results = new ArrayList<>();
List<Integer> curr = new ArrayList<>();
perm(n, results, curr, 2);
return results;
}
public void perm(int n, List<List<Integer>> results, List<Integer> curr, int start) {
if (n == 1) {
if (curr.size() > 1) {
results.add(new ArrayList<>(curr));
}
return;
}
for (int i = start; i <= n; i++) {
if (n % i == 0) {
curr.add(i);
perm(n / i, results, curr, i);
curr.remove(curr.size() - 1); }}}
Happy Number
public int sqSum(int n) {
int sum = 0;
while (n != 0) {
int temp = n % 10;
sum += temp * temp;
n = n / 10;
}
return sum;
}
public boolean isHappy(int n) {
if (n == 1) {
return true;
}
int slow = n;
int fast = sqSum(n);
while (slow != fast) {
slow = sqSum(slow);
fast = sqSum(sqSum(fast));
}
return slow == 1;
}
Decode Ways
public int numDecodings(String s) {
if (s== null || s.length() == 0) {
return 0;
}
int dp[] = new int[s.length() + 1];
dp[0] = 1;
dp[1] = s.charAt(0) == '0' ? 0 : 1;
for (int i = 2; i <= s.length(); i++) {
int s1 = Integer.parseInt(s.substring(i - 1, i));
int s2 = Integer.parseInt(s.substring(i - 2, i));
if (s1 >= 1 && s1 <= 9) {
dp[i] += dp[i - 1];
}
if (s2 >= 10 && s2 <= 26) {
dp[i] += dp[i - 2];
} return dp[s.length()]; }
Word Pattern II
boolean isMatch(String str, int i, String pat, int j, Map<Character, String> map,
Set<String> set) {
// base case
if (i == str.length() && j == pat.length()) {
return true;
}
if (i == str.length() || j == pat.length()) {
return false;
}
if (set.contains(p)) {
continue;
}
// create or update it
map.put(c, p);
// backtracking
map.remove(c);
}
Maze I
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
if (maze.length == 0 || maze[0].length == 0) {
return false;
}
int m = maze.length;
int n = maze[0].length;
boolean visited[][] = new boolean[m][n];
int dirs[][] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
Queue<int[]> q = new LinkedList<>();
q.add(start);
while (!q.isEmpty()) {
int[] entry = q.remove();
if (entry[0] == destination[0] && entry[1] == destination[1]) {
return true;
}
for (int dir[] : dirs) {
int x = entry[0] + dir[0];
int y = entry[1] + dir[1];
while (x >= 0 && x < maze.length && y >= 0 && y < maze[0].length && maze[x][y] == 0) {
x += dir[0];
y += dir[1];
}
x -= dir[0];
y -= dir[1];
if (!visited[x][y]) {
visited[x][y] = true;
q.add(new int[]{x, y});
}
}
}
return false;
}
Maze II O(mn log (mn)
public int shortestDistance(int[][] maze, int[] start, int[] destination) {
int m = maze.length;
int n = maze[0].length;
int dist[][] = new int[m][n];
for (int[] row: dist)
Arrays.fill(row, Integer.MAX_VALUE);
dist[start[0]][start[1]] = 0;
shortest(maze, start, destination, dist);
return dist[destination[0]][destination[1]] == Integer.MAX_VALUE ? -1 : dist[destination[0]]
[destination[1]];
}
public void shortest(int[][] maze, int[] start, int[] destination, int[][] dist) {
PriorityQueue<int []> pq = new PriorityQueue<>((a, b) -> a[2] - b[2]);
pq.offer(new int[]{start[0], start[1], 0});
int[][] dirs = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
while (!pq.isEmpty()) {
int locs[] = pq.poll();
for (int dir[] : dirs) {
int x = locs[0] + dir[0];
int y = locs[1] + dir[1];
int count = 0;
while (x >= 0 && x < maze.length && y < maze[0].length && y >= 0 && maze[x][y] == 0) {
x += dir[0];
y += dir[1];
count++;
}
x -= dir[0];
y -= dir[1];
if (dist[start[0]][start[1]] + count < dist[x][y]) {
dist[x][y] = dist[start[0]][start[1]] + count;
pq.offer(new int[]{x, y, dist[x][y]});
}
}
}
}
Dungeons Game
public int calculateMinimumHP(int[][] dungeon) {
int m = dungeon.length;
int n = dungeon[0].length;
int dp[] = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[n - 1] = 1;
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
dp[j] = Math.min(dp[j], dp[j + 1]) - dungeon[i][j];
dp[j] = Math.max(dp[j], 1);
}
}
return dp[0];
}
Distinct Subsequences
public int numDistinct(String s, String t) {
int m = s.length();
int n = t.length();
int dp[][] = new int[m + 1][n + 1];
for (int i = 0; i < m; i++) {
dp[i][0] = 1;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[m][n];
}
public void remove(String s, List<String> ans, int last_i, int last_j, char[] par) {
int stack = 0;
for (int 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()),
ans, i, j, par);
}
}
return;
}
String reversed = new StringBuilder(s).reverse().toString();
if (par[0] == '(') {// finished left to right
remove(reversed, ans, 0, 0, new char[]{')', '('});
} else {// finished right to left
ans.add(reversed);
}
}
Palindrome Paritioning II
Min cuts to partition a palindrome
public int minCut(String s) {
char c[] = s.toCharArray();
int n = s.length();
int cut[] = new int[n];
boolean pal[][] = new boolean[n][n];
for (int i = 0; i < n; i++) {
int min = i;
for (int j = 0; j <= i; j++) {
if ((c[j] == c[i]) && (j + 1 > i - 1 || pal[j + 1][i - 1])) {
pal[j][i] = true;
min = j == 0 ? 0 : Math.min(min, cut[j - 1] + 1);
}
}
cut[i] = min;
}
return cut[n - 1];
}
int i = 1;
int j = 0;
while (i < s.length()) {
if (s.charAt(i) == s.charAt(j)) {
table[i] = j + 1;
i++;
j++;
} else {
if (j != 0) {
j = table[j - 1];
} else {
table[i] = 0;
i++;
}
}
}
return table;
}
Generalized Abbrevations
public List<String> generateAbbreviations(String word) {
List<String> result = new ArrayList<>();
if (word == null || word.length() == 0) {
result.add("");
return result;
}
generate(word, result, 0, "", 0);
return result;
}
public void generate(String word, List<String> result, int index, String curr, int count) {
if (index == word.length()) {
if (count > 0) {
curr += count;
}
result.add(curr);
return;
}
generate(word, result, index + 1, curr, count + 1);
generate(word, result, index + 1, curr + (count > 0 ? count : "") + word.charAt(index), 0);
}
Russian Doll Envelope Sort by ascending width. If widths are equal descend heights.
public int maxEnvelopes(int[][] envelopes) {
Arrays.sort(envelopes, new Comparator<int[]>(){
@Override
public int compare(int[] arr1, int[] arr2){
if(arr1[0] == arr2[0])
return arr2[1] - arr1[1];
else
return arr1[0] - arr2[0];
}
});
}
public int dfs(Long[] debts, int pos, int count) {
while (pos < debts.length && debts[pos] == 0) {
pos++;
}
if (pos >= debts.length) {
return count;
}
int res = Integer.MAX_VALUE;
for (int i = pos + 1; i < debts.length; i++) {
if (debts[i] * debts[pos] < 0) {
debts[i] += debts[pos];
res = Math.min(res, dfs(debts, pos + 1, count + 1));
debts[i] = debts[i] - debts[pos];
}
} return res;
}
Minesweeper
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
public char[][] updateBoard(char[][] board, int[] click) {
int m = board.length;
int n = board[0].length;
int x = click[0];
int y = click[1];
if (board[x][y] == 'M') {
board[x][y] = 'X';
} else {
dfs(board, m, n, x, y);
}
return board;
}
public void dfs(char[][] board, int m, int n, int x, int y) {
if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] != 'E') {
return;
}
int mine = getAdjMines(board, m, n, x, y);
if (mine > 0) {
board[x][y] = (char) ('0' + mine);
} else {
board[x][y] = 'B';
for (int dir[] : dirs) {
dfs(board, m, n, x + dir[0], y + dir[1]);
}
}
}
int m = matrix.length;
int n = matrix[0].length;
int res = 0;
int dp[][] = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (matrix[i- 1][j - 1] == '1') {
dp[i][j] = Math.min(dp[i - 1][j], Math.min(dp[i][j - 1], dp[i - 1][j - 1])) + 1;
res = Math.max(res, dp[i][j]);
}
}
}
return res * res;
}
01 Matrix
public int[][] updateMatrix(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int dist[][] = new int[m][n];
for (int rows[] : dist) {
Arrays.fill(rows, Integer.MAX_VALUE);
}
Queue<int[]> q = new LinkedList<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
dist[i][j] = 0;
q.add(new int[]{i, j});
}
}
}
int dirs[][] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (!q.isEmpty()) {
int cell = q.remove();
for (int dir[] : dirs) {
int newRow = cell[0] + dir[0];
int newCol = cell[1] + dir[1];
if (newRow >= 0 || newRow < m || newCol >= 0 || newCol < n) {
if (dist[newRow][newCol] > 1 + dist[cell[0]][cell[1]]) {
dist[newRow][newCol] = 1 + dist[cell[0]][cell[1]]
q.add(new int[]{newRow, newCol});
}
}
}
}
return dist;
}
Teemo Attacking
public int findPoisonedDuration(int[] timeSeries, int duration) {
if (timeSeries == null || timeSeries.length == 0 || duration == 0) {
return 0;
}
int start = timeSeries[0];
int end = start + duration;
int res = 0;
for (int i = 1; i < timeSeries.length; i++) {
if (timeSeries[i] > end) {
res += end - start;
start = timeSeries[i];
}
end = timeSeries[i] + duration;
}
res += end - start;
return res;
}
Decode String
public String decodeString(String s) {
if (s == null || s.length() == 0) {
return "";
}
Stack<Integer> count = new Stack<>();
Stack<StringBuilder> sbStack = new Stack<>();
StringBuilder curr = new StringBuilder();
int k = 0;
for (char ch : s.toCharArray()) {
if (Character.isDigit(ch)) {
k = k * 10 + ch - '0';
} else if (ch == '[') {
count.push(k);
sbStack.push(curr);
curr = new StringBuilder();
k = 0;
} else if (ch == ']') {
StringBuilder tmp = curr;
curr = sbStack.pop();
int size = count.pop();
for (int i = 0; i < size; i++) {
curr.append(tmp);
}
} else {
curr.append(ch);
}
}
return curr.toString();
}
House Robber III
public int rob(TreeNode root) {
int res[] = robSub(root);
return Math.max(res[0], res[1]);
}
public int[] robSub(TreeNode root) {
if (root == null) {
return new int[2];
}
int l[] = robSub(root.left);
int r[] = robSub(root.right);
int res[] = new int[2];
res[0] = Math.max(l[0], l[1]) + Math.max(r[0], r[1]);
res[1] = root.val + l[0] + r[0];
return res;
}
Wildcard Matching
public boolean isMatch(String s, String p) {
if(s == null || p == null) {
return false;
}
boolean[][] state = new boolean[s.length() + 1][p.length() + 1];
state[0][0] = true;
for (int j = 1; j <= p.length(); j++) {
if (p.charAt(j - 1) == '*' && state[0][j - 1]) {
state[0][j] = true;
}
}
for (int i = 1; i < state.length; i++) {
for (int j = 1; j < state[0].length; j++) {
if (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '?') {
state[i][j] = state[i - 1][j - 1];
}
if (p.charAt(j - 1) == '*') {
state[i][j] = state[i - 1][j] || state[i][j - 1] ;
}
}
}
return state[s.length()][p.length()];
}
@Override
public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character,
Integer> o2) {
if (o1.getValue() == o2.getValue()) {
return Integer.compare(o1.getKey(), o2.getKey());
}
return Integer.compare(o2.getValue(), o1.getValue());
}
});
pq.addAll(map.entrySet());
if (pq.isEmpty()) {
return "";
}
vals.put(key, value);
counts.put(key, 1);
min = 1;
lists.get(1).add(key);
}
public void incrementCount(int key) {