• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Wednesday, February 1, 2023
  • Login
Zeroplusfour
No Result
View All Result
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
No Result
View All Result
Zeroplusfour
No Result
View All Result
Home Code Solutions Hackerrank Algorithms

No Prefix Set – HackerRank Solution

No Prefix Set - HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

bhautik bhalala by bhautik bhalala
May 25, 2022
Reading Time: 1 min read
0
15 Days to learn SQL Hard SQL(Advanced)-Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution alt text

Spread the love

Table of Contents

  • No Prefix Set – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
  • Solutions of Algorithms Data Structures Hard HackerRank:
    • Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
  • C++ No Prefix Set HackerRank Solution
  • Java No Prefix Set HackerRank Solution
  • Python 3 No Prefix Set HackerRank Solution
  • JavaScript No Prefix Set HackerRank Solution
  • C No Prefix Set HackerRank Solution
    • Leave a comment below
      • Related posts:

No Prefix Set – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

Solutions of Algorithms Data Structures Hard HackerRank:

Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts

C++ No Prefix Set HackerRank Solution


Copy Code Copied Use a different Browser

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <memory>
#include <unordered_map>

using namespace std;

class Trie
{
    public:
        bool insert(const string& s)
        {
            bool prefixFound = false;
            Node* node = &root;
            for (char c : s)
            {
                auto found = node->children.find(c);
                if (found == node->children.end())
                {
                    if (node->isWord) {
                        prefixFound = true;
                    }
                    Node* newNode = new Node();

                    node->children[c] = unique_ptr<Node>(newNode);
                    node = newNode;
                }
                else
                {
                    node = found->second.get();
                }
            }
            if (node->isWord) {
                prefixFound = true;
            }
            node->isWord = true;
            return prefixFound || node->children.size() > 0;
        }

    private:
        struct Node
        {
            bool isWord = false;
            unordered_map<char, unique_ptr<Node> > children;
        };

        Node root;
};



int main() {
    int n;
    cin >> n;
    
    Trie trie;
    string s;
    while (n--) {
        cin >> s;
        if (trie.insert(s)) {
            cout << "BAD SET" << endl;
            cout << s << endl;
            return 0;
        }
    }
    cout << "GOOD SET" << endl;
    return 0;
}

Java No Prefix Set HackerRank Solution


Copy Code Copied Use a different Browser

 

import java.io.*;
import java.util.*;

public class Trie {

    private static final int ALPHABET_SIZE = 26;

	class Node {
	    
	    Node[] edges;
	    char key;
	    int wordCount = 0;
	    int prefixCount = 0;
	    
	    Node(char key) {
	        this.key = key;
	        this.edges = new Node[ALPHABET_SIZE];
	    }
	    
	    boolean has(char key) {
	        return get(key) != null;
	    }
	    
	    Node get(char key) {
    	    return edges[getKey(key)];
	    }
	    
	    void put(char key, Node node) {
	        this.edges[getKey(key)] = node;
	    }
	    
	    char getKey(char ch) {
	        return (char) (ch - 'a');
	    }
	    
	}
		
	private Node root = new Node('\0');
	
	public boolean insert(String word) {
	    return insert(word, root);
	}
	
	private boolean insert(String word, Node root) {
    	root.prefixCount++;
        if (word.length() >= 0 && root.wordCount > 0) {
            return false;
        }
	    if (word.length() == 0) {
	        if (root.prefixCount > 1) {
	            return false;
	        }
	    	root.wordCount++;	    	
	    	return true;
	    }	    
	    char ch = word.charAt(0);
	    Node next = root.get(ch);	    
	    if (next == null) {
	        next = new Node(ch);	        
	        root.put(ch, next);
	    }	    
	    return insert(word.substring(1), next);	    
	}	
	
	public static void main(String[] args) throws IOException {		
	
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));		
		
		Trie trie = new Trie();        
        int n = Integer.parseInt(in.readLine());
        
        boolean bad = false;
        while (n-- > 0) {
            String word = in.readLine();  
            bad = !trie.insert(word);            
            if (bad) {
                out.println("BAD SET\n"+word);    
                break;
            }
        }
        

        if (!bad) {
            out.println("GOOD SET");
        }        
        out.close();
		
	}	
	
}



Python 3 No Prefix Set HackerRank Solution


Copy Code Copied Use a different Browser

root = {}
def add_to(root,s):
    current_node = root.setdefault(s[0],[0,{}])
    if len(s) == 1:
        current_node[0] += 1
    else:
        add_to(current_node[1],s[1:])
        
def is_prefix(root,s):
    if len(s) == 1:
        if len(root[s[0]][1])>0 or root[s[0]][0] > 1:
            return True
        else:
            return False
    else:
        if root[s[0]][0] > 0:
            return True
        else:
            return is_prefix(root[s[0]][1],s[1:])
    
    
    
n = int(input())
count = 0 
for _ in range(n):
    word = input().strip()
    add_to(root,word)
    if is_prefix(root,word):
        print("BAD SET")
        print(word)
        break
    count += 1
if count == n:
    print("GOOD SET")



JavaScript No Prefix Set HackerRank Solution


Copy Code Copied Use a different Browser

function TrieNode(letter){
    
    this.letter = letter;
    this.size = 0;
    this.complete = false;
    this.children = {};
    
}

TrieNode.prototype = {
    
    addChild: function(letter){
        
         //if(!this.hasChild(letter))
         this.children[letter] = new TrieNode(letter);
        
    },
    
    hasChild: function(letter){
        
        return !!this.children[letter];
        
    }
    
};

