Implementing Hashing in Java
Implementing Hashing in Java
Java provides many built-in classes and interfaces to implement hashing easily. That is, without creating
any HashTable or hash function. Java mainly provides us with the following classes to implement
Hashing:
class GFG {
public static void main(String args[])
{
Output:
{15=A computer, 3=Portal, 12=forGeeks, 1=Geeks}
import java.util.*;
class GFG {
// Print HashMap
System.out.println(hmap);
}
Output:
{34=1, 3=1, 5=2, 10=3}
Output:
{one=practice.geeksforgeeks.org, two=code.geeksforgeeks.org,
four=quiz.geeksforgeeks.org}
Getting value for key 'one': practice.geeksforgeeks.org
Size of the map: 3
Is map empty? false
Contains key 'two'? true
Contains value 'practice.geeksforgeeks.org'? true
delete element 'one': practice.geeksforgeeks.org
{two=code.geeksforgeeks.org, four=quiz.geeksforgeeks.org}
4. HashSet (Similar to HashMap, but maintains only keys, not pair): The HashSet class
implements the Set interface, backed by a hash table which is actually a HashMap instance. The
class also offers constant time performance for the basic operations like add, remove, contains,
and size assuming that the hash function disperses the elements properly among the buckets.
HashSet is generally used to keep a check on whether an element is present in a list or not.
Java
// Java program to demonstrate working of HashSet
import java.util.*;
class Test {
public static void main(String[] args)
{
HashSet<String> h = new HashSet<String>();
Output:
[South Africa, Australia, India]
import java.util.LinkedHashSet;
public class Demo
{
public static void main(String[] args)
{
LinkedHashSet<String> linkedset =
new LinkedHashSet<String>();
Output:
Size of LinkedHashSet = 5
Original LinkedHashSet:[A, B, C, D, E]
Removing D from LinkedHashSet: true
Trying to Remove Z which is not present: false
Checking if A is present=true
Updated LinkedHashSet: [A, B, C, E]
6. TreeSet (Implements the SortedSet interface, Objects are stored in a sorted and ascending
order):
Java
// Java program to demonstrate working of TreeSet
import java.util.*;
class TreeSetDemo {
public static void main(String[] args)
{
TreeSet<String> ts1 = new TreeSet<String>();
Output:
TreeSet: [A, B, C]
Mark as Read
Report An Issue
Count Distinct Elements
A simple solution is to run two loops. For every element, check if it has appeared before. If yes,
increment count of distinct elements.
C++Java
// C++ program to count distinct elements
// in a given array
#include <iostream>
using namespace std;
Time Complexity of above solution is O(n2). We can Use Sorting to solve the problem in O(nLogn) time.
The idea is simple, first sort the array so that all occurrences of every element become consecutive.
Once the occurrences become consecutive, we can traverse the sorted array and count distinct elements
in O(n) time. Following is the implementation of the idea.
C++Java
// C++ program to count all distinct elements
// in a given array
#include <algorithm>
#include <iostream>
using namespace std;
res++;
}
return res;
}
Output
6
We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given array from
left to right and keep track of visited elements in a hash set , as a set consists of only unique elements.
Following is the implementation of the idea.
C++Java
/* CPP program to print all distinct elements
of a given array */
#include <bits/stdc++.h>
using namespace std;
return res;
}
Output
6
Set STL approach:
Sets are a type of associative containers in which each element has to be unique, because the value of
the element identifies it. The value of the element cannot be modified once it is added to the set, though
it is possible to remove and add the modified value of that element. We exploit the very basic property
of set STL that it stores only unique numbers.
Examples: Arr = [1,2,2,2,3,16,2,8,2,1,8]
Algorithm :
3.The total size s is the number of distinct elements present in the array.
C++Java
import java.util.*;
class GFG
{
// function that accepts the array and it's size and returns
// the number of distince elements
static int distinct(int[] arr, int len)
{
HashSet<Integer> S = new HashSet<>(); // declaring a set container using STL
for (int i = 0; i < len; i++) {
S.add(arr[i]); // inserting all elements of the
// array into set
}
int ans = S.size(); // calculating the size of the set
return ans;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45};
int l = arr.length; // calculating the size of the array
int dis_elements
= distinct(arr, l); // calling the function on array
System.out.print(dis_elements +"\n");
}
}
// This code is contributed by Rajput-Ji
Output
5
Mark as Read
Report An Issue
Frequencies of array elements
Given an array which may contain duplicates, print all elements and their frequencies.
Examples:
A simple solution is to run two loops. For every item count number of times, it occurs. To avoid
duplicate printing, keep track of processed items.
C++Java
// CPP program to count frequencies of array items
#include <bits/stdc++.h>
using namespace std;
// Count frequency
int count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
visited[j] = true;
count++;
}
}
cout << arr[i] << " " << count << endl;
}
}
int main()
{
int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
countFreq(arr, n);
return 0;
}
Output
10 3
20 4
5 1
C++Java
// CPP program to count frequencies of array items
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
countFreq(arr, n);
return 0;
}
Output
5 1
10 3
20 4
Time Complexity : O(n)
Auxiliary Space : O(n)
In above efficient solution, how to print elements in same order as they appear in input?
C++Java
// CPP program to count frequencies of array items
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
countFreq(arr, n);
return 0;
}
Output
10 3
20 4
5 1
This problem can be solved in Java using Hashmap. Below is the program.
C++Java
// C++ program to count frequencies of
// integers in array using Hashmap
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = {10, 20, 20, 10, 10, 20, 5, 20};
int size = sizeof(arr)/sizeof(arr[0]);
frequencyNumber(arr,size);
}
Output
5 1
10 3
20 4
Mark as Read
Report An Issue
Subarray with Zero Sum
Given an array of positive and negative numbers, find if there is a subarray (of size at-least one) with 0
sum.
Examples :
Input: {4, 2, 0, 1, 6}
Output: true
Explanation :
Input: {-3, 2, 3, 1, 6}
Output: false
A simple solution is to consider all subarrays one by one and check the sum of every subarray. We can
run two loops: the outer loop picks a starting point i and the inner loop tries all subarrays starting from
i (See this for implementation). The time complexity of this method is O(n2).
We can also use hashing. The idea is to iterate through the array and for every element arr[i], calculate
the sum of elements from 0 to i (this can simply be done as sum += arr[i]). If the current sum has been
seen before, then there is a zero-sum array. Hashing is used to store the sum values so that we can
quickly store sum and find out whether the current sum is seen before or not.
Example :
// If prefix sum is 0 or
// it is already present
if (sum == 0
|| sumSet.find(sum)
!= sumSet.end())
return true;
sumSet.insert(sum);
}
return false;
}
// Driver code
int main()
{
int arr[] = { -3, 2, 3, 1, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
if (subArrayExists(arr, n))
cout << "Found a subarray with 0 sum";
else
cout << "No Such Sub Array Exists!";
return 0;
}
Output
No Such Sub Array Exists!
Time Complexity of this solution can be considered as O(n) under the assumption that we have good
hashing function that allows insertion and retrieval operations in O(1) time.
Space Complexity: O(n) .Here we required extra space for unordered_set to insert array elements.
Mark as Read
Report An Issue
Longest Consecutive Subsequence
Given an array of integers, find the length of the longest sub-sequence such that elements in the
subsequence are consecutive integers, the consecutive numbers can be in any order.
Examples:
Input: arr[] = {36, 41, 56, 35, 44, 33, 34, 92, 43, 32, 42}
Output: 5
Explanation:
The subsequence 36, 35, 33, 34, 32 is the longest
subsequence of consecutive elements.
Naive Approach: The idea is to first sort the array and find the longest subarray with consecutive
elements.
After sorting the array and removing the multiple occurrences of elements, run a loop and keep a count
and max (both initially zero). Run a loop from start to end and if the current element is not equal to the
previous (element+1) then set the count to 1 else increase the count. Update max with a maximum of
count and max.
C++Java
// Java program to find longest
// contiguous subsequence
import java.io.*;
import java.util.*;
class GFG
{
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 9, 3, 10, 4, 20, 2 };
int n = arr.length;
System.out.println(
"Length of the Longest "
+ "contiguous subsequence is "
+ findLongestConseqSubseq(arr, n));
}
}
Output
Length of the Longest contiguous subsequence is 3
Complexity Analysis:
Algorithm:
1. Create an empty hash.
2. Insert all array elements to hash.
3. Do following for every element arr[i]
4. Check if this element is the starting point of a subsequence. To check this, simply look for arr[i]
- 1 in the hash, if not found, then this is the first element a subsequence.
5. If this element is the first element, then count the number of elements in the consecutive starting
with this element. Iterate from arr[i] + 1 till the last element that can be found.
6. If the count is more than the previous longest subsequence found, then update this.
Below image is a dry run of the above approach:
C++Java
// C++ program to find longest
// contiguous subsequence
#include <bits/stdc++.h>
using namespace std;
// Driver code
int main()
{
int arr[] = { 1, 9, 3, 10, 4, 20, 2 };
int n = sizeof arr / sizeof arr[0];
cout << "Length of the Longest contiguous subsequence "
"is "
<< findLongestConseqSubseq(arr, n);
return 0;
}
Output
Length of the Longest contiguous subsequence is 4
Complexity Analysis:
Algorithm:
C++Java
// Java Program to find longest consecutive
// subsequence This Program uses Priority Queue
import java.io.*;
import java.util.PriorityQueue;
public class Longset_Sub
{
// return the length of the longest
// subsequence of consecutive integers
static int findLongestConseqSubseq(int arr[], int N)
{
PriorityQueue<Integer> pq
= new PriorityQueue<Integer>();
for (int i = 0; i < N; i++)
{
// adding element from
// array to PriorityQueue
pq.add(arr[i]);
}
return max;
}
// Driver Code
public static void main(String args[])
throws IOException
{
int arr[] = { 1, 9, 3, 10, 4, 20, 2 };
int n = arr.length;
System.out.println(
"Length of the Longest consecutive subsequence is "
+ findLongestConseqSubseq(arr, n));
}
}
// This code is contributed by Sudipa Sarkar
Output
Length of the Longest consecutive subsequence is 4
Mark as Read
Report An Issue