Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

1.

Heap Sort

import java.util.*;

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++){
arr[i] = sc.nextInt();
}
Arrays.sort(a);
for(int i=0; i<n; i++){
System.out.print(a[i] + " ");
}
}
}

2.Winner tree

import java.util.*;

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++){
arr[i] = sc.nextInt();
}
Arrays.sort(a);
System.out.print(a[1]);
}
}

3.BFS
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

class Graph {
int vertices;
LinkedList<Integer>[] adjList;

@SuppressWarnings("unchecked")
Graph(int vertices) {
this.vertices = vertices;
adjList = new LinkedList[vertices];
for (int i = 0; i < vertices; ++i)
adjList[i] = new LinkedList<>();
}

void addEdge(int u, int v) {


adjList[u].add(v);
}

void bfs(int startNode) {


Queue<Integer> queue = new LinkedList<>();
boolean[] visited = new boolean[vertices];

visited[startNode] = true;
queue.add(startNode);

while (!queue.isEmpty()) {
int currentNode = queue.poll();
System.out.print(currentNode + " ");
for (int neighbor : adjList[currentNode]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.add(neighbor);
}
}
}
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int vertices = scanner.nextInt();
if(vertices <= 0)
{
System.out.print("Graph doesn't exist");
}
else
{
Graph graph = new Graph(vertices);
while (true) {
int u = scanner.nextInt();
int v = scanner.nextInt();
if (u == -1 && v == -1)
break;
graph.addEdge(u, v);
}

System.out.print("BFS : " );
graph.bfs(0);

scanner.close();
}
}
}
import java.util.*;
import java.util.Map.Entry;

class Node {
int data, hd;
Node left, right;

public Node(int data) {


this.data = data;
left = right = null;
this.hd = Integer.MAX_VALUE;
}
}

4.DFS
import java.util.*;

public class Main {


static class Graph {
private int V;
private LinkedList<Integer> adj[];

@SuppressWarnings("unchecked")
Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}

void addEdge(int v, int w) { // Corrected method


adj[v].add(w); // Add edge from v to w
adj[w].add(v); // Add edge from w to v for undirected graph
}

void DFSUtil(int v, boolean visited[]) {


visited[v] = true;
System.out.print(v + " ");

Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}
}

void DFS(int v) {
boolean visited[] = new boolean[V];
DFSUtil(v, visited);
}
}

public static void main(String args[]) {


Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // Number of nodes
int m = scanner.nextInt(); // Number of edges

Graph g = new Graph(n);

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


int u = scanner.nextInt();
int v = scanner.nextInt();
g.addEdge(u, v);
}

g.DFS(0);
}
}

5.All views
import java.util.*;
import java.util.Map.Entry;

class Node {
int data, hd;
Node left, right;

public Node(int data) {


this.data = data;
left = right = null;
this.hd = Integer.MAX_VALUE;
}
}

public class Main {


static Node root;

private List<Integer> path1 = new ArrayList<>();


private List<Integer> path2 = new ArrayList<>();

static Node build(String s[]) {


if (s[0] == "N" || s.length == 0)
return null;
Node root = new Node(Integer.parseInt(s[0]));
Queue<Node> q = new LinkedList<Node>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < s.length) {
Node curr = q.poll();
String cval = s[i];
if (!cval.equals("N")) {
int h = Integer.parseInt(cval);
curr.left = new Node(h);
q.add(curr.left);
}
i++;
if (i >= s.length)
break;
cval = s[i];
if (!cval.equals("N")) {
int h = Integer.parseInt(cval);
curr.right = new Node(h);
q.add(curr.right);
}
i++;
}
return root;
}

// Right View
void rightview(Node root) {
if (root == null)
return;
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int n = q.size();
for (int i = 0; i < n; i++) {
Node curr = q.peek();
q.remove();
if (i == n - 1) {
System.out.print(curr.data + " ");
if (curr.left != null)
q.add(curr.left);
if (curr.right != null)
q.add(curr.right);
}
}
}
}

// Left View
void leftview(Node root) {
if (root == null)
return;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int n = queue.size();
for (int i = 1; i <= n; i++) {
Node temp = queue.poll();
if (i == 1)
System.out.print(temp.data + " ");
if (temp.left != null)
queue.add(temp.left);
if (temp.right != null)
queue.add(temp.right);
}
}
}

