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
19 changes: 19 additions & 0 deletions GroupAnagrams.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import java.util.*;

// O(n*m) time, O(n) space;
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
int[] freq = new int[26];
for (char c : str.toCharArray()) {
freq[c - 'a']++;
}
String key = Arrays.toString(freq);
map.putIfAbsent(key, new ArrayList<>());

map.get(key).add(str);
}
return new ArrayList<>(map.values());
}
}
22 changes: 22 additions & 0 deletions IsomorphicStrings.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import java.util.*;

// O(n) time, O(1) space since only 26 chars
class Solution {
public boolean isIsomorphic(String s, String t) {
Map<Character, Character> sMap = new HashMap<>();
Map<Character, Character> tMap = new HashMap<>();

for (int i = 0; i < s.length(); i++) {
char sChar = s.charAt(i);
char tChar = t.charAt(i);

sMap.putIfAbsent(sChar, tChar);
tMap.putIfAbsent(tChar, sChar);

if ((sMap.get(sChar) != tChar) || (tMap.get(tChar) != sChar)) {
return false;
}
}
return true;
}
}
27 changes: 27 additions & 0 deletions WordPattern.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import java.util.*;

// O(n) time, O(n) space

class Solution {
public boolean wordPattern(String pattern, String s) {
String[] parts = s.split(" ");

if (parts.length != pattern.length()) return false;

Map<Character, String> charMap = new HashMap<>();
Map<String, Character> wordMap = new HashMap<>();

for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String word = parts[i];

charMap.putIfAbsent(c, word);
wordMap.putIfAbsent(word, c);

if ((!charMap.get(c).equals(word)) || (!wordMap.get(word).equals(c))) {
return false;
}
}
return true;
}
}