HashMaps and HashSets
1. Searching for Emails in an Unsorted Array
import java.util.*;
class Source {
public static int findDuplicateEmail(String[] emails,String key){
int n = emails.length;
for (int i = 0; i < n; i++) {
if (emails[i].equals(key))
return i;
return -1;
public static void main(String[] args)
String[] emails =
{"[email protected]","[email protected]","[email protected]","[email protected]
m","[email protected]","[email protected]","[email protected]","marie.george
@xyz.com"};
String NewEmail="[email protected]";
// Write your code here
System.out.println(findDuplicateEmail(emails,NewEmail));
}
2. Hash Table to Check Registered Email IDs
import java.util.*;
class Source {
public static void main(String[] args)
Hashtable<String,Integer> emails= new Hashtable<String,Integer>();
emails.put("[email protected]",1);
emails.put("[email protected]",2);
emails.put("[email protected]",3);
emails.put("[email protected]",4);
emails.put("[email protected]",5);
emails.put("[email protected]",6);
emails.put("[email protected]",7);
emails.put("[email protected]",8);
if(emails.containsKey(NewEmail))
//Complete here
System.out.println(emails.get("[email protected]"));
else {
System.out.println("False");
}
3. The Airline Boarding-Pass Problem
import java.util.*;
import java.util.Scanner;
class Source {
public static void main(String[] args)
Hashtable<Integer,String> boardingPass= new Hashtable<Integer,String>();
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int arr[]=new int[size];
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
for(int i:arr)
if(boardingPass.get(i) == "CHECKED") {
System.out.println(i);
break;
} else {
boardingPass.put(i, "CHECKED");
}
4. Anagram of key value pairs of a HashMap
import java.util.*;
public class Source{
//Method to check if two strings are anagram of each other or not
public static boolean check(String str1, String str2){
char[] ch1 = str1.toLowerCase().toCharArray();
char[] ch2 = str2.toLowerCase().toCharArray();
//Write your code here
if (ch1.length != ch2.length)
return false;
arrange(ch1); // sort first array
arrange(ch2); // sort second array
for (int i = 0; i < ch1.length; i++)
if (ch1[i] != ch2[i])
return false;
return true;
//Method to sort the character array
public static void arrange(char[] ch){
//Write your code here
for (int i = 0; i < ch.length; i++) {
for (int j = i + 1; j < ch.length; j++) {
int tmp;
if (ch[i] > ch[j]) {
tmp = ch[i];
ch[i] = ch[j];
ch[j] = (char) tmp;
}
}
public static void main(String[] x){
Map<String,String> map = new HashMap<>();
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
String key;
String value;
for(int i = 1; i <= num; i++){
key = sc.next();
value = sc.next();
map.put(key,value);
//Write your code here
Map<String, String> anagramsMap = new TreeMap<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
key = entry.getKey();
value = entry.getValue();
if (check(key, value))
anagramsMap.put(key, value);
if (anagramsMap.isEmpty())
System.out.println("false");
else
for (Map.Entry<String, String> entry : anagramsMap.entrySet())
System.out.printf("%n%s : %s", entry.getKey(), entry.getValue());
}
5. Find Symmetric Pairs
import java.util.Scanner;
import java.util.HashMap;
class Source {
public static void main(String arg[]) {
Scanner in = new Scanner(System.in);
//number of pairs in the array
int n = in.nextInt();
int arr[][] = new int[n][2];
// store the input pairs to an array "arr"
for (int i = 0; i < n; i++) {
arr[i][0] = in.nextInt();
arr[i][1] = in.nextInt();
// Write your code here
HashMap<Integer, Integer> MatchPair = new HashMap<Integer, Integer>();
int no_of_pairs=0;
// Travelling, given array
for (int i = 0; i < arr.length; i++)
// 1st & 2nd elements of pair when i=0 to arr.length
int firstElement = arr[i][0];
int secondElement = arr[i][1];
// Looking for 2nd element of this pair in hash
Integer value = MatchPair.get(secondElement);
// pair found when value = firstElement in hash
if (value != null && value == firstElement){
no_of_pairs++;
System.out.println(secondElement + " " + firstElement);
// Else put secondElement of this pair in hash
else
MatchPair.put(firstElement, secondElement);
// No Sysmmetric Pairs coditions:
if(arr.length==0 || arr.length==1 || no_of_pairs==0)
System.out.println("No Symmetric pair");
6. First Unique Character
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class Source {
public static void main(String arg[]) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
Character firstUniqueChar = null;
Map<Character, Integer> characterCount = new LinkedHashMap<Character, Integer>();
for (Character ch : str.toCharArray()) {
if (!characterCount.containsKey(ch)) {
characterCount.put(ch, 1);
} else {
characterCount.put(ch, characterCount.get(ch) + 1);
for (Character ch : characterCount.keySet()) {
if (characterCount.get(ch) == 1) {
firstUniqueChar = ch;
break;
if (firstUniqueChar == null) {
System.out.println("-1");
} else {
System.out.println(firstUniqueChar);
}
7. Sets in Java
Description
You are given an integer ‘n’, which represents the number of operations to be performed on a
HashSet.
Each operation has two integers a and b.
‘a’ represents the type of the operation and ‘b’ represents the data value which is an integer.
import java.util.*;
class Source {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
// creating a HashSet named "hashSet"
Set<Integer> hashSet = new HashSet<Integer>();
for (int i = 0; i < n; i++) {
int a = in.nextInt();
int b = in.nextInt();
// fill the switch cases below
switch (a) {
case 1:
// Write your code to add the input value b to the hashSet
hashSet.add(b);
break;
case 2:
// If hashSet contains b, then print true. Otherwise, print false
System.out.println(hashSet.contains(b));
break;
case 3:
// Write your code here to remove the element b from the hashSet
hashSet.remove(b);
break;
8. Check Array of Contiguous Integers
Description
You will be given the array of ‘n’ integers, and you have to print “true” if the distinct integers of
the given n integers can form a set of contiguous integers. Otherwise, print “false”.
Note: the given array of integers may contain duplicates.
import java.util.*;
class Source {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n, count = 0;
n = in.nextInt();
//array to store the input elements
int[] array = new int[n];
//storing the elements to the array
for (int i = 0; i < n; i++) {
array[i] = in.nextInt();
// If the array is empty then print false and return
if (n == 0) {
System.out.println("false");
return;
/* HashSet to store all the elements of the "array" */
HashSet<Integer> hashSet = new HashSet<Integer>();
/* Store all the elements of the "array" to the "hashSet" */
for (int i = 0; i < n; i++)
hashSet.add(array[i]);
// Initialise the current element as array[0]
int currentElement = array[0];
// while "currentElement" present in "hashSet" do the following
while (hashSet.contains(currentElement) == true) {
// increment count by one
count++;
// decrement the "currentElement" by one
currentElement--;
}
/*Now to check for the elements greater than the array[0]. So, modify the "currentElement" as
array[0] + 1 */
currentElement = array[0] + 1;
// while "currentElement" present in "hashSet" do the following
while (hashSet.contains(currentElement) == true) {
// increment the "count" by one
count++;
// increment the "currentElement" by one
currentElement++;
// Print true if the "count" is equal to the size of the "hashSet"
if (count == (hashSet.size())) {
System.out.println("true");
//Otherwise print false
else
System.out.println("false");
9. Pair With a Given Sum
import java.util.*;
class Source
{
public static void main (String[] args)
Scanner in = new Scanner(System.in);
// number of the elements
int n = in.nextInt();
int array[] = new int[n];
//storing the input integers to an array
for(int i =0;i<n;i++){
array[i] = in.nextInt();
// getting the target sum from input
int targetSum = in.nextInt();
//write your code here
HashSet<Integer> s = new HashSet<Integer>();
for (int i = 0; i < array.length; ++i) {
int temp = targetSum - array[i];
// checking for condition
if (s.contains(temp)) {
System.out.println("true");
System.exit(0);
s.add(array[i]);
System.out.println("false");
} }
10. Find Itinerary From all Tickets
Description
You will be given the source and destination of all the tickets in the form of a map, and you have
to print the itinerary from all those tickets.
Note:
1. The path covered by the tickets is not circular.
2. Other than the final destination, there is exactly one ticket from every city.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Source {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// get the no of tickets from input
int n = in.nextInt();
// map to store all the tickets
Map<String, String> tickets = new HashMap<String, String>();
// Store the source and destination of the tickets to the map "tickets"
for (int i = 0; i < n; i++) {
tickets.put(in.next(), in.next());
in.nextLine();
// To store reverse mapping
Map<String, String> reverseTickets = new HashMap<String, String>();
// iterate through each entry of the "tickets" map
for (Map.Entry<String, String> entryTickets : tickets.entrySet()) {
// store the reverse mapping to the "reverseTickets" map
reverseTickets.put(entryTickets.getValue(), entryTickets.getKey());
// initialise the start as null
String start = null;
// To get the start of the itinerary, do the following.
/* for every entry in the "tickets", get the key of
entry which is not present in the "reverseTickets" map*/
for (Map.Entry<String, String> entryTickets : tickets.entrySet()) {
if (!reverseTickets.containsKey(entryTickets.getKey())) {
start = entryTickets.getKey();
break;
// If you cannot get start of the itinerary, print "Invalid"
if (start == null) {
System.out.println("Invalid");
return;
/* By now you know what is the start of itinerary, so print the itinerary */
String from = start, to;
while (from != null) {
to = tickets.get(from);
System.out.print(from + " " );
from = to;
}
11. Match Locks and Keys
Description
Consider you are given the array of locks and keys. Write the program to print the key and its
corresponding lock in the order of the keys present in the array.
Note:
• You should not compare any lock with any other lock; similarly, you should not compare
any key with any other key.
• The size of the array of locks and keys is the same.
import java.util.HashMap;
import java.util.Scanner;
class Source {
public static void main(String arg[]) {
Scanner in = new Scanner(System.in);
// get the number of keys
int n = in.nextInt();
char keys[] = new char[n];
char locks[] = new char[n];
// store all the keys to the array "keys"
for (int i = 0; i < n; i++) {
keys[i] = in.next(".").charAt(0);
in.nextLine();
//store all the locks to the array "locks"
for (int i = 0; i < n; i++) {
locks[i] = in.next(".").charAt(0);
HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
// creating a hashMap for locks
for (int i = 0; i < n; i++)
hashMap.put(locks[i], i);
// searching for locks for each key in hashMap and arranging
// the locks in the order corresponding to the keys
for (int i = 0; i < n; i++)
if (hashMap.get(keys[i]) != null) {
locks[i] = keys[i];
} else {
System.out.println("Not possible");
return;
}
// print the locks and keys in the order corresponding to the keys.
for (int i = 0; i < n; i++) {
System.out.println(locks[i] + " " + keys[i]);
12. Distinct values in a HashMap
Description
You are given a HashMap with n number of keys and values. You need to print the distinct values
in the same order as in HashMap.
Example:
Map = {1=A,2=A,3=B}
Output: A B
import java.util.*;
public class Source{
//Method to print distinct values
public static void printValues(Map<Integer,String> map){
HashMap<String,Integer> h = new HashMap<>();
String value;
for(int i : map.keySet()){
value = map.get(i);
//Checks if value for a key exists in the map or not
if(h.get(value) == null){
h.put(value,i);
}
for(String s: h.keySet()){
System.out.print(s+" ");
public static void main(String[] x){
Map<Integer,String> map = new HashMap<>();
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int key;
String value;
for(int i = 1; i <= num; i++){
key = sc.nextInt();
value = sc.next();
map.put(key,value);
printValues(map);