0% found this document useful (0 votes)
7 views

impl

The document provides implementations of various sorting algorithms, including Merge Sort and Quick Sort, as well as graph representations using adjacency lists and matrices. It also covers the Traveling Salesman problem, backtracking techniques for the N-Queen problem, and heap operations for merging k sorted arrays. Additionally, it discusses tree traversal methods such as Morris Inorder and iterative Preorder and Postorder traversals.

Uploaded by

Rahul Thorat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

impl

The document provides implementations of various sorting algorithms, including Merge Sort and Quick Sort, as well as graph representations using adjacency lists and matrices. It also covers the Traveling Salesman problem, backtracking techniques for the N-Queen problem, and heap operations for merging k sorted arrays. Additionally, it discusses tree traversal methods such as Morris Inorder and iterative Preorder and Postorder traversals.

Uploaded by

Rahul Thorat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Implementation

Sort
Merge Sort

public void mergeSort(int[] arr, int left, int right) {


if (left < right) {
int mid = (left + right) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}

public void merge(int[] arr, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;

int[] leftArray = new int[n1];


int[] rightArray = new int[n2];

for (int i = 0; i < n1; i++) {


leftArray[i] = arr[left + i];
}
for (int i = 0; i < n2; i++) {
rightArray[i] = arr[mid + 1 + i];
}

int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
arr[k++] = leftArray[i++];
} else {
arr[k++] = rightArray[j++];

Implementation 1
}
}

while (i < n1) {


arr[k++] = leftArray[i++];
}
while (j < n2) {
arr[k++] = rightArray[j++];
}
}

Quick Sort

public void quickSort(int[] arr, int low, int high) {


if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}

public int partition(int[] arr, int low, int high) {


int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;

Implementation 2
return i + 1;
}

Graph

Adj List

public class GfG {


public static void addEdge(List<List<Integer>> adj, int i, int j) {
adj.get(i).add(j);
adj.get(j).add(i); // Undirected
}
public static void displayAdjList(List<List<Integer>> adj) {
for (int i = 0; i < adj.size(); i++) {
System.out.print(i + ": "); // Print the vertex
for (int j : adj.get(i)) {
System.out.print(j + " "); // Print its adjacent
}
System.out.println();
}
}
public static void main(String[] args) {

// Create a graph with 4 vertices and no edges


int V = 4;
List<List<Integer>> adj = new ArrayList<>(V);
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}
addEdge(adj, 0, 1); addEdge(adj, 0, 2);
System.out.println("Adjacency List Representation:");
displayAdjList(adj);
}
}

Adj Mat

Implementation 3
import java.util.Arrays;

public class GfG {


public static void main(String[] args) {
int V = 4;
int[][] mat = new int[V][V];

// Now add edges one by one


addEdge(mat, 0, 1);
addEdge(mat, 0, 2);
addEdge(mat, 1, 2);
}
}

