0% found this document useful (0 votes)
1 views

Implementing Hashing in Java

The document discusses various classes and methods in Java for implementing hashing, including HashTable, HashMap, LinkedHashMap, HashSet, LinkedHashSet, and TreeSet. It provides examples of how to use these classes to store key-value pairs, maintain order, and count distinct elements in arrays. Additionally, it explores methods for counting frequencies of array elements using loops and hash sets.

Uploaded by

hrishabhjoshi123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Implementing Hashing in Java

The document discusses various classes and methods in Java for implementing hashing, including HashTable, HashMap, LinkedHashMap, HashSet, LinkedHashSet, and TreeSet. It provides examples of how to use these classes to store key-value pairs, maintain order, and count distinct elements in arrays. Additionally, it explores methods for counting frequencies of array elements using loops and hash sets.

Uploaded by

hrishabhjoshi123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

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:

1. HashTable (A synchronized implementation of hashing): This class implements a hash table,


which maps keys to values. Any non-null object can be used as a key or as a value.
Java
// Java program to demonstrate working of HashTable
import java.util.*;

class GFG {
public static void main(String args[])
{

// Create a HashTable to store


// String values corresponding to integer keys
Hashtable<Integer, String>
hm = new Hashtable<Integer, String>();

// Input the values


hm.put(1, "Geeks");
hm.put(12, "forGeeks");
hm.put(15, "A computer");
hm.put(3, "Portal");

// Printing the Hashtable


System.out.println(hm);
}
}

Output:
{15=A computer, 3=Portal, 12=forGeeks, 1=Geeks}

2. HashMap (A non-synchronized faster implementation of hashing): HashMap is also similar


to HashTables in Java but it is faster in comparison as it is not synchronized. HashMap is used to
store key-value pairs or to map a given value to a given key. The general application of HashMap
is to count frequencies of elements present in an array or a list.
Java
// Java program to create HashMap from an array
// by taking the elements as Keys and
// the frequencies as the Values

import java.util.*;

class GFG {

// Function to create HashMap from array


static void createHashMap(int arr[])
{
// Creates an empty HashMap
HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>();

// Traverse through the given array


for (int i = 0; i < arr.length; i++) {
// Get if the element is present
Integer c = hmap.get(arr[i]);

// If this is first occurrence of element


// Insert the element
if (hmap.get(arr[i]) == null) {
hmap.put(arr[i], 1);
}

// If elements already exists in hash map


// Increment the count of element by 1
else {
hmap.put(arr[i], ++c);
}
}

// Print HashMap
System.out.println(hmap);
}

// Driver method to test above method


public static void main(String[] args)
{
int arr[] = { 10, 34, 5, 10, 3, 5, 10 };
createHashMap(arr);
}
}

Output:
{34=1, 3=1, 5=2, 10=3}

3. LinkedHashMap (Similar to HashMap, but keeps order of elements):


Java
// Java program to demonstrate working of LinkedHashMap
import java.util.*;

public class BasicLinkedHashMap


{
public static void main(String a[])
{
LinkedHashMap<String, String> lhm =
new LinkedHashMap<String, String>();
lhm.put("one", "practice.geeksforgeeks.org");
lhm.put("two", "code.geeksforgeeks.org");
lhm.put("four", "quiz.geeksforgeeks.org");

// It prints the elements in same order


// as they were inserted
System.out.println(lhm);

System.out.println("Getting value for key 'one': "


+ lhm.get("one"));
System.out.println("Size of the map: " + lhm.size());
System.out.println("Is map empty? " + lhm.isEmpty());
System.out.println("Contains key 'two'? "+
lhm.containsKey("two"));
System.out.println("Contains value 'practice.geeks"
+"forgeeks.org'? "+ lhm.containsValue("practice"+
".geeksforgeeks.org"));
System.out.println("delete element 'one': " +
lhm.remove("one"));
System.out.println(lhm);
}
}

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>();

// Adding elements into HashSet usind add()


