Skip to content
Open

Trie #160

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
99 changes: 99 additions & 0 deletions JAVA/DataStructures/Trie/CompleteString.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/**
* Question link: https://www.codingninjas.com/codestudio/problems/complete-string_2687860
*/

public class CompleteString {

public static void main(String[] args) {
String[] words = {"n", "ni", "nin", "ninj", "ninja", "ninga"};
Solution solution = new Solution();
String ans = solution.completeString(6, words);
System.out.println(ans);
}

static class Solution {

private static class TrieNode{
private TrieNode[] children;
int count;
boolean isEndOfWord;

TrieNode() {
children = new TrieNode[26];
count = 0;
isEndOfWord = false;
}

boolean containsChild(char c) {
return children[c - 97] == null;
}

TrieNode getChild(char c) {
return children[c - 97];
}

void addChild(char c) {
children[c - 97] = new TrieNode();
}

void setIsEndOfWord() {
isEndOfWord = true;
}

boolean getIsEndOfWord() {
return isEndOfWord;
}
}
public static String completeString(int n, String[] a) {
// Write your code here.
TrieNode root = new TrieNode();

for (String s: a)
createTrie(root, s, 0);

String ans = "";

for(String s: a)
{
if (isCompleteString(root, s, 0))
{
if(s.length() > ans.length() || (ans.length() == s.length() && s.compareTo(ans) < 0))
ans = s;
}
}
//String empty;
if (ans == "") return "None";
return ans;
}

private static void createTrie(TrieNode root, String s, int x) {
if (x == s.length()) {
root.setIsEndOfWord();
return;
}

char child = s.charAt(x);

if (root.containsChild(child)) {
root.addChild(child);
}

createTrie(root.getChild(child), s, x + 1);
}

private static boolean isCompleteString(TrieNode root, String s, int x) {
if (x == s.length())
{
return true;
}

char c = s.charAt(x);

TrieNode child = root.getChild(c);
if(!child.getIsEndOfWord())
return false;

return isCompleteString(child, s, x + 1);
}
}
}
64 changes: 64 additions & 0 deletions JAVA/DataStructures/Trie/LongestCommonPrefix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* GFG link: https://practice.geeksforgeeks.org/problems/longest-common-prefix-in-an-array5129/1
* This question can be solved in many ways, but this is the Trie or Prefix-Tree implementation for it.
* assuming the strings contain only lowercase words(the TrieNode data member 'next' data structure can be modified based on the requirement)
*/

public class LongestCommonPrefix {

public static void main(String[] args) {
Solution solution = new Solution();
String[] words = {"geeks", "geeksforgeeks", "geekds", "geekfs"};

System.out.println(solution.lcs(words));
}

static class Solution {

public String lcs(String[] words) {
TrieNode root = new TrieNode();

for (String word: words)
createTrie(word, 0, root);

int len = search(words[0], 0, root, words.length);
return len > 0 ? words[0].substring(0, len) : "-1";
}

//Trie class
private class TrieNode {
TrieNode[] next;
int count; //how many strings is the current substring a prefix

TrieNode() {
next = new TrieNode[26];
count = 0;
}
}

private void createTrie(String s, int in, TrieNode parent) {
if(in == s.length()) {
return;
}

if(parent.next[s.charAt(in) - 'a'] == null)
parent.next[s.charAt(in) - 'a'] = new TrieNode();

parent.next[s.charAt(in) - 'a'].count++;

createTrie(s, in + 1, parent.next[s.charAt(in) - 'a']);
}

private int search(String s, int in, TrieNode parent, int totalWords) {
if(in == s.length()) {
return s.length();
}

if(parent.next[s.charAt(in) - 'a'].count != totalWords) {
return in;
}

return search(s, in + 1, parent.next[s.charAt(in) - 'a'], totalWords);
}
}
}
67 changes: 67 additions & 0 deletions JAVA/DataStructures/Trie/NumberOfDistinctSubstring.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* Question link: https://www.codingninjas.com/codestudio/problems/number-of-distinct-substring_1465938
*/

import java.util.*;

public class NumberOfDistinctSubstring {

public static void main(String[] args) {
String word = "abccbc";
Solution solution = new Solution();
int ans = solution.distinctSubstring(word);
System.out.println(ans);
}

static class Solution {

private static class TrieNode {
Map<Character, TrieNode> next;

TrieNode() {
next = new HashMap<>();
}

boolean contains(char c) {
return next.containsKey(c);
}
void add(char c) {
next.put(c, new TrieNode());
return;
}

TrieNode get(char c) {
return next.get(c);
}
}
public static int distinctSubstring(String st)
{
//your code here
TrieNode root = new TrieNode();
int length = 0;
for(int i = 0; i < st.length(); i++)
{
length+=createTrie(st, i, root);
}

return length;
}

private static int createTrie(String s, int x, TrieNode root)
{
if(x == s.length())
return 0;

char c = s.charAt(x++);

int count = 0;
if(!root.contains(c))
{
count = 1;
root.add(c);
}
TrieNode next = root.get(c);
return count + createTrie(s, x, next);
}
}
}
90 changes: 90 additions & 0 deletions JAVA/DataStructures/Trie/ShortestUniquePrefix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* Question link: https://practice.geeksforgeeks.org/problems/shortest-unique-prefix-for-every-word/1
*/

import java.util.*;

public class ShortestUniquePrefix {

public static void main(String[] args) {
String[] words = {"zebra", "dog", "duck", "dove"};

Solution solution = new Solution();
String[] prefixes = solution.findPrefixes(words, 4);

for(String s: prefixes)
System.out.println(s);
}

static class Solution {
static class TrieNode {
char val;
int count;
Map<Character, TrieNode> next;

TrieNode() {
count = 0;
next = new HashMap<Character, TrieNode>();
}

TrieNode(char c) {
count = 1;
val = c;
next = new HashMap<Character, TrieNode>();
}

void insert(char c) {
next.put(c, new TrieNode(c));
}

void incCount() {
count++;
}
}

static String[] findPrefixes(String[] arr, int N) {
// code here
TrieNode root = new TrieNode();

for(String s: arr) {
createTrie(root, s, 0);
}

String[] prefixes = new String[N];
int i = 0;
for(String s: arr) {
prefixes[i++] = getPrefix(root, s, 0, new StringBuilder(""));
}

return prefixes;
}

private static void createTrie(TrieNode root, String s, int x) {
if(x == s.length())
return;

char c = s.charAt(x);

if(!root.next.containsKey(c)) {
root.insert(c);
}
else {
root.next.get(c).incCount();
}

createTrie(root.next.get(c), s, x+1);
}

private static String getPrefix(TrieNode root, String s, int x, StringBuilder st) {
if(root.count == 1)
return st.toString();

char c = s.charAt(x);

st.append(c);

return getPrefix(root.next.get(c), s, x + 1, st);

}
}
}