TRAVELLING SALESMAN
class GfG {

static int totalCost(int mask, int curr, int n,


int[][] cost, int[][] memo) {

// Base case: if all cities are visited, return the


// cost to return to the starting city (0)
if (mask == (1 << n) - 1) {
return cost[curr][0];
}

// If the value has already been computed, return it


// from the memo table
if (memo[curr][mask] != -1) {
return memo[curr][mask];
}

int ans = Integer.MAX_VALUE;

Implementation 4
// Try visiting every city that has not been visited
// yet
for (int i = 0; i < n; i++) {
if ((mask & (1 << i))
== 0) {

// If city i is not visited


// Visit city i and update the mask
ans = Math.min(
ans, cost[curr][i]
+ totalCost(mask | (1 << i), i,
n, cost, memo));
}
}

// Memoize the result


return memo[curr][mask] = ans;
}

BackTrack

N - Queen Problem

Lower diagonal formula row + col is same


and other diagonal is row-col+N-1

Heaps

Maxheap

PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(


Collections.reverseOrder());

Merge k sorted arrays insert 1st in min heap then next during extract min

public class MergeKSortedArrays {

Implementation 5
private static class HeapNode
implements Comparable<HeapNode> {
int x;
int y;
int value;

HeapNode(int x, int y, int value)


{
this.x = x;
this.y = y;
this.value = value;
}

@Override public int compareTo(HeapNode hn)


{
if (this.value <= hn.value) {
return -1;
}
else {
return 1;
}
}
}

public static ArrayList<Integer>


mergeKArrays(int[][] arr, int K)
{
ArrayList<Integer> result
= new ArrayList<Integer>();
PriorityQueue<HeapNode> heap
= new PriorityQueue<HeapNode>();

// Initially add only first column of elements. First


// element of every array
for (int i = 0; i < arr.length; i++) {
heap.add(new HeapNode(i, 0, arr[i][0]));

Implementation 6
}

HeapNode curr = null;


while (!heap.isEmpty()) {
curr = heap.poll();
result.add(curr.value);

// Check if next element of curr min exists,


// then add that to heap.
if (curr.y < (arr[curr.x].length - 1)) {
heap.add(
new HeapNode(curr.x, curr.y + 1,
arr[curr.x][curr.y + 1]));
}
}

return result;
}
}

k largest(or smallest) elements in an array Largest use min heap store only
k elements then extract and heaping

class BinaryHeap {
static int capacity; /*Maximum elements that can be stored in heap*/
static int size; /*Current no of elements in heap*/
static int arr[]; /*array for storing the keys*/

BinaryHeap(int cap) {
capacity = cap; /*Assigning the capacity*/
size = 0; /*Intailly size of hepa is zero*/
arr = new int[capacity]; /*Creating a array*/
}

/*returns the parent of ith Node*/

Implementation 7
static int parent(int i) {
return (i - 1) / 2;
}
/*returns the left child of ith Node*/
static int left(int i) {
return 2 * i + 1;
}
/*Returns the right child of the ith Node*/
static int right(int i) {
return 2 * i + 2;
}

/*Insert a new key x*/


static void Insert(int x) {
if (size == capacity) {
System.out.println("Binary Heap Overflown");
return;
}
arr[size] = x; /*Insert new element at end*/
int k = size; /*store the index ,for checking heap property*/
size++; /*Increase the size*/

/*Fix the min heap property*/


while (k != 0 && arr[parent(k)] > arr[k]) {
int temp = arr[parent(k)];
arr[parent(k)] = arr[k];
arr[k] = temp;
k = parent(k);
}
}

static void Heapify(int ind) {


int ri = right(ind); /*right child*/
int li = left(ind); /*left child*/
int smallest = ind; /*intially assume violated value in Min value*/
if (li < size && arr[li] < arr[smallest])

Implementation 8
smallest = li;
if (ri < size && arr[ri] < arr[smallest])
smallest = ri;
/*smallest will store the minvalue index*/
/*If the Minimum among the three nodes is the parent itself,
that is Heap property satisfied so stop else call function recursively on Min
if (smallest != ind) {
int temp = arr[ind];
arr[ind] = arr[smallest];
arr[smallest] = temp;
Heapify(smallest);
}
}
static int getMin() {
return arr[0];
}
static int ExtractMin() {
if (size <= 0)
return Integer.MAX_VALUE;
if (size == 1) {
size--;
return arr[0];
}
int mini = arr[0];
arr[0] = arr[size - 1]; /*Copy last Node value to root Node value*/
size--;
Heapify(0); /*Call heapify on root node*/
return mini;
}
static void Decreasekey(int i, int val) {
arr[i] = val; /*Updating the new_val*/
while (i != 0 && arr[parent(i)] > arr[i]) /*Fixing the Min heap*/ {
int temp = arr[parent(i)];
arr[parent(i)] = arr[i];
arr[i] = temp;
i = parent(i);

Implementation 9
}
}
static void Delete(int i) {
Decreasekey(i, Integer.MIN_VALUE);
ExtractMin();
}
static void print() {
for (int i = 0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
}

Sorting

count inversions in array - for every 2 sorted arrays cout inversions using
merge sort

median of 2 sorted arrays - how many from 1st array and second array
until n

static double medianOf2(int[] a, int[] b) {


int n = a.length, m = b.length;
int i = 0, j = 0;

// m1 to store the middle element


// m2 to store the second middle element
int m1 = -1, m2 = -1;

// Loop till (m + n)/2


for (int count = 0; count <= (m + n) / 2; count++) {
m2 = m1;

// If both the arrays have remaining elements


if (i != n && j != m)
m1 = (a[i] > b[j]) ? b[j++] : a[i++];

Implementation 10
// If only a[] has remaining elements
else if (i < n)
m1 = a[i++];

// If only b[] has remaining elements


else
m1 = b[j++];
}

// Return median based on odd/even size


if ((m + n) % 2 == 1)
return m1;
else
return (m1 + m2) / 2.0;
}

Trees
Morris

// TreeNode structure
class TreeNode {
int val;
TreeNode left;
TreeNode right;

public TreeNode(int x) {
val = x;
left = null;
right = null;
}
}

public class Solution {


// Function to perform iterative Morris

Implementation 11
// inorder traversal of a binary tree
public List<Integer> getInorder(TreeNode root) {
// List to store the
// inorder traversal result
List<Integer> inorder = new ArrayList<>();
// Pointer to the current node,
// starting from the root
TreeNode cur = root;

// Loop until the current


// node is not NULL
while (cur != null) {
// If the current node's
// left child is NULL
if (cur.left == null) {
// Add the value of the current
// node to the inorder list
inorder.add(cur.val);
// Move to the right child
cur = cur.right;
} else {
// If the left child is not NULL,
// find the predecessor (rightmost node
// in the left subtree)
TreeNode prev = cur.left;
while (prev.right != null && prev.right != cur) {
prev = prev.right;
}

// If the predecessor's right child


// is NULL, establish a temporary link
// and move to the left child
if (prev.right == null) {
prev.right = cur;
cur = cur.left;
} else {

Implementation 12
// If the predecessor's right child
// is already linked, remove the link,
// add current node to inorder list,
// and move to the right child
prev.right = null;
inorder.add(cur.val);
cur = cur.right;
}
}
}

// Return the inorder


// traversal result
return inorder;
}

public static void main(String[] args) {


TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.left.right.right = new TreeNode(6);

Solution sol = new Solution();

List<Integer> inorder = sol.getInorder(root);

System.out.print("Binary Tree Morris Inorder Traversal: ");


for (int i = 0; i < inorder.size(); i++) {
System.out.print(inorder.get(i) + " ");
}
System.out.println();
}
}

Implementation 13
PreOrder Stack

// Java program to implement iterative preorder traversal

class BinaryTree {

Node root;

void iterativePreorder()
{
iterativePreorder(root);
}
void iterativePreorder(Node node)
{

// Base Case
if (node == null) {
return;
}

// Create an empty stack and push root to it


Stack<Node> nodeStack = new Stack<Node>();
nodeStack.push(root);

/* Pop all items one by one. Do following for every popped item
a) print it
b) push its right child
c) push its left child
Note that right child is pushed first so that left is processed first */
}

PostOrder 2 stacks
class GfG {

// Function to do post-order traversal


// using two stacks

Implementation 14
static ArrayList<Integer> postOrder(Node root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}

// Create two stacks


Stack<Node> stk1 = new Stack<>();
Stack<Node> stk2 = new Stack<>();

// Push root to first stack


stk1.push(root);
Node curr;

// Run while first stack is not empty


while (!stk1.isEmpty()) {

// Pop from stk1 and push it to stk2


curr = stk1.pop();
stk2.push(curr);

// Push left and right children of


// the popped node
if (curr.left != null) {
stk1.push(curr.left);
}
if (curr.right != null) {
stk1.push(curr.right);
}
}

// Collect all elements from second stack


while (!stk2.isEmpty()) {
curr = stk2.pop();
result.add(curr.data);
}

Implementation 15
return result;
}

Postorder 1 stack

static List<Integer> postOrder(Node root) {


// Check if the tree is empty
if (root == null)
return new ArrayList<>();

Node curr = root;


Stack<Node> stack = new Stack<>();
List<Integer> postorder = new ArrayList<>();

// Traverse the tree until


// current node is not null
// or the stack is not empty
while (curr != null || !stack.isEmpty()) {
// If current node is not null,
// push it onto the stack
// and move to its left child
if (curr != null) {
stack.push(curr);
curr = curr.left;
} else {
// If current node is null,
// check the right child of the
// top node in the stack
Node temp = stack.peek().right;

// If right child is also null


// or already visited, it means
// we can process the top node now
if (temp == null) {
// Get the top node from stack

Implementation 16
temp = stack.pop();
// Add the node's data to
// the postorder traversal list
postorder.add(temp.data);

// Check if there are more


// nodes to pop whose right
// subtree is also processed
while (!stack.isEmpty() && temp == stack.peek().right) {
temp = stack.pop();
postorder.add(temp.data);
}
} else {
// If right child exists,
// set current node to it
curr = temp;
}
}
}
// Return the list containing the
// Postorder Traversal Sequence
return postorder;
}

// Java program to populate inorder successor of all nodes


void populateNext(Node node)
{
// The first visited node will be the rightmost node
// next of the rightmost node will be NULL
if (node != null) {
// First set the next pointer in right subtree
populateNext(node.right);

// Set the next as previously visited node in


// reverse Inorder
node.next = next;

Implementation 17
// Change the prev for subsequent node
next = node;

// Finally, set the next pointer in left subtree


populateNext(node.left);
}
}

//min max tournament


```
static Pair getMinMax(int arr[], int low, int high)
{
Pair minmax =new Pair();
Pair mml =new Pair();
Pair mmr =new Pair();
int mid;

// If there is only one elementif (low == high) {


minmax.max = arr[low];
minmax.min = arr[low];
return minmax;
}

/* If there are two elements */if (high == low + 1) {


if (arr[low] > arr[high]) {
minmax.max = arr[low];
minmax.min = arr[high];
}
else {
minmax.max = arr[high];
minmax.min = arr[low];
}
return minmax;
}

Implementation 18
/* If there are more than 2 elements */ mid = (low + high) / 2;
mml = getMinMax(arr, low, mid);
mmr = getMinMax(arr, mid + 1, high);

/* compare minimums of two parts*/if (mml.min < mmr.min) {


minmax.min = mml.min;
}
else {
minmax.min = mmr.min;
}

/* compare maximums of two parts*/if (mml.max > mmr.max) {


minmax.max = mml.max;
}
else {
minmax.max = mmr.max;
}

return minmax;
}

BST
https://www.geeksforgeeks.org/print-common-nodes-in-two-binary-search-
trees/
https://www.geeksforgeeks.org/construct-bst-from-given-preorder-
traversa/#efficient-pass-range-in-recursion

https://www.geeksforgeeks.org/fix-two-swapped-nodes-of-bst/#expected-
approach-using-one-traversal-on-time-and-oh-space

Linked List

LinkedList<String> l =new LinkedList<String>();

Add/Update: add(), addFirst(), addLast(), set()

Implementation 19
Remove: remove(), removeFirst(), removeLast(), clear()
Access: get(), getFirst(), getLast(), peek(), peekFirst(), peekLast()
Search: contains(), indexOf(), lastIndexOf()
Queue/Deque: offer(), offerFirst(), offerLast(), poll(), pollFirst(), pollLast()
Utility: size(), isEmpty(), toArray(), iterator()

LinkedList<String> list = new LinkedList<>();


for (String element : list) {
System.out.println(element);
}

Iterator<String> iterator = list.iterator();


while (iterator.hasNext()) {
System.out.println(iterator.next());
}

Stacks/queue

Longest Valid Parentheses Substring

Stack Methods in Java:

Stack<String> stack = new Stack<>();

Push/Pop: push(E item) , pop() – Add and remove elements.

Peek: peek() – View the top element without removing.

Search: search(Object o) – Find the position of an element.

Queue Methods in Java:

Add/Remove: add(E e) , offer(E e) , poll() , remove() – Add and remove elements.

Peek/Element: peek() , element() – View the front element without removing.

Size: size() , isEmpty() – Check the number of elements and if the queue is
empty.

Deque Methods in Java:

Implementation 20
Deque<String> deque = new LinkedList<>();

Add/Remove: addFirst(E e) , addLast(E e) , offerFirst(E e) , offerLast(E e) , removeFirst() ,


removeLast() , pollFirst() , pollLast() – Add or remove elements from both ends.

Peek: peekFirst() , peekLast() – View the first or last element without removing.

Access: getFirst() , getLast() – Retrieve the first or last element.

Size: size() , isEmpty() – Check the number of elements and if the deque is
empty.

Hashmap
Working

public class MyHashMap<K, V> {


private static final int DEFAULT_CAPACITY = 16;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;

private int capacity;


private float loadFactor;
private int size;
private Node&lt;K, V&gt;[] table;

public MyHashMap() {
this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
}

public MyHashMap(int capacity, float loadFactor) {


this.capacity = capacity;
this.loadFactor = loadFactor;
this.table = (Node&lt;K, V&gt;[]) new Node[capacity];
}

private static class Node&lt;K, V&gt; {

Implementation 21
final K key;
V value;
Node&lt;K, V&gt; next;

Node(K key, V value, Node&lt;K, V&gt; next) {


this.key = key;
this.value = value;
this.next = next;
}
}

private int hash(K key) {


return key.hashCode() % capacity;
}

public void put(K key, V value) {


int index = hash(key);
Node<K, V> node = table[index];
while (node != null) {
if (node.key.equals(key)) {
node.value = value;
return;
}
node = node.next;
}
Node<K, V> newNode = new Node<>(key, value);
newNode.next = table[index];
table[index] = newNode;
size++;
if (size > capacity * loadFactor) {
resize();
}
}

Implementation 22
public V get(K key) {
int index = hash(key);
Node&lt;K, V&gt; node = table[index];
while (node != null) {
if (node.key.equals(key)) {
return node.value;
}
node = node.next;
}
return null;
}

public void remove(K key) {


int index = hash(key);
Node&lt;K, V&gt; node = table[index];
Node&lt;K, V&gt; prev = null;
while (node != null) {
if (node.key.equals(key)) {
if (prev == null) {
table[index] = node.next;
} else {
prev.next = node.next;
}
size--;
return;
}
prev = node;
node = node.next;
}
}

private void resize() {


int newCapacity = capacity * 2;
Node<K, V>[] newTable = new Node[newCapacity];
for (int i = 0; i < capacity; i++) {
Node<K, V> node = table[i];

Implementation 23
while (node != null) {
Node<K, V> next = node.next;
int index = hash(node.key);
node.next = newTable[index];
newTable[index] = node;
node = next;
}
}
table = newTable;
capacity = newCapacity;
}

Strings
https://www.geeksforgeeks.org/longest-palindromic-substring/

https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-
containing-all-characters-of-another-string/

Arrays
https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/

Find zeroes to be flipped so that no of 1 is maximum

Implementation 24

You might also like