0% found this document useful (0 votes)
54 views10 pages

Hashing

,

Uploaded by

Sagar Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views10 pages

Hashing

,

Uploaded by

Sagar Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

//Separate chaining in Hashing-->java

public static void separateChaining(int arr[], int n, ArrayList<ArrayList<Integer>>


hashTable, int hashSize)
{
//Your code here
for(int num: arr){
int hashValue = num%hashSize;
if(hashTable.get(hashValue)==null){
ArrayList <Integer> al = new ArrayList<Integer>();
al.add(num);
hashTable.add(al);
}
else{
ArrayList <Integer> al = hashTable.get(hashValue);
al.add(num);
}
}
}
===================================================================================
============
//Linear Probing in Hashing-->java
static void linearProbing(int hash_table[], int hash_size, int arr[], int
array_size)
{
//Your code here
for(int num : arr){
int hashValue = num%hash_size;
if(hash_table[hashValue]==-1)
hash_table[hashValue] = num;
else{
int i;
for(i = 1; i<hash_size; i++){
if(hash_table[(hashValue+i)%hash_size]==-1){
hash_table[(hashValue+i)%hash_size] = num;
break;
}
}
if(i==hash_size)
return;
}
}
}
===================================================================================
============
//Quadratic Probing in Hashing-->java
static void quadraticProbing(int hash_table[], int hash_size, int arr[], int
array_size)
{
//Your code here
for(int num:arr){
int hashValue = num%hash_size;
if(hash_table[hashValue]==-1)
hash_table[hashValue] = num;
else{
for(int i = 1; i<hash_size; i++){
if(hash_table[(hashValue+(i*i))%hash_size]==-1){
hash_table[(hashValue+(i*i))%hash_size]=num;
break;
}
}
}
}
}
===================================================================================
============
//Count Non-Repeated Elements-->java
class Hashing
{
// Function to count non-repeated elements in the array
// arr[]: input array
// n: size of array
static long countNonRepeated(int arr[], int n)
{
// add your code
long totalCount = n;
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
for(int num:arr){
if(hm.containsKey(num)){
hm.put(num, hm.get(num)+1);
totalCount = (hm.get(num)==2)?totalCount-2:totalCount-1;
}
else
hm.put(num, 1);
}
return totalCount;
}
}
===================================================================================
============
//Print Non-Repeated Elements-->java
class Hashing
{
static void printNonRepeated(int arr[], int n)
{
// add your code here
LinkedHashMap <Integer, Integer> hm = new LinkedHashMap<Integer,
Integer>();
for(int num:arr){
if(hm.containsKey(num))
hm.put(num, hm.get(num)+1);
else
hm.put(num,1);
}
StringBuilder sb = new StringBuilder();
for(Map.Entry <Integer, Integer> entry:hm.entrySet()){
if(entry.getValue()==1)
sb.append(""+entry.getKey()+" ");
}
System.out.print(sb);
}
}

===================================================================================
============
//First Repeating Element-->java
import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
public static void main (String[] args) {
Scanner sc= new Scanner(System.in);
int t = sc.nextInt();
while(t-->0)
{
int n = sc.nextInt();
int a[] = new int[n];

for(int i=0;i<n;i++)
a[i] = sc.nextInt();

HashMap<Integer,Integer> m = new HashMap<Integer,Integer>();


for(int i=0;i<n;i++)
{
if(m.containsKey(a[i]))
m.put(a[i],m.get(a[i])+1);
else
m.put(a[i],1);
}
ArrayList<Integer> b = new ArrayList<Integer>();
for(Map.Entry<Integer,Integer>e : m.entrySet())
{
int a1 = (int)e.getValue();
int c = (int)e.getKey();
if(a1>1)
b.add(c);
}
int index =Integer.MAX_VALUE;
if(b.size()==0)
System.out.println(-1);
else
{
for(int i=0;i<b.size();i++)
{
for(int j=0;j<n;j++)
{
if(a[j]==b.get(i))
index = Math.min(j,index);
}
}
System.out.println(index+1);

}
}
}
}
===================================================================================
============
//Intersection of two arrays-->cpp
#include<bits/stdc++.h>
using namespace std;

