diff --git a/GroupAnagrams.java b/GroupAnagrams.java new file mode 100644 index 00000000..99e67b34 --- /dev/null +++ b/GroupAnagrams.java @@ -0,0 +1,26 @@ +class Solution { + public List> groupAnagrams(String[] strs) { + // can also be solved using prime product technique + //TC - O(nk) + //SC - O(n) + if(strs.length == 0) + return new ArrayList<>(); + + Map> map = new HashMap<>(); + for(String str : strs) { + int[] freq = new int[26]; + for(char ch : str.toCharArray()) { + freq[ch - 'a']++; + } + String word = Arrays.toString(freq); + + + if(!map.containsKey(word)) + map.put(word, new ArrayList<>()); + map.get(word).add(str); + + } + return new ArrayList<>(map.values()); + } + +} \ No newline at end of file diff --git a/isIsomorphic.java b/isIsomorphic.java new file mode 100644 index 00000000..013243ff --- /dev/null +++ b/isIsomorphic.java @@ -0,0 +1,30 @@ +//TC is O(n) - n is length of string s +//SC is O(n) +class Solution { + public boolean isIsomorphic(String s, String t) { + if(s.length() != t.length()) + return false; + Map sMap = new HashMap<>(); + Map tMap = new HashMap<>(); + + for(int i = 0 ; i < s.length() ; i++) { + char sChar = s.charAt(i); + char tChar = t.charAt(i); + if(sMap.containsKey(sChar)) { + if(sMap.get(sChar) != tChar) + return false; + } + else + sMap.put(sChar, tChar); + + if(tMap.containsKey(tChar)) { + if(tMap.get(tChar) != sChar) + return false; + } + else + tMap.put(tChar, sChar); + + } + return true; + } +} \ No newline at end of file diff --git a/wordPattern.java b/wordPattern.java new file mode 100644 index 00000000..173647ad --- /dev/null +++ b/wordPattern.java @@ -0,0 +1,30 @@ +//TC is O(n) with n as the length of string pattern +//SC is O(n) with 2 hashmaps combined with n being the length of strings +class Solution { + public boolean wordPattern(String pattern, String s) { + Map map = new HashMap<>(); + Map sMap = new HashMap<>(); + String[] words = s.split("\\s+"); + if(pattern.length() != words.length) + return false; + for(int i = 0 ; i < pattern.length() ; i++) { + char ch = pattern.charAt(i); + String word = words[i]; + if(map.containsKey(ch)) { + if(!map.get(ch).equals(word)) { + System.out.println("map's word " +map.get(ch)); + return false; + } + } + else + map.put(ch, word); + if(sMap.containsKey(word)) { + if(!sMap.get(word).equals(ch)) + return false; + } + else + sMap.put(word, ch); + } + return true; + } +} \ No newline at end of file