h.add("India");
h.add("Australia");
h.add("South Africa");
h.add("India"); // adding duplicate elements

// Displaying the HashSet


System.out.println(h);

// Checking if India is present or not


System.out.println("\nHashSet contains India or not:"
+ h.contains("India"));

// Removing items from HashSet using remove()


h.remove("Australia");

// Printing the HashSet


System.out.println("\nList after removing Australia:" + h);

// Iterating over hash set items


System.out.println("\nIterating over list:");
Iterator<String> i = h.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}

Output:
[South Africa, Australia, India]

HashSet contains India or not:true

List after removing Australia:[South Africa, India]

Iterating over list:


South Africa
India

5. LinkedHashSet (Similar to LinkedHashMap, but maintains only keys, not pair):


Java
// Java program to demonstrate working of LinkedHashSet

import java.util.LinkedHashSet;
public class Demo
{
public static void main(String[] args)
{
LinkedHashSet<String> linkedset =
new LinkedHashSet<String>();

// Adding element to LinkedHashSet


linkedset.add("A");
linkedset.add("B");
linkedset.add("C");
linkedset.add("D");

// This will not add new element as A already exists


linkedset.add("A");
linkedset.add("E");

System.out.println("Size of LinkedHashSet = " +


linkedset.size());
System.out.println("Original LinkedHashSet:" + linkedset);
System.out.println("Removing D from LinkedHashSet: " +
linkedset.remove("D"));
System.out.println("Trying to Remove Z which is not "+
"present: " + linkedset.remove("Z"));
System.out.println("Checking if A is present=" +
linkedset.contains("A"));
System.out.println("Updated LinkedHashSet: " + linkedset);
}
}

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>();

// Elements are added using add() method


ts1.add("A");
ts1.add("B");
ts1.add("C");

// Duplicates will not get insert


ts1.add("C");

// Elements get stored in default natural


// Sorting Order(Ascending)
System.out.println("TreeSet: " + ts1);

// Checking if A is present or not


System.out.println("\nTreeSet contains A or not:"
+ ts1.contains("A"));

// Removing items from TreeSet using remove()


ts1.remove("A");

// Printing the TreeSet


System.out.println("\nTreeSet after removing A:" + ts1);

// Iterating over TreeSet items


System.out.println("\nIterating over TreeSet:");
Iterator<String> i = ts1.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}

Output:
TreeSet: [A, B, C]

TreeSet contains A or not:true

TreeSet after removing A:[B, C]

Iterating over TreeSet:


B
C

Mark as Read
Report An Issue
Count Distinct Elements

Given an unsorted array, count all distinct elements in it.


Examples:

Input : arr[] = {10, 20, 20, 10, 30, 10}


Output : 3
There are three distinct elements 10, 20 and 30.

Input : arr[] = {10, 20, 20, 10, 20}


Output : 2

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;

int countDistinct(int arr[], int n)


{
int res = 1;

// Pick all elements one by one


for (int i = 1; i < n; i++) {
int j = 0;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;

// If not printed earlier, then print it


if (i == j)
res++;
}
return res;
}

// Driver program to test above function


int main()
{
int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << countDistinct(arr, n);
return 0;
}
Output
5

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;

int countDistinct(int arr[], int n)


{
// First sort the array so that all
// occurrences become consecutive
sort(arr, arr + n);

// Traverse the sorted array


int res = 0;
for (int i = 0; i < n; i++) {

// Move the index ahead while


// there are duplicates
while (i < n - 1 && arr[i] == arr[i + 1])
i++;

res++;
}

return res;
}

// Driver program to test above function