int main()
{
int nooftestcases;
cin>>nooftestcases;
while(nooftestcases--){
int m,n;
cin>>m>>n;
unordered_map<int,int> mm;
int ans=0;

for(int i=0;i<m;i++){
int temp;
cin>>temp;
if(mm.find(temp)!=mm.end()){
mm[temp]++;
}
else{
mm[temp] = 1;
}
}
for(int i=0;i<n;i++){
int temp;
cin>>temp;
if(mm.find(temp)!=mm.end()){
ans++;
mm.erase(temp);
}
}
cout<<ans<<endl;
}
}

===================================================================================
============
//Union of two arrays-->java
import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
public static void main (String[] args) {
Scanner in=new Scanner(System.in);
int t=in.nextInt();
while(t-->0){
int n=in.nextInt();
int m=in.nextInt();
HashSet<Integer> set=new HashSet<>();
for(int i=0;i<n;i++)
set.add(in.nextInt());
for(int i=0;i<m;i++)
set.add(in.nextInt());
System.out.println(set.size());
}
}
}
===================================================================================
============
//Hashing for pair - 1-->java
class Geeks
{
//Complete this function, Geeks
public static int sumExists(int arr[], int sizeOfArray, int sum)
{
//Your code here, Geeks
HashSet <Integer> hs = new HashSet<Integer>();
for(int num:arr){
if(hs.contains(sum-num))
return 1;
else
hs.add(num);
}
return 0;
}
}
===================================================================================
============
//Hashing for pair - 2-->java
class Geeks
{
//Complete this function
public static int sumExists(int arr[], int sizeOfArray, int sum)
{

//Your code here


HashSet <Integer> hs = new HashSet<Integer>();
for(int num:arr){
if(hs.contains(sum-num))
return 1;
else
hs.add(num);
}
return 0;
}

}
===================================================================================
============
//Check if two arrays are equal or not-->java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG{
public static void main (String[] args)throws IOException{
//code
BufferedReader buff = new BufferedReader(new
InputStreamReader(System.in));
String s = buff.readLine();
int t = Integer.parseInt(s);
while(t-->0){
s = buff.readLine();
int n = Integer.parseInt(s);
Map<Long,Integer> a = new HashMap<>();
Map<Long,Integer> b = new HashMap<>();
//int A[] = new int[n];
//int B[] = new int[n];
long temp;
String s1[] = buff.readLine().split(" ");
for(int i=0;i<n;i++){
temp = Long.parseLong(s1[i]);
if(!a.containsKey(temp)){
a.put(temp,1);
}
else if(a.containsKey(temp)){
a.put(temp,a.get(temp)+1);
}
}
String s2[] = buff.readLine().split(" ");
for(int i=0;i<n;i++){
temp = Long.parseLong(s2[i]);
if(!b.containsKey(temp)){
b.put(temp,1);
}
else if(b.containsKey(temp)){
b.put(temp,b.get(temp)+1);
}
}
boolean ans = true;
for(Map.Entry<Long,Integer> entry: a.entrySet()){
long k;
int v;
k = entry.getKey();
v = entry.getValue();
if(!b.containsKey(k)){
System.out.println(0);
ans = false;
break;
}
else if(b.containsKey(k)){
if(b.get(k)!=v){
System.out.println(0);
ans = false;
break;
}
}
}
if(ans)
System.out.println(1);
}
}
}
===================================================================================
============
//Numbers containing 1, 2 and 3-->python
#code
for _ in range(int(input())):
size = int(input())
arr = list(map(str, input().split()))
set_123 = ("1","2","3")
lst=[]
flag = False
for item in arr:
for char in item:
if char in set_123:
flag = True
else:
flag = False
break
if flag:
lst.append(item)
if len(lst)==0:
print(-1)
else:
for item in sorted(lst,key = len):
print(item,end=' ')
print(' ')

===================================================================================
============
//Subarray with 0 sum-->python
def subArrayExists(arr,n):
s = set()
sum = 0
for i in range(n):
sum += arr[i]
if sum == 0 or sum in s:
return True
s.add(sum)

