diff --git a/18_Heaps,PriorityQueues/Connect_N_Ropes.java b/18_Heaps,PriorityQueues/Connect_N_Ropes.java new file mode 100644 index 0000000..f35bed1 --- /dev/null +++ b/18_Heaps,PriorityQueues/Connect_N_Ropes.java @@ -0,0 +1,30 @@ +import java.util.PriorityQueue; + +public class Connect_N_Ropes { + /* Given are N ropes of diffrent length,the task is to connect these ropes into one rope with + * minimum cost , such that the cost to connect two ropes is equal to the sum of their lengths. + * + * ropes = {4,3,2,6} + * answer - 29 + * connect 2 & 3 = 5 ---| + * connect 5 & 4 = 9 ---+= 29 = cost + * connect 9 & 6 = 15 --| + */ + public static void main(String args[]){ + int ropes[] = {2,3,3,4,6}; // answer - 41 + + PriorityQueue pq = new PriorityQueue<>(); + for (int i = 0; i < ropes.length; i++) { + pq.add(ropes[i]); + } + + int cost = 0; + while (pq.size() > 1) { + int min = pq.remove(); + int min2 = pq.remove(); + cost += min +min2; + pq.add(min+min2); + } + System.out.println("Cost of connecting n ropes = " + cost); + } +} diff --git a/18_Heaps,PriorityQueues/Heap.java b/18_Heaps,PriorityQueues/Heap.java new file mode 100644 index 0000000..8bce4eb --- /dev/null +++ b/18_Heaps,PriorityQueues/Heap.java @@ -0,0 +1,26 @@ +public class Heap { + /* + * 10 1 + * / \ / \ + * 4 5 2 4 + * / \ / \ + * 1 2 5 10 + * -MaxHeap -MinHeap + * + * Heap --- Visualize --> BinaryTree + * |______Implement --> Array/ArrayList + * + * BinaryTree + * -at most 2 children + * + * Complete Binary Tree + * CBT is a BT in which all the levels are completely filled except possibly the last one , + * which is filled from the left to right. + * + * Heap Order Property + * Children >= Parent (MinHeap) + * Children <= parent (MaxHeap) + * + * Heap is not implemented as class + */ +} diff --git a/18_Heaps,PriorityQueues/HeapSort.java b/18_Heaps,PriorityQueues/HeapSort.java new file mode 100644 index 0000000..da7c11e --- /dev/null +++ b/18_Heaps,PriorityQueues/HeapSort.java @@ -0,0 +1,46 @@ +public class HeapSort { + public static void heapify(int arr[],int i,int size){ + int left = 2*i+1; + int right = 2*i+2; + int maxIdx = i; + + if(left < size && arr[maxIdx] < arr[left]){ + maxIdx = left; + } + if(right < size && arr[maxIdx] < arr[right]){ + maxIdx = right; + } + if(maxIdx != i){ + // swap + int temp = arr[i]; + arr[i] = arr[maxIdx]; + arr[maxIdx] = temp; + + heapify(arr,maxIdx,size); + } + } + public static void heapSort(int arr[]){//O(n*logn) + //step 1 - build maxHeap + int n = arr.length; + for (int i = n/2; i >= 0; i--) { + heapify(arr,i,n); + } + + //step 2 - push largest at end + for (int i = n-1; i>0 ; i--) { + // swap (largest(first) with last) + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + heapify(arr, 0, i); + } + } + public static void main(String[] args) { + int arr[] = {1,7,4,5}; + heapSort(arr); + for (int i = 0; i < arr.length; i++) { + System.out.println(arr[i]); + } + } +} diff --git a/18_Heaps,PriorityQueues/MaxHeap.java b/18_Heaps,PriorityQueues/MaxHeap.java new file mode 100644 index 0000000..a467b34 --- /dev/null +++ b/18_Heaps,PriorityQueues/MaxHeap.java @@ -0,0 +1,95 @@ +import java.util.ArrayList; + +public class MaxHeap { + static class Heap{ + ArrayList arr = new ArrayList<>(); + + //Insert In Heap + public void add(int data){ + // add at last idx + arr.add(data); + + int x = arr.size()-1; // x is child index + int par = (x-1)/2; // parent index + + while (arr.get(x) > arr.get(par)) { //O(logn) + //swap + int temp = arr.get(x); + arr.set(x, arr.get(par)); + arr.set(par, temp); + + x = par; + par = (x-1)/2; + } + } + + public int peek(){ + return arr.get(0); + } + + // heapify to fix heap after element deletion + private void heapify(int i){ + int left = 2*i+1; + int right = 2*i+2; + int maxIdx = i; + + if(left < arr.size() && arr.get(maxIdx) < arr.get(left)){ + maxIdx = left; + } + if(right < arr.size() && arr.get(maxIdx) < arr.get(right)){ + maxIdx = right; + } + if(maxIdx != i){ + // swap + int temp = arr.get(i); + arr.set(i, arr.get(maxIdx)); + arr.set(maxIdx, temp); + + heapify(maxIdx); + } + } + //Delete in Heap + /* 1) 1st & last node swap + * 2) remove last idx (arr.remove (arr.size()-1)) + * 3) fix my Heap --> heapify() + */ + public int remove(){ + int data = arr.get(0); + + //step 1 - swap first & last + int temp = arr.get(0); + arr.set(0, arr.get(arr.size()-1)); + arr.set(arr.size()-1, temp); + + //step 2 - delete last + arr.remove(arr.size()-1); + + //step 3 - heapify + heapify(0); + return data; + } + public boolean isEmpty(){ + return arr.size() == 0; + } + // // To print our heap + // public void print(){ + // while(!arr.isEmpty()){ + // System.out.println(arr.get(0)/* Or use --> peek()*/); + // arr.remove(0); + // } + // } + // Get Min in Heap + + } + public static void main(String[] args) { + Heap pq = new Heap(); + pq.add(5); + pq.add(3); + pq.add(7); + + while (!pq.isEmpty()) { + System.out.println(pq.peek()); + pq.remove(); + } + } +} diff --git a/18_Heaps,PriorityQueues/NearbyCars.java b/18_Heaps,PriorityQueues/NearbyCars.java new file mode 100644 index 0000000..a76f395 --- /dev/null +++ b/18_Heaps,PriorityQueues/NearbyCars.java @@ -0,0 +1,39 @@ +import java.util.PriorityQueue; + +public class NearbyCars { + /* We are given N points in a 2D plane which are locations of N cars. if we are at the + * origin , print the nearest K cars. + * --> C0 (3,3) 3^2 + 3^2 = 18 + * --> C1 (5,-1) if k = 2 ans = C0 & C2 5^2 + (-1)^2 = 26 + * --> C2 (-2,4) -2^2 + 4^2 = 20 + */ + static class Point implements Comparable{ + int x,y,distSq,idx; // Actually here is no need of x & y. + public Point(int x,int y,int distSq,int idx){ + this.x = x; + this.y = y; + this.distSq = distSq; + this.idx = idx; + } + @Override + public int compareTo(Point p2){ + return this.distSq - p2.distSq; + } + } + + public static void main(String[] args) { + int pts[][] = {{3,3},{5,-1},{-2,4}}; + int k = 2; + + PriorityQueue pq = new PriorityQueue<>(); + for (int i = 0; i < pts.length; i++) { + int distSq = pts[i][0]*pts[i][0] + pts[i][1]*pts[i][1]; + pq.add(new Point(pts[i][0], pts[i][1], distSq, i)); + } + + //nearest k cars + for (int i = 0; i < k; i++) { + System.out.println("C" + pq.remove().idx); + } + } +} diff --git a/18_Heaps,PriorityQueues/OperationsInHeap.java b/18_Heaps,PriorityQueues/OperationsInHeap.java new file mode 100644 index 0000000..8a29b8e --- /dev/null +++ b/18_Heaps,PriorityQueues/OperationsInHeap.java @@ -0,0 +1,95 @@ +import java.util.ArrayList; + +public class OperationsInHeap { + static class Heap{ + ArrayList arr = new ArrayList<>(); + + //Insert In Heap + public void add(int data){ + // add at last idx + arr.add(data); + + int x = arr.size()-1; // x is child index + int par = (x-1)/2; // parent index + + while (arr.get(x) < arr.get(par)) { //O(logn) + //swap + int temp = arr.get(x); + arr.set(x, arr.get(par)); + arr.set(par, temp); + + x = par; + par = (x-1)/2; + } + } + + public int peek(){ + return arr.get(0); + } + + // heapify to fix heap after element deletion + private void heapify(int i){ + int left = 2*i+1; + int right = 2*i+2; + int minIdx = i; + + if(left < arr.size() && arr.get(minIdx) > arr.get(left)){ + minIdx = left; + } + if(right < arr.size() && arr.get(minIdx) > arr.get(right)){ + minIdx = right; + } + if(minIdx != i){ + // swap + int temp = arr.get(i); + arr.set(i, arr.get(minIdx)); + arr.set(minIdx, temp); + + heapify(minIdx); + } + } + //Delete in Heap + /* 1) 1st & last node swap + * 2) remove last idx (arr.remove (arr.size()-1)) + * 3) fix my Heap --> heapify() + */ + public int remove(){ + int data = arr.get(0); + + //step 1 - swap first & last + int temp = arr.get(0); + arr.set(0, arr.get(arr.size()-1)); + arr.set(arr.size()-1, temp); + + //step 2 - delete last + arr.remove(arr.size()-1); + + //step 3 - heapify + heapify(0); + return data; + } + public boolean isEmpty(){ + return arr.size() == 0; + } + // // To print our heap + // public void print(){ + // while(!arr.isEmpty()){ + // System.out.println(arr.get(0)/* Or use --> peek()*/); + // arr.remove(0); + // } + // } + // Get Min in Heap + + } + public static void main(String[] args) { + Heap pq = new Heap(); + pq.add(5); + pq.add(3); + pq.add(7); + + while (!pq.isEmpty()) { + System.out.println(pq.peek()); + pq.remove(); + } + } +} diff --git a/18_Heaps,PriorityQueues/PQ_For_Objects.java b/18_Heaps,PriorityQueues/PQ_For_Objects.java new file mode 100644 index 0000000..9d87dce --- /dev/null +++ b/18_Heaps,PriorityQueues/PQ_For_Objects.java @@ -0,0 +1,29 @@ +import java.util.PriorityQueue; +public class PQ_For_Objects { + static class Student implements Comparable{ + //Overriding + String name; + int rank; + + public Student(String name,int rank){ + this.name = name; + this.rank = rank; + } + @Override + public int compareTo(Student s2){ + return this.rank - s2.rank; // make it reverse to get decressing order + } + } + public static void main(String[] args) { + PriorityQueue pq = new PriorityQueue<>(); + pq.add(new Student("A",4)); + pq.add(new Student("B",5)); + pq.add(new Student("C",2)); + pq.add(new Student("D",12)); + + while(!pq.isEmpty()){ + System.out.println(pq.peek().name + " --> " + pq.peek().rank); + pq.remove(); + } + } +} diff --git a/18_Heaps,PriorityQueues/Pair.java b/18_Heaps,PriorityQueues/Pair.java new file mode 100644 index 0000000..b880fbb --- /dev/null +++ b/18_Heaps,PriorityQueues/Pair.java @@ -0,0 +1,4 @@ + +public class Pair { + +} diff --git a/18_Heaps,PriorityQueues/PriorityQueueJCF.java b/18_Heaps,PriorityQueues/PriorityQueueJCF.java new file mode 100644 index 0000000..f46f881 --- /dev/null +++ b/18_Heaps,PriorityQueues/PriorityQueueJCF.java @@ -0,0 +1,28 @@ +// import java.util.Comparator; +import java.util.PriorityQueue; + +public class PriorityQueueJCF{ + public static void main(String[] args) { + PriorityQueue pq = new PriorityQueue<>(); + // PriorityQueue pq = new PriorityQueue<>(Comparator.reverseOrder()); /* to get reverse priority */ + pq.add(3); + pq.add(7); + pq.add(4); + pq.add(1); + + /* TO understand how queue actually works */ + System.out.println(pq); + pq.remove(); + System.out.println(pq); + pq.remove(); + System.out.println(pq); + pq.remove(); + System.out.println(pq); + + while(!pq.isEmpty()){ + System.out.println(pq.peek()); + pq.remove(); + } + + } +} \ No newline at end of file diff --git a/18_Heaps,PriorityQueues/SlidingWindowMaximum.java b/18_Heaps,PriorityQueues/SlidingWindowMaximum.java new file mode 100644 index 0000000..9146447 --- /dev/null +++ b/18_Heaps,PriorityQueues/SlidingWindowMaximum.java @@ -0,0 +1,45 @@ +import java.util.PriorityQueue; + +public class SlidingWindowMaximum { + static class Pair implements Comparable{ + int val,idx; + public Pair(int val,int idx){ + this.val = val; + this.idx = idx; + } + @Override + public int compareTo(Pair p2){ + //ascending + //return this.val - p2.val; + //descending + return p2.val-this.val; + } + } + public static void main(String[] args) {//O(nlogk) + int arr[] = {1,3,-1,-3,5,3,6}; + int k = 3; // window size + int res[] = new int[arr.length-k+1]; + + PriorityQueue pq = new PriorityQueue<>(); + + //1st window + for (int i = 0; i < k; i++) { + pq.add(new Pair(arr[i],i)); + } + res[0] = pq.peek().val; + + for (int i = k; i < arr.length; i++) { + while (pq.size() > 0 && pq.peek().idx <= (i-k)) { + pq.remove(); + } + pq.add(new Pair(arr[i], i)); + res[i-k+1] = pq.peek().val; + } + + //print result + for (int i = 0; i < res.length; i++) { + System.out.print(res[i] + " "); + } + System.out.println(); + } +} diff --git a/18_Heaps,PriorityQueues/WeakestSoldier.java b/18_Heaps,PriorityQueues/WeakestSoldier.java new file mode 100644 index 0000000..07033da --- /dev/null +++ b/18_Heaps,PriorityQueues/WeakestSoldier.java @@ -0,0 +1,48 @@ +import java.util.PriorityQueue; + +public class WeakestSoldier { + /* We are given an M*N binary matrix of 1's (Soldiers) and 0's (Civilians). + * The Soldiers are positioned in front of the civilians. That is all the 1's + * will appear to the left of all the 0's in each row. + * + * A row i is weaker than a row j if one of the following is true + * - The number of Soldier in row i is less than the number of Soldier in j. + * - Both rows have the same numbers of Soldier and i < j. + * Find the K weakest rows. + */ + static class Row implements Comparable{ + int Soldiers; + int idx; + + public Row(int Soldiers,int idx){ + this.Soldiers = Soldiers; + this.idx = idx; + } + @Override + public int compareTo(Row r2){ + if(this.Soldiers == r2.Soldiers){ + return this.idx - r2.idx; + }else{ + return this.Soldiers - r2.Soldiers; + } + } + } + public static void main(String[] args) { + int army[][] = {{1,0,0,0}, + {1,1,1,1}, + {1,0,0,0}, + {1,0,0,0}}; + int k = 2; + PriorityQueue pq = new PriorityQueue<>(); + for (int i = 0; i < army.length; i++) { + int count = 0; + for (int j = 0; j < army[0].length; j++) { + count += army[i][j] == 1 ? 1:0; + } + pq.add(new Row(count, i)); + } + for (int i = 0; i < k; i++) { + System.out.println("R" + pq.remove().idx); + } + } +} diff --git a/19_Hashing/CountDistinctElements.java b/19_Hashing/CountDistinctElements.java new file mode 100644 index 0000000..bb3c751 --- /dev/null +++ b/19_Hashing/CountDistinctElements.java @@ -0,0 +1,22 @@ +import java.util.HashSet; + +public class CountDistinctElements { + /* + * Input : arr[] = {10, 20, 20, 10, 30, 10} + * Output : 3 + * Explanation: There are three distinct elements 10, 20, and 30. + * + * Input : arr[] = {10, 20, 20, 10, 20} + * Output : 2 + * + */ + public static void main(String[] args) { + int num[] = {4,3,2,5,6,7,3,4,2,1}; + HashSet set = new HashSet<>(); + + for (int i = 0; i < num.length; i++) { + set.add(num[i]); + } + System.out.println(set.size()); + } +} diff --git a/19_Hashing/Find_Iternerary_from_tickets.java b/19_Hashing/Find_Iternerary_from_tickets.java new file mode 100644 index 0000000..8d3a8b2 --- /dev/null +++ b/19_Hashing/Find_Iternerary_from_tickets.java @@ -0,0 +1,41 @@ +import java.util.HashMap; + +public class Find_Iternerary_from_tickets { + /* + * Input: + * "Chennai" -> "Banglore" + * "Bombay" -> "Delhi" + * "Goa" -> "Chennai" + * "Delhi" -> "Goa" + * + * Output: + * Bombay ->Delhi ->Goa ->Chennai->Banglore + * + */ + public static String getStart(HashMap tickets){ + HashMap revMap = new HashMap<>(); + for (String key : tickets.keySet()) { + revMap.put(tickets.get(key), key); + } + for(String key : tickets.keySet()){ + if (!revMap.containsKey(key)) { + return key; // starting point + } + } + return null; + } + public static void main(String[] args) { + HashMap tickets = new HashMap<>(); + tickets.put("Chennai", "Bengaluru"); + tickets.put("Mumbai", "Delhi"); + tickets.put("Goa", "Chennai"); + tickets.put("Delhi", "Goa"); + + String start = getStart(tickets); + System.out.print(start); + for (String key : tickets.keySet()) { + System.out.print("-> " + tickets.get(start)); + start = tickets.get(start); + } + } +} diff --git a/19_Hashing/HashMapCode.java b/19_Hashing/HashMapCode.java new file mode 100644 index 0000000..f304fdd --- /dev/null +++ b/19_Hashing/HashMapCode.java @@ -0,0 +1,44 @@ +import java.util.HashMap; +public class HashMapCode{ + /* #Hashing --Map --(1)HashMap,(2)LinkedHashMap,(3)TreeMap + * |______--Set --(1)HashSet,(2)LinkedSet,(3)TreeSet + * + * HasMap + * (Key,Value) + * | + * unique + * + * i.g. Menu + * Tea 10 + * Samosha 15 + * Pizza 250 + * Burger 50 + * + * HashMap Operations // import java.util.HashMap; + * + * put(key,Value);--------| + * get(Key); | + * containsKey(key); O(1) + * remove(key);-----------| + * + */ + public static void main(String[] args) { + HashMap hm = new HashMap<>(); + hm.put("India", 100); + hm.put("China", 150); + hm.put("US", 50); + + System.out.println(hm); + int population = hm.get("India"); //{China=150, US=50, India=100} + System.out.println(population); //100 + System.out.println(hm.containsKey("India")); // True + System.out.println(hm.containsKey("Indonasia")); //false + + System.out.println(hm.size()); // 3 + System.out.println(hm.isEmpty()); // false + hm.remove("China"); + System.out.println(hm); + hm.clear(); // to clear full HashMap + System.out.println(hm.isEmpty()); //True + } +} \ No newline at end of file diff --git a/19_Hashing/HashMap_ImplementationCode.java b/19_Hashing/HashMap_ImplementationCode.java new file mode 100644 index 0000000..445ddb8 --- /dev/null +++ b/19_Hashing/HashMap_ImplementationCode.java @@ -0,0 +1,147 @@ +import java.util.ArrayList; +import java.util.LinkedList; + +public class HashMap_ImplementationCode { + static class HashMap { // generic + private class Node { + K key; + V value; + + public Node (K key , V value){ + this.key = key; + this.value = value; + } + } + + private int n; // n -- number of nodes + private int N; // N -- buckets.length + private LinkedList buckets[]; // N = buckets.length + + @SuppressWarnings("unchecked") + public HashMap(){ + this.N = 4; + this.buckets = new LinkedList[4]; + for (int i = 0; i < 4; i++) { + this.buckets[i] = new LinkedList<>(); + } + } + + private int hashFunction(K key){ + int hc = key.hashCode(); + return Math.abs(hc) % N; + } + + private int SearchInLL(K key, int bi){ + LinkedList ll = buckets[bi]; + int di = 0; + for (int i = 0; i < ll.size(); i++) { + Node node = ll.get(i); + if(node.key == key) + return di; + di++; + } + return -1; + } + + @SuppressWarnings("unchecked") + private void rehash(){ + LinkedList oldBuck[] = buckets; + buckets = new LinkedList[N*2]; + N = 2*N; + for (int i = 0; i < buckets.length; i++) { + buckets[i] = new LinkedList<>(); + } + //nodes --> add in bucket + for (int i = 0; i < oldBuck.length; i++) { + LinkedList ll = oldBuck[i]; + for (int j = 0; j < ll.size(); j++) { + Node node = ll.remove(); + put(node.key, node.value); + } + } + } + public void put(K key,V value){ //O(lambda)--> O(1) + int bi = hashFunction(key); + int di = SearchInLL(key , bi); + + if (di != -1) { + Node node = buckets[bi].get(di); + node.value = value; + }else{ + buckets[bi].add(new Node(key, value)); + n++; + } + double lambda = (double)n/N; + if(lambda > 2.0){ + rehash(); + } + } + + public boolean containsKey(K key){ // O(1) + int bi = hashFunction(key); + int di = SearchInLL(key , bi); + + if (di != -1) { + return true; + }else{ + return false; + } + } + + public V remove(K key){ + int bi = hashFunction(key); + int di = SearchInLL(key , bi); + + if (di != -1) { + Node node = buckets[bi].remove(di); + n--; + return node.value; + }else{ + return null; + } + } + + public V get(K key){ //O(1) + int bi = hashFunction(key); + int di = SearchInLL(key , bi); + + if (di != -1) { + Node node = buckets[bi].get(di); + return node.value; + }else{ + return null; + } + } + + public ArrayList keySet(){ + ArrayList keys = new ArrayList<>(); + + for (int i = 0; i < buckets.length; i++) { + LinkedList ll = buckets[i]; + for(Node node : ll){ + keys.add(node.key); + } + } + return keys; + } + + public boolean isEmpty(){ + return n==0; + } + } + public static void main(String[] args) { + HashMap hm = new HashMap<>(); + hm.put("India", 100); + hm.put("China", 150); + hm.put("US", 50); + hm.put("Nepal", 5); + + ArrayList keys = hm.keySet(); + for(String key: keys){ + System.out.println(key); + } + System.out.println(hm.get("India")); + System.out.println(hm.remove("India")); + System.out.println(hm.get("India")); + } +} diff --git a/19_Hashing/Hash_Set.java b/19_Hashing/Hash_Set.java new file mode 100644 index 0000000..c338450 --- /dev/null +++ b/19_Hashing/Hash_Set.java @@ -0,0 +1,42 @@ +import java.util.HashSet; + +public class Hash_Set{ + /* 1)no duplicates + * 2)unordered + * 3)Null is allowed + * Set --> Collection of unque elements + * + * HashSet hs = new HashSet<>(); + * it's implementation is done by HashMap + * + * HashSet Operations + * add(key) //O(1) + * contains(Key) //O(1) + * remove(key) //O(1) + * it also has .clear() , .isEmpty() , .size() methods + */ + public static void main(String[] args) { + HashSet set = new HashSet<>(); + set.add(1); + set.add(1); + set.add(8); + set.add(5); + set.add(4); + set.add(11); + set.add(24); + + System.out.println(set); + System.out.println("removing 1 from the set via set.remove(1)");set.remove(1); + System.out.println(set); + + if (set.contains(2)) { + System.out.println("contains 2"); + } + else{ + System.out.println("not contains 2"); + } + System.out.println("Set is empty ? " + set.isEmpty()); + System.out.println("Clearing the set via set.clear()"); set.clear(); + System.out.println("Set is empty ? " + set.isEmpty()); + } +} \ No newline at end of file diff --git a/19_Hashing/IterationOnHashMap.java b/19_Hashing/IterationOnHashMap.java new file mode 100644 index 0000000..daf8150 --- /dev/null +++ b/19_Hashing/IterationOnHashMap.java @@ -0,0 +1,16 @@ +import java.util.HashMap; +import java.util.Set; +public class IterationOnHashMap { + public static void main(String[] args) { + HashMap hm = new HashMap<>(); + hm.put("India", 100); + hm.put("China", 150); + hm.put("US", 50); + Set Keys = hm.keySet(); + System.out.println(Keys); // [China, US, India] + + for(String k : Keys){ + System.out.println("key = " + k + " , Value = " + hm.get(k)); + } + } +} diff --git a/19_Hashing/IterationOnHashSet.java b/19_Hashing/IterationOnHashSet.java new file mode 100644 index 0000000..d90a853 --- /dev/null +++ b/19_Hashing/IterationOnHashSet.java @@ -0,0 +1,25 @@ +import java.util.HashSet; +import java.util.Iterator; + +public class IterationOnHashSet { + public static void main(String[] args) { + HashSet cities = new HashSet<>(); + cities.add("Delhi"); + cities.add("Mumbai"); + cities.add("Noida"); + cities.add("Bengaluru"); + + // (A) Using Iterator , Itorator is interface in java which returns iterator + System.out.println("(A) Using Iterator "); + Iterator it = cities.iterator(); + while(it.hasNext()){ + System.out.println(it.next()); + } + + System.out.println("(B) (Advance / Enhance for-each loop) "); + // (B) (Advance / Enhance for-each loop) + for (String city : cities) { + System.out.println(city); + } + } +} diff --git a/19_Hashing/LargestSubArrayWithSumZero.java b/19_Hashing/LargestSubArrayWithSumZero.java new file mode 100644 index 0000000..0df027b --- /dev/null +++ b/19_Hashing/LargestSubArrayWithSumZero.java @@ -0,0 +1,23 @@ +import java.util.*; + +public class LargestSubArrayWithSumZero { + public static void main(String[] args) { //O(n) + int arr[] = {15,-2,2,-8,1,7,10,23}; + + HashMap map = new HashMap<>(); + //(sum.idx) + + int sum = 0, len = 0; + + for (int j = 0; j < arr.length; j++) { + sum += arr[j]; + if (map.containsKey(sum)) { + len = Math.max(len, j-map.get(sum)); + }else{ + map.put(sum, j); + } + } + + System.out.print("largest subarray with sum as 0 => " + len ); + } +} diff --git a/19_Hashing/Linked_HashSet.java b/19_Hashing/Linked_HashSet.java new file mode 100644 index 0000000..f80db40 --- /dev/null +++ b/19_Hashing/Linked_HashSet.java @@ -0,0 +1,22 @@ +import java.util.LinkedHashSet; + +public class Linked_HashSet { + // Order of Insertion + // Ordered using DLL(Doubly Linked List) + // LinkedHashSet lhs = new LinkedHashSet<>(); + // Performance -- + // LHM < HashMap + // LHS < HashSet + // | | + // -O(1)- + // As we add values , as we get output. + public static void main(String[] args) { + LinkedHashSet lhs = new LinkedHashSet<>(); + lhs.add("Delhi"); + lhs.add("Mumbai"); + lhs.add("Noida"); + lhs.add("Bengaluru"); + + System.out.println(lhs); // [Delhi, Mumbai, Noida, Bengaluru] -- the way is same,as we inserted these elements. + } +} diff --git a/19_Hashing/Linked_Hash_Map.java b/19_Hashing/Linked_Hash_Map.java new file mode 100644 index 0000000..d48aa00 --- /dev/null +++ b/19_Hashing/Linked_Hash_Map.java @@ -0,0 +1,24 @@ +import java.util.LinkedHashMap; +import java.util.HashMap; +public class Linked_Hash_Map { + //keys are insertion ordered + public static void main(String[] args) { + + HashMap hm = new HashMap<>(); + hm.put("India", 100); + hm.put("China", 150); + hm.put("US", 50); + + System.out.println("HashMap = " + hm); // {China=150, US=50, India=100} + + LinkedHashMap lhm = new LinkedHashMap<>(); + lhm.put("India", 100); + lhm.put("China", 150); + lhm.put("US", 50); + + System.out.println("LinkedHashMap = " + lhm); // {India=100, China=150, US=50} + + //entrySet() method ---> to create a set out of the same elements contained in the hash map. + System.out.println("The set is" + lhm.entrySet()); // [India=100, China=150, US=50] + } +} diff --git a/19_Hashing/MajorityElement.java b/19_Hashing/MajorityElement.java new file mode 100644 index 0000000..7ecdd00 --- /dev/null +++ b/19_Hashing/MajorityElement.java @@ -0,0 +1,24 @@ +import java.util.HashMap; +import java.util.Set; + +public class MajorityElement { + //Given an integer array of size n, find all element that appear more than n/3 time. + public static void main(String[] args) { + int nums[] = {1,3,2,5,1,3,1,5,1}; + // Ans - 1 || n = 9 , 9/3 = 3 and only 1 is appearing more than 3 times. + HashMap map = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + if(map.containsKey(nums[i])){ + map.put(nums[i],map.get(nums[i])+1); + }else{ + map.put(nums[i], 1); + } + } + Set keySet = map.keySet(); + for (Integer key : keySet) { + if (map.get(key) > nums.length / 3) { + System.out.println(key); + } + } + } +} \ No newline at end of file diff --git a/19_Hashing/MajorityElementShortCode.java b/19_Hashing/MajorityElementShortCode.java new file mode 100644 index 0000000..020d4c0 --- /dev/null +++ b/19_Hashing/MajorityElementShortCode.java @@ -0,0 +1,23 @@ +import java.util.HashMap; +import java.util.Set; + +public class MajorityElementShortCode { + public static void main(String[] args) { + int nums[] = {1,3,2,5,1,3,1,5,1}; + // Ans - 1 || n = 9 , 9/3 = 3 and only 1 is appearing more than 3 times. + HashMap map = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + if(map.containsKey(nums[i])){ + map.put(nums[i],map.get(nums[i])+1); + }else{ + map.put(nums[i], 1); + } + } + Set keySet = map.keySet(); + for (Integer key : keySet) { + if (map.get(key) > nums.length / 3) { + System.out.println(key); + } + } + } +} diff --git a/19_Hashing/SubArraySumEqualToK.java b/19_Hashing/SubArraySumEqualToK.java new file mode 100644 index 0000000..cb74a32 --- /dev/null +++ b/19_Hashing/SubArraySumEqualToK.java @@ -0,0 +1,20 @@ +public class SubArraySumEqualToK { + /* + * Given an array of integers nums and an integer k, return the total number of + * subarrays whose sum equals to k. + * + * A subarray is a contiguous non-empty sequence of elements within an array. + * + * + * + * Example 1: + * + * Input: nums = [1,1,1], k = 2 + * Output: 2 + * Example 2: + * + * Input: nums = [1,2,3], k = 3 + * Output: 2 + */ + +} diff --git a/19_Hashing/Tree_Map.java b/19_Hashing/Tree_Map.java new file mode 100644 index 0000000..3fb9a0c --- /dev/null +++ b/19_Hashing/Tree_Map.java @@ -0,0 +1,22 @@ +import java.util.LinkedHashMap; +import java.util.TreeMap; + +public class Tree_Map { + // Keys are sorted + // put,get,romove are O(log n) + public static void main(String[] args) { + TreeMap tm = new TreeMap<>(); + tm.put("India", 100); + tm.put("China", 150); + tm.put("US", 50); + + System.out.println("TreeMap = " + tm); // TreeMap = {China=150, India=100, US=50} + + LinkedHashMap lhm = new LinkedHashMap<>(); + lhm.put("India", 100); + lhm.put("China", 150); + lhm.put("US", 50); + + System.out.println("LinkedHashMap = " + lhm); // {India=100, China=150, US=50} + } +} diff --git a/19_Hashing/Tree_Set.java b/19_Hashing/Tree_Set.java new file mode 100644 index 0000000..17ed23d --- /dev/null +++ b/19_Hashing/Tree_Set.java @@ -0,0 +1,24 @@ +import java.util.TreeSet; + +public class Tree_Set { + /* Sorted in ascending order + * Null values are not allowed (cause - TreeSet compares value to sort them,so it would be not + * possible to compare with null) + * + * TreeSet Functions -- O(log n) cause - sorting + * + * HashSet---------\ + * Null key + * LinkedHashSet---/ + * + */ + public static void main(String[] args) { + TreeSet ts = new TreeSet<>(); + ts.add("India"); + ts.add("China"); + ts.add("US"); + ts.add("Qatar"); + + System.out.println(ts); // [China, India, Qatar, US] - alphabatical order + } +} diff --git a/19_Hashing/Union_And_Intersection.java b/19_Hashing/Union_And_Intersection.java new file mode 100644 index 0000000..bfb50ea --- /dev/null +++ b/19_Hashing/Union_And_Intersection.java @@ -0,0 +1,32 @@ +import java.util.HashSet; + +public class Union_And_Intersection { + // return no. of elements in Union And Intersection of 2 arrays + public static void main(String[] args) { + int arr1[] = {7,3,9}; + int arr2[] = {6,3,9,2,9,4}; + HashSet set = new HashSet<>(); + //Union + for (int i = 0; i < arr1.length; i++) { + set.add(arr1[i]); + } + for (int i = 0; i < arr2.length; i++) { + set.add(arr2[i]); + } + System.out.println("union = " + set.size()); + + //Intersection + set.clear(); + for(int i=0; i map = new HashMap<>(); + for(int i=0; i