int main()
{
int arr[] = { 6, 10, 5, 4, 9, 120, 4, 6, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << countDistinct(arr, n);
return 0;
}

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;

// This function prints all distinct elements


int countDistinct(int arr[], int n)
{
// Creates an empty hashset
unordered_set<int> s;

// Traverse the input array


int res = 0;
for (int i = 0; i < n; i++) {

// If not present, then put it in


// hashtable and increment result
if (s.find(arr[i]) == s.end()) {
s.insert(arr[i]);
res++;
}
}

return res;
}

// Driver program to test above function


int main()
{
int arr[] = { 6, 10, 5, 4, 9, 120, 4, 6, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << countDistinct(arr, n);
return 0;
}

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]

Distinct elements present = [1,2,3,16,8]

Total number of distinct elements in the array are 5

Algorithm :

1. Insert all the elements into the set S one by one.

2. Store the total size s of the set using set::size().

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:

Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20}


Output : 10 3
20 4
5 1

Input : arr[] = {10, 20, 20}


Output : 10 1
20 2

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;

void countFreq(int arr[], int n)


{
// Mark all array elements as not visited
vector<bool> visited(n, false);

// Traverse through array elements and


// count frequencies
for (int i = 0; i < n; i++) {

// Skip this element if already processed


if (visited[i] == true)
continue;

// 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

Time Complexity : O(n2)


Auxiliary Space : O(n)

An efficient solution is to use hashing.

C++Java
// CPP program to count frequencies of array items
#include <bits/stdc++.h>
using namespace std;

void countFreq(int arr[], int n)


{
unordered_map<int, int> mp;

// Traverse through array elements and


// count frequencies
for (int i = 0; i < n; i++)
mp[arr[i]]++;

// Traverse through map and print frequencies


for (auto x : mp)
cout << x.first << " " << x.second << 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
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;

void countFreq(int arr[], int n)


{
unordered_map<int, int> mp;

// Traverse through array elements and


// count frequencies
for (int i = 0; i < n; i++)
mp[arr[i]]++;

// To print elements according to first


// occurrence, traverse array one more time
// print frequencies of elements and mark
// frequencies as -1 so that same element
// is not printed multiple times.
for (int i = 0; i < n; i++) {
if (mp[arr[i]] != -1)
{
cout << arr[i] << " " << mp[arr[i]] << endl;
mp[arr[i]] = -1;
}
}
}

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

Time Complexity : O(n)


Auxiliary Space : O(n)

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;

void frequencyNumber(int arr[],int size)


{

// Creating a HashMap containing integer


// as a key and occurrences as a value
unordered_map<int,int>freqMap;

for (int i=0;i<size;i++) {


freqMap[arr[i]]++;
}

// Printing the freqMap


for (auto it : freqMap) {
cout<<it.first<<" "<<it.second<<endl;
}
}

int main()
{
int arr[] = {10, 20, 20, 10, 10, 20, 5, 20};
int size = sizeof(arr)/sizeof(arr[0]);
frequencyNumber(arr,size);
}

// This code is contributed by shinjanpatra.

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, -3, 1, 6}


Output: true
Explanation:
There is a subarray with zero sum from index 1 to 3.

Input: {4, 2, 0, 1, 6}
Output: true

Explanation :

The third element is zero. A single element is also a sub-array.

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 :

arr[] = {1, 4, -2, -2, 5, -4, 3}

If we consider all prefix sums, we can


notice that there is a subarray with 0
sum when :
1) Either a prefix sum repeats or
2) Or prefix sum becomes 0.

Prefix sums for above array are:


1, 5, 3, 1, 6, 2, 5

Since prefix sum 1 repeats, we have a subarray


with 0 sum.

Following is implementation of the above approach.


C++Java
// A C++ program to find if
// there is a zero sum subarray
#include <bits/stdc++.h>
using namespace std;

bool subArrayExists(int arr[], int n)


