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
26 changes: 26 additions & 0 deletions GroupAnagrams.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class Solution {
public List<List<String>> 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<String, List<String>> 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());
}

}
30 changes: 30 additions & 0 deletions isIsomorphic.java
Original file line number Diff line number Diff line change
@@ -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<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);
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;
}
}
30 changes: 30 additions & 0 deletions wordPattern.java
Original file line number Diff line number Diff line change
@@ -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<Character, String> map = new HashMap<>();
Map<String, Character> 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;
}
}