Showing posts with label LC. Show all posts
Showing posts with label LC. Show all posts

Thursday, December 3, 2026

Leetcode - Alien Dictionary from Neetcode

 class Solution {

    HashMap<Character, Set<Character>> graph; // Can you use set?in case of List
    HashMap<Character, Integer> indegree;
   
    public String foreignDictionary(String[] words) {
        graph = new HashMap<>();
        indegree = new HashMap<>();

      for(String word:words) {
            for(char ch: word.toCharArray()) {
                graph.computeIfAbsent(ch, k-> new HashSet<>());
                indegree.computeIfAbsent(ch, k->0);
            }
      }

      for(int i= 0; i< words.length-1; i++) {
        if(!compare(words[i], words[i+1])) {
            return "";
        }
      }

      return bfs();
    }

    public String bfs() {
        Queue<Character> queue = new LinkedList<>();
        for( char key : indegree.keySet()) {
            if( indegree.get(key) == 0 ) {
                queue.offer(key);
            }
        }
        int count = 0;
        StringBuilder sb = new StringBuilder();
        while(!queue.isEmpty()) {
            char ch = queue.poll();
            sb.append(ch);

            for(var item : graph.get(ch)) {
              indegree.put(item, indegree.get(item)-1);  
              if(indegree.get(item) == 0) {
                queue.offer(item);
              }
            }
            count++;
        }
       
        return count==indegree.size()?  sb.toString() : "";
    }

    public Boolean compare(String firstWord, String secondWord)
    {
        //find first two characters which mismatch and add in graph
        int firstLen = firstWord.length();
        int secondLen = secondWord.length();
        int minLen = Math.min(firstLen, secondLen);
        int i = 0;
        while(i<minLen && firstWord.charAt(i)== secondWord.charAt(i)) {
            i++;
        }
        // if samecase matches till now but firstLen has characters left
        if(i==minLen) {
            return  firstLen <= secondLen; // zo , p  // z0 ,z
        }
        // now graph -- z->p , indegree-> p -> 1
       char source = firstWord.charAt(i);
        char target = secondWord.charAt(i);
        if(graph.get(source).add(target)) {
            // add returns boolean so false if present
        indegree.put(target, indegree.get(target)+1);
        }
        return true;
    }
}

Leetcode - Alien Dictionary from Neetcode

  class Solution {     HashMap < Character , Set < Character >> graph; // Can you use set?in case of List     HashMap < Cha...