static class QueueObj {


Node node;
int hd;

QueueObj(Node node, int hd) {


this.node = node;
this.hd = hd;
}
}

static void topview(Node root) {


if (root == null)
return;
Queue<QueueObj> q = new LinkedList<>();
Map<Integer, Integer> map = new HashMap<>();
int min = 0;
int max = 0;
q.add(new QueueObj(root, 0));
while (!q.isEmpty()) {
QueueObj curr = q.poll();
if (!map.containsKey(curr.hd))
map.put(curr.hd, curr.node.data);
if (curr.node.left != null) {
min = Math.min(min, curr.hd - 1);
q.add(new QueueObj(curr.node.left, curr.hd - 1));
}
if (curr.node.right != null) {
max = Math.max(max, curr.hd + 1);
q.add(new QueueObj(curr.node.right, curr.hd + 1));
}
}
for (; min <= max; min++)
System.out.print(map.get(min) + " ");
}

static void bottomview(Node root) {


if (root == null)
return;
int hd = 0;
Map<Integer, Integer> map = new TreeMap<>();
Queue<Node> queue = new LinkedList<Node>();
root.hd = hd;
queue.add(root);
while (!queue.isEmpty()) {
Node temp = queue.remove();
hd = temp.hd;
map.put(hd, temp.data);
if (temp.left != null) {
temp.left.hd = hd - 1;
queue.add(temp.left);
}
if (temp.right != null) {
temp.right.hd = hd + 1;
queue.add(temp.right);
}
}
Set<Entry<Integer, Integer>> set = map.entrySet();
Iterator<Entry<Integer, Integer>> iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, Integer> me = iterator.next();
System.out.print(me.getValue() + " ");
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int i;
Main ob = new Main();
String s[] = sc.nextLine().split(" ");
root = build(s);
ob.rightview(root);
System.out.println();
ob.leftview(root);
System.out.println();
ob.topview(root);
System.out.println();
ob.bottomview(root);
}
}

6.Vertical order traversal


import java.util.*;
import java.util.Map.Entry;

class Node {
int data;
Node left, right;

public Node(int data){


this.data = data;
left = right = null;
}
}

public class Solution {


static Node root;

private List<Integer> path1 = new ArrayList<>();


private List<Integer> path2 = new ArrayList<>();

static Node build(String s[]) {


if (s[0].equals("N") || s.length == 0)
return null;
Node root = new Node(Integer.parseInt(s[0]));
Queue<Node> q = new LinkedList<Node>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < s.length) {
Node curr = q.poll();
String cval = s[i];
if (!cval.equals("N")) {
int h = Integer.parseInt(cval);
curr.left = new Node(h);
q.add(curr.left);
}
i++;
if (i >= s.length)
break;
cval = s[i];
if (!cval.equals("N")) {
int h = Integer.parseInt(cval);
curr.right = new Node(h);
q.add(curr.right);
}
i++;
}
return root;
}

static void preOrderTraversal(Node root, long hd, long vd, TreeMap<Long, Vector<Integer> >
m){
if (root == null)
return;
long val = hd << 30 | vd;
if (m.get(val) != null)
m.get(val).add(root.data);
else {
Vector<Integer> v = new Vector<Integer>();
v.add(root.data);
m.put(val, v);
}
preOrderTraversal(root.left, hd - 1, vd + 1, m);
preOrderTraversal(root.right, hd + 1, vd + 1, m);
}

void verticalOrder(Node root){


TreeMap<Long, Vector<Integer> > mp = new TreeMap<>();
preOrderTraversal(root, 0, 1, mp);
int prekey = Integer.MAX_VALUE;
for (Entry<Long, Vector<Integer> > entry :mp.entrySet()) {
prekey = (int)(entry.getKey() >> 30);
for (int x : entry.getValue())
System.out.print(x + " ");
}
}

public static void main(String[] args){


Scanner sc=new Scanner(System.in);
Solution ob = new Solution();
String s[]=sc.nextLine().split(" ");
root = build(s);
ob.verticalOrder(root);
}
}