{
unordered_set<int> sumSet;

// Traverse through array


// and store prefix sums
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += arr[i];

// 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[] = {1, 9, 3, 10, 4, 20, 2}


Output: 4
Explanation:
The subsequence 1, 3, 4, 2 is the longest
subsequence of consecutive elements

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
{

static int findLongestConseqSubseq(int arr[],


int n)
{

// Sort the array


Arrays.sort(arr);

int ans = 0, count = 0;

ArrayList<Integer> v = new ArrayList<Integer>();


v.add(10);

// Insert repeated elements


// only once in the vector
for (int i = 1; i < n; i++)
{
if (arr[i] != arr[i - 1])
v.add(arr[i]);
}

// Find the maximum length


// by traversing the array
for (int i = 0; i < v.size(); i++)
{

// Check if the current element is


// equal to previous element +1
if (i > 0 &&v.get(i) == v.get(i - 1) + 1)
count++;
else
count = 1;

// Update the maximum


ans = Math.max(ans, count);
}
return ans;
}

// 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));
}
}

// This code is contributed by parascoding

Output
Length of the Longest contiguous subsequence is 3
Complexity Analysis:

• Time complexity: O(nLogn).


Time to sort the array is O(nlogn).
• Auxiliary space : O(1).
As no extra space is needed.
Efficient solution:
This problem can be solved in O(n) time using an Efficient Solution. The idea is to use Hashing. We
first insert all elements in a Set. Then check all the possible starts of consecutive subsequences.

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:

Below is the implementation of the above approach:

C++Java
// C++ program to find longest
// contiguous subsequence
#include <bits/stdc++.h>
using namespace std;

// Returns length of the longest


// contiguous subsequence
int findLongestConseqSubseq(int arr[], int n)
{
unordered_set<int> S;
int ans = 0;
// Hash all the array elements
for (int i = 0; i < n; i++)
S.insert(arr[i]);

// check each possible sequence from


// the start then update optimal length
for (int i = 0; i < n; i++)
{
// if current element is the starting
// element of a sequence
if (S.find(arr[i] - 1) == S.end())
{
// Then check for next elements
// in the sequence
int j = arr[i];
while (S.find(j) != S.end())
j++;

// update optimal length if


// this length is more
ans = max(ans, j - arr[i]);
}
}
return ans;
}

// 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:

•Time complexity: O(n).


Only one traversal is needed and the time complexity is O(n) under the assumption that hash
insert and search take O(1) time.
• Auxiliary space: O(n).
To store every element in hashmap O(n) space is needed
Another Solution:
This problem can be solved in O(N log N) time with another Method, this time the Idea is to use Priority
Queue.

Algorithm:

1. Create a Priority Queue to store the element


2. Store the first element in a variable
3. Remove it from the Priority Queue
4. Check the difference between this removed first element and the new peek element
5. If the difference is equal to 1 increase count by 1 and repeats step 2 and step 3
6. If the difference is greater than 1 set counter to 1 and repeat step 2 and step 3
7. if the difference is equal to 0 repeat step 2 and 3
8. if counter greater than the previous maximum then store counter to maximum
9. Continue step 4 to 7 until we reach the end of the Priority Queue
10. Return the maximum value

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]);
}

// Storing the first element


// of the Priority Queue
// This first element is also
// the smallest element
int prev = pq.poll();

// Taking a counter variable with value 1


int c = 1;

// Storing value of max as 1


// as there will always be
// one element
int max = 1;

for (int i = 1; i < N; i++)


{
// check if current peek
// element minus previous
// element is greater then
// 1 This is done because
// if it's greater than 1
// then the sequence
// doesn't start or is broken here
if (pq.peek() - prev > 1)
{
// Store the value of counter to 1
// As new sequence may begin
c = 1;

// Update the previous position with the


// current peek And remove it
prev = pq.poll();
}

// Check if the previous


// element and peek are same
else if (pq.peek() - prev == 0)
{
// Update the previous position with the
// current peek And remove it
prev = pq.poll();
}
// if the difference
// between previous element and peek is 1
else
{
// Update the counter
// These are consecutive elements
c++;

// Update the previous position


// with the current peek And remove it
prev = pq.poll();
}

// Check if current longest


// subsequence is the greatest
if (max < c)
{
// Store the current subsequence count as
// max
max = c;
}
}

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

You might also like