From 4e38e1bf1b1190f3ed24c0f12d57a1e81ca809b4 Mon Sep 17 00:00:00 2001 From: Mitesh Birru <79537705+mitibirru@users.noreply.github.com> Date: Wed, 10 Jul 2024 22:55:15 +0530 Subject: [PATCH] until heap --- divide-conquer/Inversioncount.java | 67 +++++++++++++++++ divide-conquer/MaximumSubArray.java | 69 +++++++++++++++++ graph/Bipartite.java | 91 +++++++++++++++++++++++ graph/Dijkstras.java | 50 +++++++++++++ graph/IsCycleDirected.java | 67 +++++++++++++++++ graph/RottenOranges.java | 86 +++++++++++++++++++++ graph/TopologicalSort.java | 43 +++++++++++ heap/MergeKSortedArray.java | 0 heap/MinimumCostRopes.java | 40 ++++++++++ sliding-window/MaxConsecutiveOnesIII.java | 32 ++++++++ sliding-window/MaximumScore.java | 30 ++++++++ trees/binary-trees/MorrisTree.java | 36 +++++++++ trees/binary-trees/PreOrder.java | 3 + 13 files changed, 614 insertions(+) create mode 100644 divide-conquer/Inversioncount.java create mode 100644 divide-conquer/MaximumSubArray.java create mode 100644 graph/Bipartite.java create mode 100644 graph/Dijkstras.java create mode 100644 graph/IsCycleDirected.java create mode 100644 graph/RottenOranges.java create mode 100644 graph/TopologicalSort.java create mode 100644 heap/MergeKSortedArray.java create mode 100644 heap/MinimumCostRopes.java create mode 100644 sliding-window/MaxConsecutiveOnesIII.java create mode 100644 sliding-window/MaximumScore.java create mode 100644 trees/binary-trees/MorrisTree.java create mode 100644 trees/binary-trees/PreOrder.java diff --git a/divide-conquer/Inversioncount.java b/divide-conquer/Inversioncount.java new file mode 100644 index 0000000..8ec5799 --- /dev/null +++ b/divide-conquer/Inversioncount.java @@ -0,0 +1,67 @@ +import java.util.Scanner;; + +public class Inversioncount { + private static long count; + + // Function to count inversions in the array. + static long inversionCount(long arr[], int n) { + count = 0; // Reset count before starting + mergeSort(arr, 0, n - 1); + return count; + } + + // Helper function for merge sort. + private static void mergeSort(long[] arr, int lo, int hi) { + if (lo < hi) { + int mid = lo + (hi - lo) / 2; + mergeSort(arr, lo, mid); + mergeSort(arr, mid + 1, hi); + merge(arr, lo, mid, hi); + } + } + + // Function to merge two sorted halves and count inversions. + private static void merge(long[] arr, int lo, int mid, int hi) { + int n1 = mid - lo + 1; + int n2 = hi - mid; + + long[] left = new long[n1]; + long[] right = new long[n2]; + + System.arraycopy(arr, lo, left, 0, n1); + System.arraycopy(arr, mid + 1, right, 0, n2); + + int i = 0, j = 0, k = lo; + + while (i < n1 && j < n2) { + if (left[i] <= right[j]) { + arr[k++] = left[i++]; + } else { + arr[k++] = right[j++]; + count += (n1 - i); // Count inversions + } + } + + while (i < n1) { + arr[k++] = left[i++]; + } + + while (j < n2) { + arr[k++] = right[j++]; + } + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + long[] arr = new long[n]; + + for (int i = 0; i < n; i++) { + arr[i] = sc.nextLong(); + } + + inversionCount(arr, n); + System.out.println(count); + sc.close(); + } +} diff --git a/divide-conquer/MaximumSubArray.java b/divide-conquer/MaximumSubArray.java new file mode 100644 index 0000000..6a81502 --- /dev/null +++ b/divide-conquer/MaximumSubArray.java @@ -0,0 +1,69 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class MaximumSubArray { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + try { + System.out.print("Enter the number of elements: "); + int n = sc.nextInt(); + + if (n <= 0) { + System.out.println("The number of elements must be positive."); + return; + } + + int[] arr = new int[n]; + System.out.println("Enter the elements:"); + for (int i = 0; i < n; i++) { + arr[i] = sc.nextInt(); + } + + List result = findMaximumSubArray(arr); + if (result.isEmpty()) { + System.out.println("No positive subarray found."); + } else { + System.out.println("Maximum subarray:"); + for (int num : result) { + System.out.println(num); + } + } + } catch (Exception e) { + System.out.println("Invalid input. Please enter integers only."); + } finally { + sc.close(); + } + } + + static List findMaximumSubArray(int[] arr) { + List res = new ArrayList<>(); + int currentSum = 0, maxSum = Integer.MIN_VALUE; + int maxStart = -1, maxEnd = -1; + int currentStart = 0; + + for (int i = 0; i < arr.length; i++) { + if (arr[i] >= 0) { + currentSum += arr[i]; + if (currentSum > maxSum || (currentSum == maxSum && (i - currentStart > maxEnd - maxStart))) { + maxSum = currentSum; + maxStart = currentStart; + maxEnd = i; + } + } else { + currentSum = 0; + currentStart = i + 1; + } + } + + if (maxStart == -1 || maxEnd == -1) { + return res; // Return an empty list if no positive subarray is found + } + + for (int i = maxStart; i <= maxEnd; i++) { + res.add(arr[i]); + } + + return res; + } +} diff --git a/graph/Bipartite.java b/graph/Bipartite.java new file mode 100644 index 0000000..d20ce70 --- /dev/null +++ b/graph/Bipartite.java @@ -0,0 +1,91 @@ +package graph; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.Queue; + +public class Bipartite { + /** + * Function to check if graph is bipartite. + * + * @param v the number of vertices in the graph + * @param adj the adjacency list representing the graph + * @return true if the graph is bipartite, false otherwise + */ + + /** + * Helper function to perform BFS and check for bipartiteness. + * + * @param start the source vertex to start BFS + * @param color the array to store colors of vertices + * @param adj the adjacency list representing the graph + * @param n the number of vertices in the graph + * @return true if the component is bipartite, false otherwise + */ + private boolean check(int start, ArrayList> adj, int[] color, int n) { + Queue q = new LinkedList<>(); + q.add(start); + color[start] = 0; + + while (!q.isEmpty()) { + int curr = q.poll(); + + for (int nei : adj.get(curr)) { + // If the neighbor is not colored, color it with the opposite color + if (color[nei] == -1) { + color[nei] = 1 - color[curr]; + q.add(nei); + } + // If the neighbor has the same color as the current node, it's not bipartite + else if (color[nei] == color[curr]) + return false; + } + } + + return true; + } + + public boolean isBipartite(int v, ArrayList> adj) { + int color[] = new int[v]; + + Arrays.fill(color, -1); // Initialize all vertices as uncolored + + for (int i = 0; i < v; i++) { + if (color[i] == -1) { + // If the vertex is not colored, perform BFS + if (!check(i, adj, color, v)) + return false; + } + } + + return true; + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int T = Integer.parseInt(br.readLine().trim()); + while (T-- > 0) { + String[] input = br.readLine().trim().split(" "); + int V = Integer.parseInt(input[0]); + int E = Integer.parseInt(input[1]); + ArrayList> adj = new ArrayList<>(); + for (int i = 0; i < V; i++) { + adj.add(new ArrayList<>()); + } + for (int i = 0; i < E; i++) { + String[] edge = br.readLine().trim().split(" "); + int u = Integer.parseInt(edge[0]); + int v = Integer.parseInt(edge[1]); + adj.get(u).add(v); + adj.get(v).add(u); + } + Bipartite obj = new Bipartite(); + boolean ans = obj.isBipartite(V, adj); + System.out.println(ans ? "1" : "0"); + } + } +} \ No newline at end of file diff --git a/graph/Dijkstras.java b/graph/Dijkstras.java new file mode 100644 index 0000000..4d79cfc --- /dev/null +++ b/graph/Dijkstras.java @@ -0,0 +1,50 @@ +package graph; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.PriorityQueue; + +public class Dijkstras { + private int v; + private List> adj; + + Dijkstras(int v) { + this.v = v; + + adj = new ArrayList<>(); + for (int i = 0; i < v; i++) { + adj.add(new ArrayList<>()); + } + } + + public int[] shortestPath(int src) { + int[] dist = new int[v]; + Arrays.fill(dist, Integer.MAX_VALUE); + dist[src] = 0; + + PriorityQueue pq = new PriorityQueue<>(v, (a, b) -> a.dist - b.dist); //minheap + pq.add(new Pair(src, 0)); + + while(!pq.isEmpty()) { + int currNode = pq.poll().node; + + for (Pair p : adj.get(currNode)) { + if (dist[p.node] > dist[currNode] + p.dist) { + dist[p.node] = dist[currNode] + p.dist; + pq.add(new Pair(p.node, dist[currNode] + p.dist)); + } + } + } + return dist; + } +} + +class Pair { + int dist; + int node; + + Pair(int node, int dist) { + this.dist = dist; + this.node = node; + } +} \ No newline at end of file diff --git a/graph/IsCycleDirected.java b/graph/IsCycleDirected.java new file mode 100644 index 0000000..9ba5c4a --- /dev/null +++ b/graph/IsCycleDirected.java @@ -0,0 +1,67 @@ +package graph; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +public class IsCycleDirected { + public static void main(String[] args) { + IsCycleDirected solution = new IsCycleDirected(); + ArrayList> adj = new ArrayList<>(); + + // Example graph with 4 vertices + int V = 4; + for (int i = 0; i < V; i++) { + adj.add(new ArrayList<>()); + } + + // Adding edges to the graph + adj.get(0).add(1); + adj.get(1).add(2); + adj.get(2).add(3); + adj.get(3).add(1); // This creates a cycle + + boolean hasCycle = solution.isCyclic(V, adj); + System.out.println("Graph has cycle: " + hasCycle); + } + + // Function to detect cycle in a directed graph. + public boolean isCyclic(int V, ArrayList> adj) { + // Step 1: Calculate in-degree of each vertex + int[] indegree = new int[V]; + for (ArrayList list : adj) { + for (int nei : list) { + indegree[nei]++; + } + } + + // Step 2: Initialize a queue and enqueue all vertices with in-degree 0 + Queue queue = new LinkedList<>(); + for (int i = 0; i < V; i++) { + if (indegree[i] == 0) { + queue.offer(i); + } + } + + // Step 3: Initialize count of visited vertices + int count = 0; + + // Step 4: Process vertices in queue + while (!queue.isEmpty()) { + int node = queue.poll(); + count++; + + // Decrease in-degree for all adjacent vertices + for (int nei : adj.get(node)) { + indegree[nei]--; + // If in-degree becomes zero, add it to the queue + if (indegree[nei] == 0) { + queue.offer(nei); + } + } + } + + // Step 5: Check if topological sort included all vertices + return count != V; + } +} diff --git a/graph/RottenOranges.java b/graph/RottenOranges.java new file mode 100644 index 0000000..24c66a6 --- /dev/null +++ b/graph/RottenOranges.java @@ -0,0 +1,86 @@ +package graph; +import java.util.LinkedList; +import java.util.Queue; + +public class RottenOranges { + static class Pair { + int x, y; + + public Pair(int x, int y) { + this.x = x; + this.y = y; + } + } + + public int orangesRotting(int[][] grid) { + if (grid == null || grid.length == 0 || grid[0].length == 0) { + throw new IllegalArgumentException("Grid cannot be null or empty"); + } + + Queue q = new LinkedList<>(); + + int n = grid.length; + int m = grid[0].length; + boolean[][] vis = new boolean[n][m]; + + int freshOranges = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (grid[i][j] == 2) { + q.offer(new Pair(i, j)); + vis[i][j] = true; + } else if (grid[i][j] == 1) { + freshOranges++; + } + } + } + + if (q.size() == 0) + return 0; + + int minimumTime = 0; + int[] directionRow = { -1, 0, 1, 0 }; + int[] directionCol = { 0, 1, 0, -1 }; + int trackFreshOranges = 0; + + while (!q.isEmpty()) { + int size = q.size(); + minimumTime += 1; + + for (int i = 0; i < size; i++) { + Pair rottenOrange = q.poll(); + int r = rottenOrange.x; + int c = rottenOrange.y; + + for (int j = 0; j < 4; j++) { + int newRow = r + directionRow[j]; + int newCol = c + directionCol[j]; + + if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < m && !vis[newRow][newCol] + && grid[newRow][newCol] == 1) { + vis[newRow][newCol] = true; + trackFreshOranges++; + q.offer(new Pair(newRow, newCol)); + } + } + } + } + + if (trackFreshOranges != freshOranges) + return -1; + + return minimumTime; + } + + public static void main(String[] args) { + int[][] grid = { + { 2, 1, 1 }, + { 1, 1, 0 }, + { 0, 1, 1 } + }; + + RottenOranges solution = new RottenOranges(); + int minimumTime = solution.orangesRotting(grid); + System.out.println("Minimum time required to rot all oranges: " + minimumTime); + } +} diff --git a/graph/TopologicalSort.java b/graph/TopologicalSort.java new file mode 100644 index 0000000..33b6585 --- /dev/null +++ b/graph/TopologicalSort.java @@ -0,0 +1,43 @@ +package graph; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +public class TopologicalSort { + public List topoSort(List> adj, int v) { + int[] indegree = new int[v]; + for (List list : adj) { + for (int nei : list) { + indegree[nei]++; + } + } + + Queue q = new LinkedList<>(); + for (int i = 0; i < v; i++) { + if (indegree[i] == 0) + q.add(i); + } + + List result = new ArrayList<>(); + + while (!q.isEmpty()) { + int node = q.poll(); + result.add(node); + + for (int nei : adj.get(node)) { + indegree[nei]--; + if (indegree[nei] == 0) { + q.add(nei); + } + } + } + + if (result.size() != v) { + result.clear(); + return result; + } + + return result; + } +} diff --git a/heap/MergeKSortedArray.java b/heap/MergeKSortedArray.java new file mode 100644 index 0000000..e69de29 diff --git a/heap/MinimumCostRopes.java b/heap/MinimumCostRopes.java new file mode 100644 index 0000000..c30187e --- /dev/null +++ b/heap/MinimumCostRopes.java @@ -0,0 +1,40 @@ +package heap; + +import java.util.PriorityQueue; +import java.util.Scanner; + +public class MinimumCostRopes { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + int n = sc.nextInt(); + + long[] arr = new long[n]; + + for (int i = 0; i < n; i++) { + arr[i] = sc.nextLong(); + } + + System.out.println(minCost(arr, n)); + + sc.close(); + } + + static long minCost(long[] arr, int n) { + long cost = 0l; + + PriorityQueue pq = new PriorityQueue<>(); + + for (long num : arr) + pq.offer(num); + + while (pq.size() > 1) { + long num1 = pq.poll(); + long num2 = pq.poll(); + + cost += num1 + num2; + pq.offer(num1 + num2); + } + return cost; + } +} diff --git a/sliding-window/MaxConsecutiveOnesIII.java b/sliding-window/MaxConsecutiveOnesIII.java new file mode 100644 index 0000000..27b7850 --- /dev/null +++ b/sliding-window/MaxConsecutiveOnesIII.java @@ -0,0 +1,32 @@ +public class MaxConsecutiveOnesIII { + public int longestOnes(int[] nums, int k) { + int left = 0, right = 0, maxlen = 0, zeros = 0; + + while (right < nums.length) { + if (nums[right] == 0) + zeros++; + if (zeros > k) { + if (nums[left] == 0) + zeros--; + left++; + } + + if (zeros <= k) { + int len = right - left + 1; + maxlen = Math.max(maxlen, len); + } + + right++; + } + + return maxlen; + } + + public static void main(String[] args) { + MaxConsecutiveOnesIII solution = new MaxConsecutiveOnesIII(); + int[] arr = { 1, 1, 0, 0, 1, 1, 1, 0, 1, 1 }; + int k = 2; + System.out + .println("Longest sequence of ones with at most " + k + " zeros flip: " + solution.longestOnes(arr, k)); + } +} diff --git a/sliding-window/MaximumScore.java b/sliding-window/MaximumScore.java new file mode 100644 index 0000000..5e19dd7 --- /dev/null +++ b/sliding-window/MaximumScore.java @@ -0,0 +1,30 @@ +public class MaximumScore { + public int maxScore(int[] cardPoints, int k) { + int leftSum = 0, rightSum = 0, sum = 0; + + for (int i = 0; i < k; i++) { + leftSum += cardPoints[i]; + } + + sum = leftSum; + + int rightIndex = cardPoints.length - 1; + for (int i = k - 1; i >= 0; i--) { + leftSum -= cardPoints[i]; + rightSum += cardPoints[rightIndex]; + + sum = Math.max(sum, leftSum+rightSum); + rightIndex--; + } + + return sum; + } + + public static void main(String[] args) { + MaximumScore solution = new MaximumScore(); + int[] cardPoints = { 1, 2, 3, 4, 5, 6, 1 }; + int k = 3; + int maxScore = solution.maxScore(cardPoints, k); + System.out.println(maxScore); + } +} diff --git a/trees/binary-trees/MorrisTree.java b/trees/binary-trees/MorrisTree.java new file mode 100644 index 0000000..9ecf153 --- /dev/null +++ b/trees/binary-trees/MorrisTree.java @@ -0,0 +1,36 @@ +class Node { + int data; + Node left, right; + + Node(int data) { + this.data = data; + this.left = this.right = null; + } +} + +public class MorrisTree { + public void morrisTraversal(Node root) { + Node node = root; + + while (node != null) { + if (node.left == null) { + System.out.print(node.data + " "); + node = node.right; + } else { + Node current = node.left; + while (current.right != null && current.right != node) { + current = current.right; + } + + if (current.right == node) { + current.right = null; + node = node.right; + } else { + System.out.print(node.data + " "); + current.right = node; + node = node.left; + } + } + } + } +} diff --git a/trees/binary-trees/PreOrder.java b/trees/binary-trees/PreOrder.java new file mode 100644 index 0000000..bc5562d --- /dev/null +++ b/trees/binary-trees/PreOrder.java @@ -0,0 +1,3 @@ +public class PreOrder { + +}