7.Bellman ford
import java.util.*;
class Solution
{
class Edge
{
int src, dest, weight;
Edge()
{
src = dest = weight = 0;
}
};
int V, E;
Edge edge[];
Solution(int v, int e)
{
V = v;
E = e;
edge = new Edge[e];
for (int i = 0; i < e; ++i)
edge[i] = new Edge();
}
void BellmanFord(Solution graph, int src)
{
int V = graph.V, E = graph.E;
int dist[] = new int[V];
for (int i = 0; i < V; ++i)
dist[i] = Integer.MAX_VALUE;
dist[src] = 0;
for (int i = 1; i < V; ++i)
{
for (int j = 0; j < E; ++j)
{
int u = graph.edge[j].src;
int v = graph.edge[j].dest;
int weight = graph.edge[j].weight;
if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}
for (int j = 0; j < E; ++j)
{
int u = graph.edge[j].src;
int v = graph.edge[j].dest;
int weight = graph.edge[j].weight;
if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v])
{
System.out.println(-1);
return;
}
}
for (int i = 0; i < V; ++i)
if (dist[i] != Integer.MAX_VALUE)
System.out.print(dist[i] + " ");
else
System.out.print(-1 + " ");
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int V = sc.nextInt();
int E = sc.nextInt();
Solution graph = new Solution(V, E);
for (int i = 0; i < E; i++)
{
int u = sc.nextInt();
int v = sc.nextInt();
int w = sc.nextInt();
graph.edge[i].src = u;
graph.edge[i].dest = v;
graph.edge[i].weight = w;
}
graph.BellmanFord(graph, 0);
}
}

8.Boundary traversal
import java.util.*;

public class BoundaryTraversal {


static class TreeNode {
int val;
TreeNode left, right;

TreeNode(int val) {
this.val = val;
left = right = null;
}
}

public static void printLeftBoundary(TreeNode root) {


if (root == null || (root.left == null && root.right == null)) {
return;
}
System.out.print(root.val + " ");
if (root.left != null) {
printLeftBoundary(root.left);
} else {
printLeftBoundary(root.right);
}
}

public static void printLeaves(TreeNode root) {


if (root == null) {
return;
}
printLeaves(root.left);
if (root.left == null && root.right == null) {
System.out.print(root.val + " ");
}
printLeaves(root.right);
}

public static void printRightBoundary(TreeNode root) {


if (root == null || (root.left == null && root.right == null)) {
return;
}
if (root.right != null) {
printRightBoundary(root.right);
} else {
printRightBoundary(root.left);
}
System.out.print(root.val + " ");
}

public static void printBoundaryTraversal(TreeNode root) {


if (root == null) {
return;
}
System.out.print(root.val + " ");
printLeftBoundary(root.left);
printLeaves(root);
printRightBoundary(root.right);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
String[] values = scanner.nextLine().split(" ");
TreeNode root = constructTree(values);
printBoundaryTraversal(root);
}

public static TreeNode constructTree(String[] values) {


if (values.length == 0 || values[0].equals("-1")) {
return null;
}
int idx = 0;
TreeNode root = new TreeNode(Integer.parseInt(values[idx++]));
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty() && idx < values.length) {
TreeNode curr = queue.remove();
if (!values[idx].equals("-1")) {
curr.left = new TreeNode(Integer.parseInt(values[idx]));
queue.add(curr.left);
}
idx++;
if (idx < values.length && !values[idx].equals("-1")) {
curr.right = new TreeNode(Integer.parseInt(values[idx]));
queue.add(curr.right);
}
idx++;
}
return root;
}
}

9.Binary heap
import java.util.*;

class TreeNode {
int val;
TreeNode left, right;

TreeNode(int val) {
this.val = val;
left = null;
right = null;
}
}

public class Main {


public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null)
return result;

Queue<TreeNode> queue = new LinkedList<>();


queue.offer(root);

while (!queue.isEmpty()) {
int size = queue.size();
TreeNode rightmost = null;

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


TreeNode node = queue.poll();

if (i == 0) // Add the value of the rightmost node at each level


result.add(node.val);

// Traverse the children, add the right child first


if (node.right != null)
queue.offer(node.right);
if (node.left != null)
queue.offer(node.left);
}
}

return result;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
// System.out.println("Enter the tree nodes in level-order (null for absent nodes):");
TreeNode root = buildTree(scanner);

Main solution = new Main();


List<Integer> result = solution.rightSideView(root);

// Print the output separated by spaces


// System.out.println("Right side view of the tree:");
for (int i = 0; i < result.size(); i++) {
System.out.print(result.get(i));
if (i < result.size() - 1)
System.out.print(" ");
}
System.out.println();
}

