Skip to content

Commit 0284420

Browse files
committed
Add hashtable algorithms
1 parent 9fa4dec commit 0284420

File tree

22 files changed

+719
-69
lines changed

22 files changed

+719
-69
lines changed

README.md

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -188,21 +188,14 @@ List of Programs related to data structures and algorithms
188188
| 5 | Meeting rooms 2 | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/interval/5.meetingRooms2/meetingRooms2.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/interval/5.meetingRooms2/meetingRooms2.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/interval/5.meetingRooms2/meetingRooms2.md) | Medium | Two pointers |
189189

190190
### Hashtable
191-
192-
<!--| No. | Name | Source | Live | Documentation | Level | Pattern |
193-
194-
| 6 | Longest consecutive sequence | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/6.longestConsecutiveSequence/longestConsecutiveSequence.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/6.longestConsecutiveSequence/longestConsecutiveSequence.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/6.longestConsecutiveSequence/longestConsecutiveSequence.md) | | |
195-
-->
196-
197-
1. Duplicates: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/duplicates.js)
198-
199-
2. Two sum: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/twoSum/twoSum.js) [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/twoSum/twoSum.md)
200-
201-
3. First non repeating character: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/firstNonRepeatingCharacter.js)
202-
203-
4. Group anagram: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/groupAnagrams.js)
204-
205-
5. Verify Common Elements: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/verifyCommonElements.js)
191+
| No. | Name | Source | Live | Documentation | Level | Pattern |
192+
| :-: | :---------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :----: | :---------------------: |
193+
| 1 | Duplicates | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/1.duplicates/duplicates.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/1.duplicates/duplicates.js) | [JavaScript](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/1.duplicates/duplicates.md) | Easy | Using Map |
194+
| 2 | Two sum | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/2.twoSum/twoSum.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/2.twoSum/twoSum.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/2.twoSum/twoSum.md) | Easy | Using Map |
195+
| 3 | First non repeating character | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/3.firstNonRepeatingCharacter/firstNonRepeatingCharacter.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/3.firstNonRepeatingCharacter/firstNonRepeatingCharacter.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/3.firstNonRepeatingCharacter/firstNonRepeatingCharacter.md) | Easy | Using Map |
196+
| 4 | Group anagrams | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/4.groupAnagrams/groupAnagrams.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/4.groupAnagrams/groupAnagrams.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/4.groupAnagrams/groupAnagrams.md) | Medium | Using Map & its methods |
197+
| 5 | Verify Common Elements | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/5.verifyCommonElements/verifyCommonElements.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/5.verifyCommonElements/verifyCommonElements.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/5.verifyCommonElements/verifyCommonElements.md) | Easy | Using Map methods |
198+
| 6 | Longest consequtive sequence |[Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/6.longestConsecutiveSequence/longestConsecutiveSequence.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/6.longestConsecutiveSequence/longestConsecutiveSequence.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/hashtable/6.longestConsecutiveSequence/longestConsecutiveSequence.md) | Medium | Find sequence using set or hash table |
206199

