Skip to content

Back tracking #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Nov 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .githooks/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/bin/sh

# Run 'mvn clean install' and check if it succeeds
echo "Running 'mvn clean install'..."
if mvn clean install; then
echo "Build successful, proceeding with commit."
else
echo "Build failed. Aborting commit."
exit 1
fi
181 changes: 129 additions & 52 deletions .idea/workspace.xml

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.thealgorithm.graph;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
* @author: Subham Santra
*/
public class ConnectedComponentOnUndirectedGraph {
public static void main(String[] args) {
// TEST 1
{
GraphCreator graphCreator =
GraphCreator.getUndirected(7)
.addEdge(1, 2, 1)
.addEdge(2, 3, 1)
.addEdge(3, 4, 1)
.addEdge(5, 6, 1);

System.out.println(
countOfConnectedComponents(graphCreator.getAdjacencyList(), graphCreator.getVertices()));
}

// TEST 2
{
GraphCreator graphCreator =
GraphCreator.getUndirected(7);
System.out.println(
countOfConnectedComponents(graphCreator.getAdjacencyList(), graphCreator.getVertices()));
}

// TEST 3
{
GraphCreator graphCreator =
GraphCreator.getUndirected(3)
.addEdge(1, 2)
.addEdge(2, 0)
.addEdge(1, 0);
System.out.println(
countOfConnectedComponents(graphCreator.getAdjacencyList(), graphCreator.getVertices()));
}
}

public static int countOfConnectedComponents(
Map<Integer, Set<Integer>> adjacencyList, Set<Vertex<Integer, Integer>> vertexSet) {
int count = 0;
Set<Integer> visited = new HashSet<>();
for (Vertex<Integer, Integer> vertex : vertexSet) {
if (!visited.contains(vertex.getKey())) {
count++;
DFS(adjacencyList, vertex.getKey(), visited);
}
}
return count;
}

private static void DFS(
Map<Integer, Set<Integer>> adjacencyList, int vertex, Set<Integer> visited) {
if (visited.contains(vertex)) return;
visited.add(vertex);
for (int child : adjacencyList.get(vertex)) {
DFS(adjacencyList, child, visited);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package com.thealgorithm.graph;

import static java.util.AbstractMap.*;

import java.util.*;

public class DijkstraAlgorithm {
public static class InvalidWeightException extends Exception {
private String msg;

public InvalidWeightException(String msg) {
super(msg);
this.msg = msg;
}
}

void dijkstra(int[][] graph, int n, int source) throws InvalidWeightException {
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[source] = 0;

Set<Integer> shortestPathFound = new HashSet<>();
PriorityQueue<Entry<Integer, Integer>> priorityQueue =
new PriorityQueue<>(Comparator.comparingInt(Entry::getValue));

priorityQueue.offer(new SimpleEntry<>(source, 0));
shortestPathFound.add(source);

while (!priorityQueue.isEmpty()) {
Entry<Integer, Integer> shortedstEntry = priorityQueue.poll();
int node = shortedstEntry.getKey();
int cost = shortedstEntry.getValue();

for (int i = 0; i < n; ++i) {
if (graph[node][i] < 0) {
throw new InvalidWeightException("Invalid data");
}
if (node != i && graph[node][i] != 0) {
if (dist[i] > cost + graph[node][i]) {
dist[i] = cost + graph[node][i];
int finalI = i;
priorityQueue.removeIf(e -> e.getKey() == finalI);
priorityQueue.offer(new SimpleEntry<>(i, dist[i]));
}
}
}
shortestPathFound.add(node);
if (shortestPathFound.size() == n) break;
}

System.out.println(Arrays.toString(dist));
}

public static void main(String[] args) throws InvalidWeightException {

GraphCreator graphCreator =
GraphCreator.getUndirected(9)
.addEdge(0, 1, 4)
.addEdge(0, 7, 8)
.addEdge(1, 7, 11)
.addEdge(1, 2, 8)
.addEdge(2, 8, 2)
.addEdge(8, 6, 6)
.addEdge(8, 6, 6)
.addEdge(7, 6, 1)
.addEdge(7, 8, 7)
.addEdge(6, 5, 2)
.addEdge(2, 5, 4)
.addEdge(2, 3, 7)
.addEdge(5, 3, 14)
.addEdge(5, 4, 10)
.addEdge(3, 4, 9);

new DijkstraAlgorithm().dijkstra(graphCreator.getAdjacencyMatrix(), graphCreator.getSize(), 0);
new DijkstraAlgorithm().dijkstra(graphCreator.getAdjacencyMatrix(), graphCreator.getSize(), 8);
new DijkstraAlgorithm().dijkstra(graphCreator.getAdjacencyMatrix(), graphCreator.getSize(), 6);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.thealgorithm.graph;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import lombok.Value;

@Value
public class GraphCreator {
int size;
int[][] adjacencyMatrix;
Map<Integer, Set<Integer>> adjacencyList;
Set<Vertex<Integer, Integer>> vertices;
Set<Edge<Integer, Integer>> edgeSet;
boolean undirected;

private GraphCreator(int size, boolean undirected) {
this.size = size;
this.adjacencyMatrix = new int[size][size];
this.undirected = undirected;
this.adjacencyList = new HashMap<>();
this.vertices = new HashSet<>();
this.edgeSet = new HashSet<>();
for (int i = 0; i < size; ++i) {
vertices.add(Vertex.create(i));
}
for (int i = 0; i < size; ++i) {
adjacencyList.put(i, new HashSet<>());
}
}

public static GraphCreator getUndirected(int n) {
return new GraphCreator(n, true);
}

public static GraphCreator getDirected(int n) {
return new GraphCreator(n, false);
}

public GraphCreator addEdge(int u, int v) {
return addEdge(u, v, 1);
}

public GraphCreator addEdge(int u, int v, int w) {
addEdge0(u, v, w);
if (undirected) {
addEdge0(v, u, w);
}
return this;
}

private void addEdge0(int u, int v, int w) {
edgeSet.add(Edge.createEdge(u, v, w));
addToAdjacencyList(u, v);
adjacencyMatrix[u][v] = w;
}

private void addToAdjacencyList(int u, int v) {
adjacencyList.get(u).add(v);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.thealgorithm.heap;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author: Subham Santra
*/
public class TopKFrequentWords {
public List<String> topKFrequent(String[] words, int k) {
return Arrays.stream(words)
.collect(Collectors.toMap(Function.identity(), s -> 1, Integer::sum))
.entrySet()
.stream()
.sorted(
(kv1, kv2) -> {
int diff = kv1.getValue() - kv2.getValue();
if (diff == 0) {
return kv1.getKey().compareTo(kv2.getKey());
}
return -diff;
})
.limit(k)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}

public static void main(String[] args) throws IOException {
// System.out.println(
// new TopKFrequentWords()
// .topKFrequent(new String[] {"i", "love", "leetcode", "i", "love", "coding"}, 2));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.thealgorithm.linkedlist;

/**
* @author: Subham Santra
*/
public class DoublyLinkedList {
DoublyLinkedListNode head;
DoublyLinkedListNode tail;

public void addLast(int data) {
if (isEmpty()) {
head = tail = new DoublyLinkedListNode(data, null, null);
} else {
tail.next = new DoublyLinkedListNode(data, null, null);
}
}

private boolean isEmpty() {
return head == null && tail == null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.thealgorithm.linkedlist;

/**
* @author: Subham Santra
*/
public class DoublyLinkedListNode extends LinkedListNode {
DoublyLinkedListNode previous;

public DoublyLinkedListNode(int data, LinkedListNode next, DoublyLinkedListNode previous) {
super(data, next);
this.previous = previous;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.thealgorithm.linkedlist;

import lombok.AllArgsConstructor;

/**
* @author: Subham Santra
*/
@AllArgsConstructor
public class LinkedListNode {
int data;
LinkedListNode next;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package com.thealgorithm.strings;

/**
* @author: Subham Santra
*/
public class LongestChunkedPalindromeDecomposition {
static class Solution {
private final long p = 31;
private final long mod = (int) 1e9 + 7;
private final long[] p_pow = new long[1001];

public Solution() {
p_pow[0] = 1;
for (int i = 1; i <= 1000; ++i) {
p_pow[i] = p_pow[i - 1] * p;
p_pow[i] = (p_pow[i] + mod) % mod;
}
}

void rollingHash(long[] rh, String txt) {
for (int i = 0; i < txt.length(); ++i) {
int c = txt.charAt(i) - 'a' + 1;
rh[i + 1] = ((rh[i] * 31) % mod + c + mod) % mod;
}
}

long hash(long[] RH, int i, int j) {
return ((RH[j + 1] - RH[i] * p_pow[j - i + 1]) % mod + mod) % mod;
}

public int longestDecomposition(String text) {
int[][] DP = new int[text.length()][text.length()];
long[] RH = new long[text.length() + 1];
for (int i = 0; i < text.length(); ++i) {
for (int j = 0; j < text.length(); ++j) {
DP[i][j] = -1;
}
}
rollingHash(RH, text);
// System.out.println(Arrays.toString(RH));
return decompose(text, 0, text.length() - 1, DP, RH);
}

int decompose(String text, int lo, int hi, int[][] DP, long[] RH) {
if (lo == hi + 1) return 0;
if (lo > hi) return -1;

if (DP[lo][hi] != -1) return DP[lo][hi];

int ans = 1;

for (int len = 1; len <= (hi - lo + 1) / 2; ++len) {
long h1 = hash(RH, lo, lo + len - 1);
long h2 = hash(RH, hi - len + 1, hi);

// System.out.printf(
// "%s %d %s %d\n",
// text.substring(lo, lo + len), h1, text.substring(hi - len + 1, hi + 1), h2);

if (h1 == h2) {
int a = decompose(text, lo + len, hi - len, DP, RH);
if (a > -1) ans = Math.max(a + 2, ans);
}
}

return DP[lo][hi] = ans;
}
}

public static void main(String[] args) {
System.out.println(new Solution().longestDecomposition("ghiabcdefhelloadamhelloabcdefghi"));
System.out.println(
new Solution().longestDecomposition("wuamlwxskgjzegshjhcwchkgjzegshjwuamlwxs"));
System.out.println(new Solution().longestDecomposition("antaprezatepzapreanta"));
System.out.println(new Solution().longestDecomposition("aabaab"));
System.out.println(new Solution().longestDecomposition("aabaabaab"));
System.out.println(new Solution().longestDecomposition("aabaabaabaab"));
System.out.println(new Solution().longestDecomposition("aabaabaabaabc"));
}
}
Loading