public static TreeNode buildTree(Scanner scanner) {


Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = null;

if (scanner.hasNextInt()) {
root = new TreeNode(scanner.nextInt());
queue.offer(root);
}

while (!queue.isEmpty()) {
TreeNode current = queue.poll();

if (scanner.hasNext()) {
String leftValue = scanner.next();
if (!leftValue.equals("null")) {
current.left = new TreeNode(Integer.parseInt(leftValue));
queue.offer(current.left);
}
}

if (scanner.hasNext()) {
String rightValue = scanner.next();
if (!rightValue.equals("null")) {
current.right = new TreeNode(Integer.parseInt(rightValue));
queue.offer(current.right);
}
}
}

return root;
}
}

10. Topo sort


import java.util.*;

public class TopologicalSort {

// Function to perform DFS and topological sorting


static void
topologicalSortUtil(int v, List<List<Integer> > adj,
boolean[] visited,
Stack<Integer> stack)
{
// Mark the current node as visited
visited[v] = true;

// Recur for all adjacent vertices


for (int i : adj.get(v)) {
if (!visited[i])
topologicalSortUtil(i, adj, visited, stack);
}

// Push current vertex to stack which stores the


// result
stack.push(v);
}

// Function to perform Topological Sort


static void topologicalSort(List<List<Integer> > adj,
int V)
{
// Stack to store the result
Stack<Integer> stack = new Stack<>();
boolean[] visited = new boolean[V];

// Call the recursive helper function to store


// Topological Sort starting from all vertices one
// by one
for (int i = 0; i < V; i++) {
if (!visited[i])
topologicalSortUtil(i, adj, visited, stack);
}

// Print contents of stack


System.out.print(
"Topological sorting of the graph: ");
while (!stack.empty()) {
System.out.print(stack.pop() + " ");
}
}

// Driver code
public static void main(String[] args)
{
// Number of nodes
int V = 4;
Scanner sc = new Scanner(System.in);
// Edges

List<List<Integer> > edges = new ArrayList<>();


for(int i = 0 ; i < V;i++)
{
int x = sc.nextInt();
int y = sc.nextInt();
edges.add(Arrays.asList(x, y));

// Graph represented as an adjacency list


List<List<Integer> > adj = new ArrayList<>(V);
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}

for (List<Integer> i : edges) {


adj.get(i.get(0)).add(i.get(1));
}

topologicalSort(adj, V);
}
}
11. Recover BST
import java.io.*;
import java.util.*;

class Node {
int data;
Node left;
Node right;

public Node(int d) {
data = d;
left = null;
right = null;
}
}

public class Solution {


public static Node buildTree(ArrayList<String> nodes) {
Queue<Node> q = new LinkedList<>();
if(nodes.size() == 0 || nodes.get(0) == "N")
return null;

int ind = 0;
int data = Integer.valueOf(nodes.get(ind++));

Node root = new Node(data);


q.offer(root);

while(!q.isEmpty() && ind < nodes.size()) {


// System.out.println(q.size());
int count = q.size();

for(int i=0; i<count && ind < nodes.size(); i++) {


Node curr = q.poll();

if(!nodes.get(ind).equals("N")) {
data = Integer.valueOf(nodes.get(ind));
curr.left = new Node(data);

q.offer(curr.left);
}
ind++;
if(ind == nodes.size())
break;
if(!nodes.get(ind).equals("N")) {
data = Integer.valueOf(nodes.get(ind));
curr.right = new Node(data);

q.offer(curr.right);
}
ind++;
}
}

return root;
}

public static void print(Node root) {


if(root == null)
return;

Queue<Node> q = new LinkedList<>();


q.offer(root);

// Node curr = null;


while(!q.isEmpty()) {
int count = q.size();

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


Node curr = q.poll();
System.out.print(curr.data + " ");

if(curr.left != null)
q.offer(curr.left);
if(curr.right != null)
q.offer(curr.right);
}
}
}

static Node prev = null;

public static void recover(Node root) {


if(root == null)
return;
recover(root.left);
if(prev != null && prev.data > root.data) {
if(from == null)
from = prev;
to = root;
}

prev = root;

recover(root.right);
}

public static void preOrder(Node root) {


if(root == null)
return;

System.out.print(root.data + " ");


preOrder(root.left);
preOrder(root.right);
}

static Node from = null;


static Node to = null;