207200
## Sorting
208201

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package java1.algorithms.hashmap.duplicates;
2+
3+
import java.util.ArrayList;
4+
import java.util.HashMap;
5+
import java.util.List;
6+
import java.util.Map;
7+
import java.util.Map.Entry;
8+
9+
public class Duplicates {
10+
11+
private static List<Integer> findDuplicates(int[] nums){
12+
Map<Integer, Integer> numsCount = new HashMap<>();
13+
List<Integer> duplicates = new ArrayList<>();
14+
15+
for (Integer num : nums) {
16+
numsCount.put(num, (numsCount.getOrDefault(num, 0)) +1);
17+
}
18+
19+
for (Entry<Integer, Integer> entry : numsCount.entrySet()) {
20+
if(entry.getValue() > 1) {
21+
duplicates.add(entry.getKey());
22+
}
23+
}
24+
25+
return duplicates;
26+
}
27+
28+
public static void main(String[] args) {
29+
/**---------------
30+
No Duplicates
31+
--------------- */
32+
System.out.println("Input: [6, 5, 4, 3, 2, 1]");
33+
System.out.println(findDuplicates(new int[]{6, 5, 4, 3, 2, 1}));
34+
System.out.println("---------------");
35+
36+
/**---------------
37+
Single Duplicate
38+
--------------- */
39+
System.out.println("Input: [6, 5, 5, 4, 3, 2, 1]");
40+
System.out.println(findDuplicates(new int[]{6, 5, 5, 4, 3, 2, 1}));
41+
System.out.println("---------------");
42+
43+
/**---------------
44+
Multiple Duplicates
45+
--------------- */
46+
System.out.println("Input: [5, 4, 4, 4, 3, 2, 1, 4, 2]");
47+
System.out.println(findDuplicates(new int[]{5, 4, 4, 4, 3, 2, 1, 4, 2}));
48+
System.out.println("---------------");
49+
}
50+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
**Problem statement:**
2+
Given an integer array `nums`, find all the duplicates in the array(i.e, numbers which appear more than once). Return an empty array if there are no duplicate numbers.
3+
4+
## Examples:
5+
Example 1:
6+
7+
Input: nums = [6, 5, 5 , 4, 3, 2, 1]
8+
Output: [5]
9+
10+
Example 2:
11+
12+
Input: nums = [5, 4, 4, 4, 3, 2, 1, 4, 2]
13+
Output: [4, 2]
14+
15+
Example 3:
16+
17+
Input: nums = [6, 5, 4, 3, 2, 1]
18+
Output: []
19+
20+
**Algorithmic Steps**
21+
This problem is solved with hashtable with elements as keys and number of occurrences as values. The algorithmic approach can be summarized as follows:
22+
23+
1. Create an empty map(`numsCount`) to store the elements and their respective counts.
24+
25+
2. Create an empty duplicates array(`duplicates`) to list the duplicated elements.
26+
27+
3. Iterate an input array using for-each loop and update the count of an element using `put` method of map.
28+
4. Iterate over a map which is filled with elements and their occurences. If an element appears more than once(i.e, the occurence of an element is more than 1), add it to the duplicate list.
29+
30+
5. Return `duplicates` as an output list with all duplicates of a given array.
31+
32+
33+
**Time and Space complexity:**
34+
This algorithm has a time complexity of `O(n)`, where n is the number of elements in an array. This is because populating the map by iterating through an array takes `O(n)` and finding duplicates from occurences map (incase of no duplicates) takes `O(n)` time complexity. Hence, the overall time complexity is `O(n)`.
35+
36+
Here, we use map datastructure which is used to store upto `n` unique elements and duplicates array can store upto `n/2` elements in the worst case(if each element has duplicate). Hence, the space complexity will be `O(n)`.
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package java1.algorithms.hashmap.firstNonRepeatingCharacter;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class FirstNonRepeatingCharacter {
7+
private static Character firstNonRepeatingChar(String str){
8+
if(str.length() == 0) return null;
9+
10+
Map<Character, Integer> charCountsMap = new HashMap<>();
11+
for(char ch: str.toCharArray()){
12+
charCountsMap.put(ch, charCountsMap.getOrDefault(ch, 0) +1 );
13+
}
14+
15+
for(Map.Entry<Character, Integer> entry: charCountsMap.entrySet()){
16+
if(entry.getValue() == 1) {
17+
return entry.getKey();
18+
}
19+
}
20+
21+
return null;
22+
}
23+
public static void main(String[] args) {
24+
/**---------------
25+
All Unique
26+
--------------- */
27+
System.out.println("Input: 'abcdefgh'");
28+
System.out.println("Output: "+ firstNonRepeatingChar("abcdefgh"));
29+
System.out.println("---------------");
30+
31+
/**---------------
32+
Some Duplicates
33+
--------------- */
34+
System.out.println("Input: 'abccddefgggh'");
35+
System.out.println("Output: "+ firstNonRepeatingChar("abccddefgggh"));
36+
System.out.println("---------------");
37+
38+
/** ---------------
39+
All Duplicates
40+
--------------- */
41+
System.out.println("Input: 'aabbccdddeeeff'");
42+
System.out.println("Output: "+ firstNonRepeatingChar("aabbccdddeeeff"));
43+
System.out.println("---------------");
44+
45+
/** ---------------
46+
Empty String
47+
--------------- */
48+
System.out.println("Input: ''");
49+
System.out.println("Output: "+ firstNonRepeatingChar(""));
50+
System.out.println("---------------");
51+
}
52+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
**Problem statement:**
2+
Given a string `str`, find the first non-repeating character in it and return its index position. If it does not exist, return -1.
3+
4+
## Examples:
5+
Example 1:
6+
7+
Input: str = "abcdefgh"
8+
Output: a
9+
10+
Example 2:
11+
12+
Input: str = "abccddefgggh"
13+
Output: a
14+
15+
Example 3:
16+
17+
Input: str = "aabbccdddeeeff"
18+
Output: null
19+
20+
Example 4:
21+
22+
Input: str = ""
23+
Output: null
24+
25+
**Algorithmic Steps**
26+
This problem is solved with hashtable with elements as keys and number of occurrences as values. The algorithmic approach can be summarized as follows:
27+
28+
**Approach 1**
29+
1. Add a base case check, returning `null` if the given string is empty.
30+
31+
2. Create an empty map(`charCountsMap`) to store the elements and their respective counts.
32+
33+
3. Iterate an input array using for-of loop and update the count of an element using `set` method of map.
34+
4. Iterate over a map which is filled with elements and their occurences. If an element appears only once(i.e, the occurence of an element is equals to 1), return its key as first unique character in the string.
35+
36+
5. Return `null` at the end of the function indicating that there are no unique characters.
37+
38+
**Approach 2**
39+
1. Add a base case check, returning `null` if the given string is empty.
40+
41+
2. Create an empty object(`charCountsObj`) to store the elements and their respective counts.
42+
43+
3. Create an empty duplicates array(`duplicates`) to list the duplicated elements.
44+
45+
3. Iterate an input array using for-of loop and update the count of an element in an object.
46+
47+
4. Iterate over an object which is filled with elements and their occurences. If an element appears more than once(i.e, the occurence of an element is equals to 1), return object's property as first unique character in the string.
48+
49+
5. Return `null` at the end of the function indicating that there are no unique characters.
50+
51+
52+
**Time and Space complexity:**
53+
This algorithm has a time complexity of `O(n)`, where n is the number of elements in an array. This is because populating the map by iterating through an array takes `O(n)` and finding unique character from occurences map(incase of no duplicates) takes `O(n)` time complexity. Hence, the overall time complexity is `O(n)`.
54+
55+
Here, we use map datastructure which is used to store upto `n` unique elements. Hence, the space complexity will be `O(n)`.
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package java1.algorithms.hashmap.groupAnagrams;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.HashMap;
6+
import java.util.List;
7+
import java.util.Map;
8+
9+
public class GroupAnagrams {
10+
private static List<List<String>> groupAnagrams1(String[] arr){
11+
Map<String, List<String>> anagramGroups = new HashMap<>();
12+
13+
for (String str : arr) {
14+
char[] strArr = str.toCharArray();
15+
Arrays.sort(strArr);
16+
String sortedString = new String(strArr);
17+
anagramGroups.putIfAbsent(sortedString, new ArrayList<>());
18+
anagramGroups.get(sortedString).add(str);
19+
}
20+
21+
return new ArrayList<>(anagramGroups.values());
22+
}
23+
24+
//Without sorting: TC(K * N) SC(K * N)
25+
private static List<List<String>> groupAnagrams2(String[] arr){
26+
Map<String, List<String>> anagramGroups = new HashMap<>();
27+
28+
for (String str : arr) {
29+
char[] strArr = str.toLowerCase().toCharArray();
30+
int[] charCount = new int[26];
31+
for(char ch: strArr){
32+
charCount[ch-'a']++;
33+
}
34+
String charCountkey = Arrays.toString(charCount);
35+
anagramGroups.putIfAbsent(charCountkey, new ArrayList<>());
36+
anagramGroups.get(charCountkey).add(str);
37+
}
38+
39+
return new ArrayList<>(anagramGroups.values());
40+
}
41+
42+
public static void main(String[] args) {
43+
// Multiple Anagrams
44+
System.out.println("Input: ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']");
45+
System.out.println("Output1: "+ groupAnagrams1(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}));
46+
System.out.println("Output2: "+ groupAnagrams2(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}));
47+
System.out.println("---------------");
48+
49+
// Mixed Case Anagrams
50+
System.out.println("Input: ['Eat', 'Tea', 'Tan', 'Ate', 'Nat', 'Bat']");
51+
System.out.println("Output1: "+ groupAnagrams1(new String[]{"Eat", "Tea", "Tan", "Ate", "Nat", "Bat"}));
52+
System.out.println("Output2: "+ groupAnagrams2(new String[]{"Eat", "Tea", "Tan", "Ate", "Nat", "Bat"}));
53+
System.out.println("---------------");
54+
55+
// No Anagrams
56+
System.out.println("Input: ['apple', 'orange', 'banana']");
57+
System.out.println("Output1: "+ groupAnagrams1(new String[]{"apple", "orange", "banana"}));
58+
System.out.println("Output2: "+ groupAnagrams2(new String[]{"apple", "orange", "banana"}));
59+
System.out.println("---------------");
60+
61+
}
62+
}

0 commit comments

Comments
 (0)