diff --git a/grouping-anagrams.java b/grouping-anagrams.java new file mode 100644 index 00000000..80b6d234 --- /dev/null +++ b/grouping-anagrams.java @@ -0,0 +1,40 @@ +// Time Complexity: O(n × k) (n = number of words, k = average word length) +// Space Complexity: O(n) +// Explantion: We assign a unique prime number to each character from 'a' to 'z'. For every word, we multiply the prime values of its characters to generate a unique BigInteger key. Since anagrams produce the same prime product, we group words in a HashMap using this key. Finally, we return all grouped anagrams from the map. +import java.math.BigInteger; +class Solution { + public List> groupAnagrams(String[] strs) { + int m = strs.length; + if (m==0) return new ArrayList<>(); + if(m==1) { + return Arrays.asList(Arrays.asList(strs[0])); + } + Map> map = new HashMap<>(); + int[] primes = { + 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, + 31, 37, 41, 43, 47, 53, 59, 61, 67, + 71, 73, 79, 83, 89, 97, 101 + }; + for (int i=0; i append; + if(!map.containsKey(multi)) { + append = new ArrayList(); + } else { + append = map.get(multi); + } + append.add(curr); + map.put(multi, append); + } + + return new ArrayList<>(map.values()); + + + } +} \ No newline at end of file diff --git a/isomorphic-strings.java b/isomorphic-strings.java new file mode 100644 index 00000000..1e6e2d41 --- /dev/null +++ b/isomorphic-strings.java @@ -0,0 +1,30 @@ +// TimeComplexity: O(n) +// SpaceComplexity: O(1) +// Explnation : We first check if both strings have the same length. Then we use two HashMaps to maintain a one-to-one mapping between characters of s and t. While iterating, we verify that any existing mapping is consistent; otherwise, we return false. If all characters follow a valid bijection, we return true. +class Solution { + public boolean isIsomorphic(String s, String t) { + Map map1 = new HashMap<>(); + Map map2 = new HashMap<>(); + int m = s.length(); + int n = t.length(); + if(m!=n) return false; + for(int i=0; i map1 = new HashMap<>(); + Map map2 = new HashMap<>(); + int m = pattern.length(); + int n = words.length; + if(m!=n) return false; + for(int i=0; i