public static void main(String[] args) {


prev = null;
from = null;
to = null;
Scanner sc = new Scanner(System.in);

String[] arr = sc.nextLine().trim().split(" ");


ArrayList<String> nodes = new ArrayList<>();
for(String x: arr)
nodes.add(x);

// System.out.println(Integer.valueOf("23"));
Node root = buildTree(nodes);
recover(root);
int temp = from.data;
from.data = to.data;
to.data = temp;
preOrder(root);
}
}

12. Dials
import java.util.*;
public class Graph {
static final int INF = Integer.MAX_VALUE;
private int V;
private ArrayList<ArrayList<Tuple> > adj;
public Graph(int v){
this.V = v;
this.adj = new ArrayList<ArrayList<Tuple> >();
for (int i = 0; i < v; i++)
this.adj.add(new ArrayList<Tuple>());
}
public void AddEdge(int u, int v, int w){
adj.get(u).add(new Tuple(v, w));
adj.get(v).add(new Tuple(u, w));
}
public void shortestPath(int src, int W){
int[] dist = new int[V];
Arrays.fill(dist, INF);
ArrayList<Integer>[] B = new ArrayList[W * V + 1];
for (int i = 0; i < W * V + 1; i++)
B[i] = new ArrayList<Integer>();
B[0].add(src);
dist[src] = 0;
int idx = 0;
while (true) {
while (B[idx].size() == 0 && idx < W * V)
idx++;
if (idx == W * V)
break;
int u = B[idx].get(0);
B[idx].remove(0);
for (Tuple i : adj.get(u)) {
int v = i.v;
int weight = i.w;
int du = dist[u];
int dv = dist[v];
if (dv > du + weight) {
dist[v] = du + weight;
dv = dist[v];
B[dv].add(0, v);
}
}
}

System.out.println("Vertex Distance from Source");


for (int i = 0; i < V; ++i)
System.out.println(i + "\t\t" + dist[i]);
}
static class Tuple {
int v, w;
Tuple(int v, int w){
this.v = v;
this.w = w;
}
}
public static void main(String[] args){
Scanner s=new Scanner(System.in);
int V = s.nextInt();
Graph g = new Graph(V);
int e=s.nextInt();
int st,en,d;

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


st=s.nextInt();
en=s.nextInt();
d=s.nextInt();
g.AddEdge(st,en,d);
}
g.shortestPath(0,e);
}
}

13. K-ary
import java.util.*;
public class KaryHeap {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int[] arr = new int[size+10];
for(int i=0; i<size; i++){
arr[i] = sc.nextInt();
}
int n = sc.nextInt();
int k = sc.nextInt();

buildHeap(arr, n, k);

System.out.println("Built Heap : ");


for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");

int element = 3;
insert(arr, n, k, element);
n++;

System.out.println("\nHeap after insertion of " + element + ": ");


for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");

System.out.println("\nExtracted max is " + extractMax(arr, n, k));


n--;

System.out.println("Heap after extract max: ");


for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}

public static void buildHeap(int[] arr, int n, int k) {


for (int i = (n - 1) / k; i >= 0; i--)
restoreDown(arr, n, i, k);
}

public static void insert(int[] arr, int n, int k, int elem) {


n++; // Increment n before insertion
arr[n-1] = elem; // Insert the element at the newly available index
restoreUp(arr, n - 1, k); // Restore the heap property upwards
}

public static int extractMax(int[] arr, int n, int k) {


int max = arr[0];
arr[0] = arr[n - 1];
restoreDown(arr, n - 1, 0, k);
return max;
}

public static void restoreDown(int[] arr, int len, int index, int k) {
int[] child = new int[k + 1];
while (true) {
for (int i = 1; i <= k; i++)
child[i] = (k * index + i) < len ? (k * index + i) : -1;

int maxChild = -1, maxChildIndex = 0;


for (int i = 1; i <= k; i++) {
if (child[i] != -1 && arr[child[i]] > maxChild) {
maxChildIndex = child[i];
maxChild = arr[child[i]];
}
}

if (maxChild == -1)
break;

if (arr[index] < arr[maxChildIndex])


swap(arr, index, maxChildIndex);

index = maxChildIndex;
}
}

public static void restoreUp(int[] arr, int index, int k) {


int parent = (index - 1) / k;
while (parent >= 0 && arr[index] > arr[parent]) { // Continue swapping until heap
property is satisfied
swap(arr, index, parent);
index = parent;
parent = (index - 1) / k;
}
}

public static void swap(int[] arr, int i, int j) {


int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

You might also like