Skip to content
Open
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
23 changes: 23 additions & 0 deletions GroupingAnagrams.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import java.math.BigInteger;
// time complexity is O(N k log k )
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
// this is to check id we have already looked at a string with the same char
HashMap<String, List<String>> map = new HashMap<>();

for (String str : strs) {
char[] sortedArr = str.toCharArray();
// sorting will produce the same for each anagram
Arrays.sort(sortedArr);
String sortedStr = String.valueOf(sortedArr);

if (!map.containsKey(sortedStr)) {
map.put(sortedStr, new ArrayList<>());
}

map.get(sortedStr).add(str);
}

return new ArrayList<>(map.values());
}
}
19 changes: 19 additions & 0 deletions Isomorphic.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
public class Isomorphic {
public boolean isIsomorphic(String s, String t) {
// to check the reverse order we need to store the reverse
char[] isormofic = new char[95];
char[] reverseIsormofic = new char[95];
// O (N)
for (int i = 0; i < s.length(); i++) {
if (isormofic[s.charAt(i) - ' '] != 0) {
if (reverseIsormofic[t.charAt(i) - ' '] != s.charAt(i)) return false;
} else {
// if reverse dont match then return false
if (reverseIsormofic[t.charAt(i) - ' '] != 0) return false;
reverseIsormofic[t.charAt(i) - ' '] = s.charAt(i);
isormofic[s.charAt(i) - ' '] = t.charAt(i);
}
}
return true;
}
}
33 changes: 33 additions & 0 deletions WordPattern.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
public class WordPattern {
public boolean wordPattern(String pattern, String s) {
Map<Character, String> charToWord = new HashMap<>();
Map<String, Character> wordToChar = new HashMap<>();

char[] p = pattern.toCharArray();
String[] words = s.split(" ");
// check if the length is the same
if (p.length != words.length) {
return false;
}

for (int i = 0; i < p.length; i++) {
char c = p[i];
String word = words[i];

if (charToWord.containsKey(c)) {
if (!charToWord.get(c).equals(word)) {
return false;
}
} else {
if (wordToChar.containsKey(word)) {
return false;
}
// if the sord doesnt already exist add them to the map and reverse map
charToWord.put(c, word);
wordToChar.put(word, c);
}
}

return true;
}
}