return False
===================================================================================
============
//Winner of an election-->python
from collections import Counter
def winner(arr,n):
dic = Counter(arr)
maxo = max(dic.values())
for key,value in sorted(dic.items()):
if value==maxo:
print(key,end = ' ')
print(value,end = ' ')
break
===================================================================================
============
//Subarray range with given sum-->
===================================================================================
============
//Positive Negative Pair-->java
import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {

//code
public static void main (String[] args) {

StringBuilder sb = new StringBuilder();


Scanner in = new Scanner(System.in);
int T = in.nextInt();
while(T-->0){
int N = in.nextInt();
int[] arr = new int [N];
for(int i = 0; i<N; i++)
arr[i] = in.nextInt();
sb.append(PositiveNegativePair(arr, N)+"\n");
}
System.out.print(sb);
}
public static String PositiveNegativePair(int arr[], int N){
String str = "";
TreeSet <Integer> ts = new TreeSet<Integer>();
for(int num:arr){
if(num!=0)
ts.add(num);
}
for(Integer value: ts){
if(value>0)
return (str.isEmpty())?"0":str;
if(ts.contains(-value))
str =(-value)+" "+value+" "+str;
}
return "0";
}
}

===================================================================================
============
//Zero Sum Subarrays-->cpp
#include <bits/stdc++.h>
using namespace std;
int sub(int a[],int n){
int sum=0,count=0;
unordered_map<int,int>ump;
ump[0]++;
for(int i=0;i<n;i++){
sum+=a[i];
if(ump.find(sum)!=ump.end()){
count+=ump[sum];
}
ump[sum]++;
}
return count;
}
int main() {
int t;cin>>t;
while(t--){
int n;cin>>n;
int a[n];
for(int i=0;i<n;i++)cin>>a[i];
cout<<sub(a,n)<<"\n";
}
return 0;
}
===================================================================================
============
//Subarrays with equal 1s and 0s-->cpp
long long int countSubarrWithEqualZeroAndOne(int arr[], int n)
{
//Your code here
unordered_map<int, int> um;
int curr_sum = 0;
for (int i = 0; i < n; i++) {
curr_sum += (arr[i] == 0) ? -1 : arr[i];
um[curr_sum]++;
}

int count = 0;
for (auto itr = um.begin(); itr != um.end(); itr++) {
if (itr->second > 1)
count += ((itr->second * (itr->second - 1)) / 2);
}
if (um.find(0) != um.end())
count += um[0];
return count;
}
===================================================================================
============
//Relative Sorting-->java
import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n1=sc.nextInt();
int n2=sc.nextInt();
int a[]=new int[n1];
int b[]=new int[n2];
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<n1;i++){
a[i]=sc.nextInt();
if(map.containsKey(a[i]))
map.put(a[i],map.get(a[i])+1);
else
map.put(a[i],1);
}
for(int i=0;i<n2;i++)
b[i]=sc.nextInt();
int out[]=new int[n1];
int res=0;
for(int i=0;i<n2;i++)
{
if(map.containsKey(b[i]))
{
int count=map.get(b[i]);
for(int k=0;k<count;k++)
out[res+k]=b[i];

res+=count;
map.remove(b[i]);
}
}
ArrayList<Integer> al=new ArrayList<>(map.keySet());
Collections.sort(al);
for(int i : al)
{
int k=map.get(i);
for(int p=0;p<k;p++)
out[res++]=i;
}
for(int i=0;i<n1;i++)
System.out.print(out[i]+" ");
System.out.println();

}
}
===================================================================================
============
//Sorting Elements of an Array by Frequency-->python
def sortByFreq(a,n):
a.sort()
A = sorted(a,key = a.count,reverse = True)
for item in A:
print(item,end = " ")
print()

===================================================================================
============
//Longest consecutive subsequence-->cpp
int findLongestConseqSubseq(int arr[], int n)
{
vector<int> hash(100001,0);
for(int i=0;i<n;i++)
{
hash[arr[i]]=1;
}
int i=0;int max=1;
while(i<100001)
{
int cnt=0;
while(i<100001 && hash[i]!=0)
{
i++;cnt++;

}
if(cnt>max)
max=cnt;
while(i<100001 && hash[i]==0)
{
i++;
}

}
return max;
}

You might also like