function Trie(){
    
    this.root = new TrieNode('');
    
}

Trie.prototype = {
    
    add: function(name){
        
        let letters = name.split('');
        let current = this.root;
        
        for(let i = 0; i < name.length; i++){
            
            let letter = name.charAt(i);
            /*
            if(!current.hasChild(letter) && current.complete){
                
                return {valid: false, error: name};
                
            } 
            
            current.addChild(letter);      
            current = current.children[letter];*/
            
            current.size++;
            
            if(!current.hasChild(letter)){
                
                if(current.complete) return {valid: false, error: name};
             
                current.addChild(letter);
                
            }
            
            current = current.children[letter];
            
        }
        
        current.complete = true;
        if(current.size > 0) return {valid: false, error: name};
        
        current.size++;
        
        return {valid: true, error: ''};
        
    }
    
};

function processData(input) {
    //Enter your code here
    let lines = input.split('\n');
    let n = lines[0];
    
    let trie = new Trie();
    
    for(let i = 0; i < n; i++){
        
        let entry = lines[1 + i];
        
        let status = trie.add(entry)
        if(!status.valid){
         
            console.log([
                
                'BAD SET',
                status.error
                
            ].join('\n'));
            
            return;
            
        }
        
    }
    
    console.log('GOOD SET');
    
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});



C No Prefix Set HackerRank Solution


Copy Code Copied Use a different Browser

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

typedef struct trieNode{
    struct trieNode **dic;
    int lw;
}tNode;

tNode *root;

int addStr(char *s){
    tNode *t;
    char c;
    t=root;
    while(*s){
        c = *s - 'a';
        s++;
        if(t->dic == NULL) t->dic=(tNode**)calloc(10,sizeof(tNode));
        if(t->dic[c] && t->dic[c]->lw) return 1;
        if((*s==0)&&(t->dic[c]!=NULL)) return 1;
        if(t->dic[c]==NULL) t->dic[c]=(tNode*)calloc(1,sizeof(tNode*));
        if(*s==0) t->dic[c]->lw=1;
        else t=t->dic[c];
    }
    return 0;
}

int main() {
    int n,m=0;
    char str[61];
    root=(tNode*)calloc(1,sizeof(tNode));
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%s",str);
        m=addStr(str);
        if(m) break;
    }
    if(m) printf("BAD SET\n%s\n",str);
    else printf("GOOD SET\n");
    return 0;
}

 

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionTwo Two – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAlmost Integer Rock Garden – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionPlus Minus – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCaesar Cipher – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionQueue using Two Stacks – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTree: Preorder Traversal – HackerRank Solution
Tags: Cc++14full solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptNo Prefix Setpypy 3Python 2python 3
ShareTweetPin
bhautik bhalala

bhautik bhalala

Related Posts

Leetcode All Problems Solutions
Code Solutions

Exclusive Time of Functions – LeetCode Solution

by admin
October 5, 2022
0
30

Exclusive Time of Functions - LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions...

Read more
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
32
Leetcode All Problems Solutions

Course Schedule III – LeetCode Solution

October 5, 2022
25
Leetcode All Problems Solutions

Maximum Product of Three Numbers – LeetCode Solution

September 11, 2022
52
Leetcode All Problems Solutions

Task Scheduler – LeetCode Solution

September 11, 2022
119
Leetcode All Problems Solutions

Valid Triangle Number – LeetCode Solution

September 11, 2022
28
Next Post
15 Days to learn SQL Hard SQL(Advanced)-Solution

Subset Component - HackerRank Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution

Dijkstra: Shortest Reach 2 - HackerRank Solution

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

15 Days to learn SQL Hard SQL(Advanced)-SolutionTwo Two – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAlmost Integer Rock Garden – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionPlus Minus – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCaesar Cipher – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionQueue using Two Stacks – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionTree: Preorder Traversal – HackerRank Solution

Categories

  • Algorithms
  • Anime
  • Biography
  • Business
  • Code Solutions
  • Cosmos
  • Countdowns
  • Culture
  • Economy
  • Education
  • Entertainment
  • Finance
  • Games
  • Hackerrank
  • Health
  • How to
  • Investment
  • LeetCode
  • Lifestyle
  • LINUX SHELL
  • Manga
  • News
  • Opinion
  • Politics
  • Sports
  • SQL
  • Tech
  • Travel
  • Uncategorized
  • Updates
  • World
  • DMCA
  • Home
  • My account
  • Privacy Policy
  • Top Posts

Recent Blogs

Leetcode All Problems Solutions

Exclusive Time of Functions – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
Code Solutions

Solutions of All SQL Problems HackerRank

May 29, 2022
7
Top 10 Best Yoga poses alt textevery girl needs to know
Health

5 Foods to avoid during pregnancy

May 13, 2022
4
Leetcode All Problems Solutions
Code Solutions

Peeking Iterator – LeetCode Solution

September 6, 2022
37
15 Days to learn SQL Hard SQL(Advanced)-Solution
Code Solutions

‘Awk’ – 1 – HackerRank Solution

August 25, 2022
2

© 2022 ZeroPlusFour - Latest News & Blog.

No Result
View All Result
  • Home
  • Category
    • Business
    • Culture
    • Economy
    • Lifestyle
    • Health
    • Travel
    • Opinion
    • Politics
    • Tech
  • Landing Page
  • Support Forum
  • Contact Us

© 2022 ZeroPlusFour - Latest News & Blog.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?