├── .github └── FUNDING.yml ├── .gitignore ├── README.md ├── pom.xml └── src └── main ├── java └── com │ └── interview │ └── brushups │ ├── algorithm │ ├── searching │ │ ├── BinarySearch.java │ │ └── LinearSearch.java │ └── sorting │ │ ├── MergerSort.java │ │ ├── QuickSort.java │ │ └── SelectionSort.java │ ├── askedprograms │ ├── BalancedParenthesis.java │ ├── CountCharacter.java │ ├── FindDifferenceEqualsTarget.java │ ├── FindFragmentsEqualsZero.java │ ├── FindMinPossibleNumberForSum.java │ ├── FindNonRepetitiveSum.java │ ├── FindNxtGreatest.java │ ├── FindPairsInArraySum.java │ ├── FindPanagram.java │ ├── FindRepeatedNumbers.java │ ├── FindSecondLargest.java │ ├── FindSquareOfNumbersInAscending.java │ ├── FindXtoXPlusOne.java │ ├── GCFOfNumberList.java │ ├── HighestVersion.java │ ├── MergeNumbers.java │ ├── MessageSplit.java │ ├── MinimumDifferencePermutations.java │ ├── NonRepeatingCharacter.java │ ├── README.md │ ├── ReturnNRepeated.java │ └── WordCounts.java │ ├── crunch │ ├── CrunchPersonRecordsToAvro.java │ └── Person.java │ ├── datastructures │ ├── array │ │ └── SmallestNumber.java │ ├── linkedlist │ │ ├── Caller.java │ │ └── LinkedList.java │ ├── queue │ │ ├── Caller.java │ │ ├── PrintNBinaryNumber.java │ │ └── Queue.java │ ├── stack │ │ ├── Caller.java │ │ └── Stack.java │ └── tree │ │ ├── BinarySearchTree.java │ │ ├── Caller.java │ │ └── Node.java │ ├── designpatterns │ ├── builder │ │ ├── Caller.java │ │ └── PersonBuilder.java │ ├── factory │ │ ├── Caller.java │ │ ├── Car.java │ │ ├── CarFactory.java │ │ ├── HatchBack.java │ │ ├── SUV.java │ │ └── Sedan.java │ └── singleton │ │ ├── Caller.java │ │ ├── DoubleCheckedSingleton.java │ │ ├── LazySingleton.java │ │ ├── Singleton.java │ │ └── ThreadSafeSingleton.java │ ├── exceptions │ ├── Caller.java │ └── OddNumberException.java │ ├── garbagecollection │ └── Caller.java │ ├── hive │ └── HelloUDF.java │ ├── javacollection │ ├── CollectionDataStructure.java │ ├── HashMapVsHashTable.java │ ├── LinkedListAsStack.java │ ├── MapDataStructure.java │ ├── StackInDS.java │ ├── comparable │ │ ├── Caller.java │ │ └── Employee.java │ └── comparator │ │ ├── Caller.java │ │ ├── Movie.java │ │ └── RatingComparator.java │ ├── javarefresher │ ├── immutable │ │ ├── Address.java │ │ ├── Caller.java │ │ └── Employee.java │ └── strings │ │ └── Strings.java │ ├── jdk │ ├── Executable.java │ ├── FirstInterface.java │ ├── JDK8InterfaceFeature.java │ ├── JDK8StreamTimeAPI.java │ └── SecondInterface.java │ ├── kafka │ ├── ConsumerClient.java │ ├── ProducerClient.java │ └── TweetProducer.java │ ├── kafkaspark │ └── KafkaSparkStream.java │ ├── mapreduce │ ├── BixiMontrealAnalysis.java │ ├── SalesCount.java │ └── WordCountMapReduce.java │ ├── marker │ ├── cloneable │ │ ├── Caller.java │ │ └── Student.java │ ├── externalizable │ │ ├── Caller.java │ │ └── Car.java │ └── serializable │ │ ├── Caller.java │ │ └── Car.java │ ├── multithreading │ ├── callable │ │ └── CallableExecutor.java │ ├── creation │ │ ├── Caller.java │ │ └── HelloThread.java │ ├── deadlock │ │ └── DeadLock.java │ ├── executorservice │ │ ├── ThreadPool.java │ │ └── WorkerThread.java │ ├── performance │ │ ├── SumRange.java │ │ └── ThreadPerformance.java │ ├── producerconsumer │ │ ├── BlockingQueue.java │ │ └── Caller.java │ └── waitnotify │ │ ├── Caller.java │ │ └── Customer.java │ ├── recursion │ ├── Factorial.java │ ├── FibonacciSeries.java │ ├── HelloWorld.java │ └── RecursionCounter.java │ ├── spark │ └── SparkRDDWordCount.java │ └── strings │ └── StringCompareTo.java └── resources ├── images ├── concurrency │ └── concurrency.png └── java │ ├── collections.png │ ├── maps.png │ ├── thread-lifecycle.png │ └── throwable.png ├── interview-answers.md └── interview-questions.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | patreon: amarkumar 4 | open_collective: # Replace with a single Open Collective username 5 | ko_fi: # Replace with a single Ko-fi username 6 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 7 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 8 | liberapay: # Replace with a single Liberapay username 9 | issuehunt: # Replace with a single IssueHunt username 10 | otechie: # Replace with a single Otechie username 11 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/* 2 | target/ 3 | *.txt 4 | *.iml 5 | *.iml/ 6 | .DS_Store 7 | interview-brushups.iml 8 | 9 | src/main/resources/output/* -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Java, SQL, Data Structures & Algorithms, and Big Data Brushup 3 | 4 | This is a one-stop repository to look up code snippets related to core Java concepts, SQL queries, data structures, algorithms, and Big Data frameworks. Ideal for quick reference and brushing up on important concepts. 5 | 6 | ## Content 7 | 8 | ### Algorithms 9 | - Searching and Sorting algorithms. 10 | - Frequently asked programs. 11 | 12 | ### Apache Crunch 13 | - A framework to execute MapReduce jobs with sample programs. 14 | 15 | ### Data Structures 16 | - Arrays, LinkedLists, Stacks, Queues, Trees with code examples. 17 | 18 | ### Design Patterns 19 | - Implementation of popular design patterns: 20 | - Singleton 21 | - Factory 22 | - Builder 23 | 24 | ### Exceptions 25 | - Code snippets for creating custom exceptions in Java. 26 | 27 | ### Garbage Collection 28 | - Practical usage of Java Garbage Collection mechanisms. 29 | 30 | ### Java Collections 31 | - Examples showcasing the use of the Java Collection Framework. 32 | 33 | ### Java Refresher 34 | - Useful Java concepts for quick revision. 35 | 36 | ### JDK Features 37 | - Code snippets demonstrating new features introduced in various JDK versions. 38 | 39 | ### Kafka 40 | - Kafka Producer and Consumer programs with real-world examples. 41 | 42 | ### Kafka & Spark 43 | - Programs that process streaming data from Kafka using Spark. 44 | 45 | ### MapReduce 46 | - Simple programs demonstrating MapReduce concepts and implementations. 47 | 48 | ### Marker Interface 49 | - Examples of Marker Interfaces in Java. 50 | 51 | ### Multithreading 52 | - Snippets demonstrating multithreading in Java. 53 | 54 | ### Recursion 55 | - A collection of recursive programs. 56 | 57 | ### Spark 58 | - Spark programs such as the WordCount problem. 59 | 60 | ### String Concepts 61 | - Common string-related operations and concepts in Java. 62 | 63 | ## Resources 64 | 65 | ### Images 66 | - Contains useful images for various purposes. 67 | 68 | ### Interview Questions & Answers 69 | - A collection of interview questions & Answers from Java, Big Data, SQL, and more. 70 | 71 | ## Contribution 72 | Feel free to contribute by sending a Pull Request to this repository. 73 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 4.0.0 6 | com.interview.brushups 7 | interview-brushups 8 | 1.0-SNAPSHOT 9 | interview-brushups 10 | 11 | http://www.example.com 12 | 13 | UTF-8 14 | 1.7 15 | 1.7 16 | 17 | 18 | 19 | 20 | com.atlassian.commonmark 21 | commonmark 22 | 0.14.0 23 | 24 | 25 | 26 | 27 | com.twitter 28 | hbc-core 29 | 2.2.0 30 | 31 | 32 | 33 | org.apache.crunch 34 | crunch-core 35 | 0.14.0 36 | 37 | 38 | 39 | 40 | org.apache.hive 41 | hive-exec 42 | 3.1.2 43 | 44 | 45 | 46 | 47 | org.apache.hadoop 48 | hadoop-client 49 | 2.10.0 50 | 51 | 52 | 53 | org.apache.spark 54 | spark-sql_2.11 55 | 2.3.1 56 | provided 57 | 58 | 59 | 60 | org.apache.spark 61 | spark-core_2.11 62 | [2.3.3,) 63 | compile 64 | 65 | 66 | 67 | 68 | org.apache.spark 69 | spark-streaming_2.11 70 | 71 | [2.3.3,) 72 | 73 | 74 | 75 | 76 | org.apache.spark 77 | spark-streaming-kafka-0-10_2.11 78 | 79 | [2.3.3,) 80 | 81 | 82 | 83 | 84 | org.apache.kafka 85 | kafka-clients 86 | 0.10.2.1 87 | 88 | 89 | 90 | 91 | commons-io 92 | commons-io 93 | 2.5 94 | 95 | 96 | 97 | com.fasterxml.jackson.core 98 | jackson-databind 99 | 2.6.7.3 100 | 101 | 102 | 103 | jar 104 | 105 | 106 | 107 | maven-assembly-plugin 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | jar-with-dependencies 116 | 117 | 118 | 119 | 120 | make-assembly 121 | package 122 | 123 | single 124 | 125 | 126 | 127 | 128 | 129 | org.apache.maven.plugins 130 | maven-compiler-plugin 131 | 132 | 8 133 | 8 134 | 135 | 136 | 137 | 138 | 139 | org.skife.maven 140 | really-executable-jar-maven-plugin 141 | 1.1.0 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | interview 150 | 151 | 152 | 153 | package 154 | 155 | really-executable-jar 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/algorithm/searching/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.algorithm.searching; 2 | 3 | /** 4 | * Binary search works on the condition that array is sorted. 5 | * Binary Search has reduce time complexity to O(Log n). 6 | */ 7 | public class BinarySearch { 8 | 9 | public static void main(String args[]) { 10 | int[] array = {1, 2, 7, 5, 9, 32, 34, 36, 47}; 11 | 12 | for (int number : array) { 13 | System.out.print(number + " "); 14 | } 15 | int searchElement = 9; 16 | 17 | int index = binarySearch(array, 0, array.length - 1, searchElement); 18 | 19 | if (index != -1) { 20 | System.out.println("\nElement " + searchElement + " found at position: " + (index + 1)); 21 | return; 22 | } 23 | System.out.println("\nElement " + searchElement + "Not Found"); 24 | } 25 | 26 | static int binarySearch(int arr[], int low, int high, int x) { 27 | int mid = (low + high) / 2; 28 | 29 | // Only continue if there are more than two elements in the array 30 | if (low < high) { 31 | 32 | // If the searched element is exactly equal to mid, send the index 33 | if (x == arr[mid]) 34 | return mid; 35 | 36 | // If the searched element is less than mid element, call binary search with, 0 to middle-1 37 | if (x < arr[mid]) 38 | return binarySearch(arr, low, mid - 1, x); 39 | 40 | // Else search from middle+1 to last element 41 | return binarySearch(arr, mid + 1, high, x); 42 | } 43 | return -1; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/algorithm/searching/LinearSearch.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.algorithm.searching; 2 | 3 | /** 4 | * Linear Search is the simplest of all search algorithm. 5 | * The time complexity of above algorithm is O(n). 6 | */ 7 | public class LinearSearch { 8 | 9 | public static void main(String args[]) { 10 | int[] array = {90, 23, 101, 45, 65, 23, 67, 89, 34, 23}; 11 | 12 | for (int number : array) { 13 | System.out.print(number + " "); 14 | } 15 | int searchElement = 89; 16 | 17 | int index = linearSearch(array, searchElement); 18 | if (index != -1) { 19 | System.out.println("\nElement " + searchElement + " found at position: " + (index + 1)); 20 | return; 21 | } 22 | System.out.println("\nElement " + searchElement + "Not Found"); 23 | } 24 | 25 | public static int linearSearch(int[] array, int value) { 26 | for (int i = 0; i < array.length; i++) { 27 | if (value == array[i]) { 28 | return i; 29 | } 30 | } 31 | return -1; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/algorithm/sorting/MergerSort.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.algorithm.sorting; 2 | 3 | /** 4 | * Like, QuickSort Merge Sort also use Divide and Conquer algorithm for sorting the element 5 | * Video Explanation : https://www.youtube.com/watch?v=JSceec-wEyw 6 | * Approach - Divide and Conquer 7 | * Time Complexity - Time complexity of Merge Sort for all cases is nLogn 8 | */ 9 | public class MergerSort { 10 | 11 | public static void main(String args[]) { 12 | int[] array = {90, 23, 101, 45, 65, 23, 67, 89, 34, 23}; 13 | mergeSort(array, 0, array.length - 1); 14 | 15 | for (int number : array) { 16 | System.out.println(number); 17 | } 18 | } 19 | 20 | static void merge(int[] arr, int start, int mid, int end) { 21 | 22 | int l = mid - start + 1; 23 | int r = end - mid; 24 | int i, j; 25 | 26 | int[] LeftArray = new int[l]; 27 | int[] RightArray = new int[r]; 28 | 29 | for (i = 0; i < l; ++i) 30 | LeftArray[i] = arr[start + i]; 31 | 32 | for (j = 0; j < r; ++j) 33 | RightArray[j] = arr[mid + 1 + j]; 34 | 35 | i = 0; 36 | j = 0; 37 | int k = start; 38 | while (i < l && j < r) { 39 | if (LeftArray[i] <= RightArray[j]) { 40 | arr[k] = LeftArray[i]; 41 | i++; 42 | } else { 43 | arr[k] = RightArray[j]; 44 | j++; 45 | } 46 | k++; 47 | } 48 | while (i < l) { 49 | arr[k] = LeftArray[i]; 50 | i++; 51 | k++; 52 | } 53 | 54 | while (j < r) { 55 | arr[k] = RightArray[j]; 56 | j++; 57 | k++; 58 | } 59 | } 60 | 61 | static void mergeSort(int[] arr, int start, int end) { 62 | 63 | // if start is less than end, meaning the array has at least two element, do the operation. 64 | if (start < end) { 65 | 66 | //find the mid, by dividing by 2 67 | int mid = (start + end) / 2; 68 | 69 | //call to divide the array into sub-arrays and perform a merge by sorting the elements 70 | mergeSort(arr, start, mid); 71 | mergeSort(arr, mid + 1, end); 72 | merge(arr, start, mid, end); 73 | } 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/algorithm/sorting/QuickSort.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.algorithm.sorting; 2 | 3 | /** 4 | * Quick Sort is the most effective in average case of Sorting Algorithm 5 | * Merge Sort has time complexity of every case as nLogn, but take so much of space,not optimal for large arrays 6 | * Video Explanation : https://www.youtube.com/watch?v=PgBzjlCcFvc 7 | * Approach - Divide and Conquer 8 | * Time Complexity - Time complexity of Quick Sort for average case is nLogn and worst case n^2 9 | */ 10 | public class QuickSort { 11 | 12 | public static void main(String args[]) { 13 | int[] array = {34, 36, 2, 9, 9, 32, 47, 7, 1}; 14 | quickSort(array, 0, array.length - 1); 15 | 16 | for (int number : array) { 17 | System.out.println(number); 18 | } 19 | } 20 | 21 | /** 22 | * 23 | * The partition does shifts operations, 24 | * all the lesser element of the pivot to left side and greater element to right side 25 | * 26 | * @param array 27 | * @param low 28 | * @param high 29 | * @return 30 | */ 31 | static int getPartition(int[] array, int low, int high) { 32 | int pivot = array[high]; 33 | 34 | //set it to -1 for 1st pass 35 | int i = low - 1; 36 | 37 | for (int j = low; j < high; j++) { 38 | 39 | // if the value are less than pivot keep swapping the elements 40 | if (array[j] < pivot) { 41 | i++; // increment the i 42 | int temp = array[i]; 43 | array[i] = array[j]; 44 | array[j] = temp; 45 | } 46 | } 47 | 48 | //put the pivot at the correct place by swapping, 49 | int temp = array[i + 1]; 50 | array[i + 1] = array[high]; 51 | array[high] = temp; 52 | 53 | // i+1 returns the location of correctly place pivot element 54 | return i + 1; 55 | } 56 | 57 | static void quickSort(int[] array, int low, int high) { 58 | { 59 | if (low < high) { 60 | //get the index of pivot element 61 | int pi = getPartition(array, low, high); 62 | 63 | //call the recursive function 64 | quickSort(array, low, pi - 1); 65 | quickSort(array, pi + 1, high); 66 | } 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/algorithm/sorting/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.algorithm.sorting; 2 | 3 | /** 4 | * Selection Sort is the most simplest of Sorting Algorithm 5 | */ 6 | public class SelectionSort { 7 | 8 | public static void main(String args[]) { 9 | int[] array = {34, 36, 2, 9, 47, 7, 1}; 10 | selectionSort(array); 11 | 12 | for (int number : array) { 13 | System.out.println(number); 14 | } 15 | } 16 | 17 | public static void selectionSort(int[] array) { 18 | for (int i = 0; i < array.length; i++) { 19 | 20 | //store the minimum value as that index 21 | int min = array[i]; 22 | 23 | //also store the index is being worked 24 | int minId = i; 25 | 26 | //run another loop and lookup an element skipping the current element 27 | for (int j = i + 1; j < array.length; j++) { 28 | 29 | // if the next element and forward element is shorter than the current minimum 30 | // capture the index of it, and store the index 31 | if (array[j] < min) { 32 | min = array[j]; 33 | minId = j; 34 | } 35 | } 36 | 37 | // now we have the selected the shortest element, exchange it with the current index 38 | int temp = array[i]; 39 | array[i] = min; 40 | array[minId] = temp; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/BalancedParenthesis.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.*; 4 | 5 | public class BalancedParenthesis 6 | { 7 | public static int findBalanced () 8 | { 9 | Scanner scan = new Scanner(System.in); 10 | 11 | Stack stack = new Stack(); 12 | System.out.println("Parenthesis Matching Test\n"); 13 | 14 | System.out.println("Enter expression"); 15 | String exp = scan.next(); 16 | int len = exp.length(); 17 | 18 | for (int i = 0; i < len; i++) 19 | { 20 | char character = exp.charAt(i); 21 | if (character == '(') 22 | stack.push(i); 23 | else if (character == ')') 24 | { 25 | stack.pop(); 26 | } 27 | } 28 | 29 | if (!stack.isEmpty()) { 30 | return -1; 31 | } 32 | return 1; 33 | } 34 | 35 | public static void main(String args[]){ 36 | System.out.println(findBalanced()); 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/CountCharacter.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | 6 | public class CountCharacter { 7 | 8 | /** 9 | * Interview Company - Nokia 10 | * Given a String which has character in repeated sequence. 11 | * Output a String which contains how many times a character has been repeated. 12 | * @param args 13 | */ 14 | public static void main(String[] args) { 15 | 16 | String word = "aazzzBBB"; 17 | String output = ""; 18 | 19 | Map < Character, Integer > map = new LinkedHashMap < > (); 20 | for (int i = 0; i < word.length(); i++) { 21 | char c = word.charAt(i); 22 | if(map.containsKey(c)){ 23 | int count = map.get(c); 24 | map.put(c,++count); 25 | } 26 | else map.put(c, 1); 27 | } 28 | 29 | for (Map.Entry entry: map.entrySet()) { 30 | output = output + entry.getKey() + entry.getValue(); 31 | } 32 | System.out.println(output); 33 | } 34 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/FindDifferenceEqualsTarget.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | 6 | 7 | /** 8 | * Interview Company - Walmart 9 | * Given a array, and a target number 10 | * Output true or false, if the repeated number, with difference with base Index is equal to target number 11 | * 12 | */ 13 | class FindDifferenceEqualsTarget { 14 | public static void main(String[] args) { 15 | int numbers[] = {2, 3, 2, 4, 5, 7}; 16 | int target = 2; 17 | System.out.println(isIndexDiffSame(numbers, target)); 18 | } 19 | 20 | public static boolean isIndexDiffSame(int[] numbers, int target) { 21 | Map numMap = new LinkedHashMap<>(); 22 | for (int i = 0; i < numbers.length; i++) { 23 | if (!numMap.containsKey(numbers[i])) { 24 | numMap.put(numbers[i], i); 25 | } else { 26 | int prevIndex = numMap.get(numbers[i]); 27 | int resultant = i - prevIndex; 28 | if (resultant == target) { 29 | return true; 30 | } 31 | } 32 | } 33 | return false; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/FindFragmentsEqualsZero.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | /** 4 | * Write a Program that returns number of Fragments of a List whose Sum Equals to 0 5 | * Codility - given an array A consisting of N integers, returns the number of fragments of A 6 | */ 7 | public class FindFragmentsEqualsZero { 8 | 9 | public static int findFragments(int[] arrayOfNumbers) { 10 | 11 | int zeroCounter = 0; 12 | int patternSequence = 0; 13 | int value; 14 | 15 | //get the length of the array 16 | int length = arrayOfNumbers.length; 17 | 18 | // If it has only one value, if it's not 0, return 0 directly. 19 | if (length == 1) { 20 | if (arrayOfNumbers[0] != 0) { 21 | return 0; 22 | } 23 | } 24 | // iterate through the list, if it has a zero, ++ the zeroCounter 25 | for (int i = 0; i < length; i++) { 26 | if (arrayOfNumbers[i] == 0) { 27 | zeroCounter++; 28 | } 29 | int sum = arrayOfNumbers[i]; 30 | 31 | for (int j = i + 1; j < length; j++) { 32 | sum = sum + arrayOfNumbers[j]; 33 | if (sum == 0) { 34 | patternSequence++; 35 | } 36 | } 37 | } 38 | value = zeroCounter + patternSequence; 39 | return value; 40 | } 41 | 42 | public static void main(String[] args) { 43 | int[] arrayOfNumbers = {2, -2, 3, 0, 4, -7}; 44 | System.out.println("\nNumber of Such Fragments : " + findFragments(arrayOfNumbers)); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/FindMinPossibleNumberForSum.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | /** 4 | * Interview Company - JP Morgan & Chase 5 | * In an array, find the minimum number required to add from the list to get the sum greater or equals to given number. 6 | */ 7 | import java.util.*; 8 | 9 | public class FindMinPossibleNumberForSum { 10 | 11 | public static void main(String[] args) { 12 | Integer input[] = {1, 3, 4, 2}; 13 | int sum = 5; 14 | 15 | List numbers = Arrays.asList(input); 16 | Collections.sort(numbers); 17 | 18 | int numberCount = 0; 19 | int summation = 0; 20 | 21 | for (int i = numbers.size()-1; i >= 0; i--) { 22 | summation += numbers.get(i); 23 | numberCount++; 24 | if (summation >= sum) { 25 | System.out.println(numberCount); 26 | break; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/FindNonRepetitiveSum.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * Interview Company - GlobalLogic 7 | * Find sum of non-repeating (distinct) elements in an array 8 | */ 9 | public class FindNonRepetitiveSum { 10 | public static void main(String[] args) { 11 | List numbers = Arrays.asList(1, 2, 3, 4, 5, 2, 3, 4, 4); 12 | //output : 6 13 | 14 | Map map = new HashMap<>(); 15 | for (int number : numbers) { 16 | if (!map.containsKey(number)) { 17 | map.put(number, 1); 18 | } else { 19 | int value = map.get(number); 20 | map.put(number, ++value); 21 | } 22 | } 23 | int sum = 0; 24 | for (Map.Entry entry : map.entrySet()) { 25 | if ((int) entry.getValue() == 1) { 26 | sum += (int) entry.getKey(); 27 | } 28 | } 29 | System.out.println("Sum of Distinct is :" + sum); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/FindNxtGreatest.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Interview Company - 24/7 8 | * Given an array, find the greatest element to the right side of it at immediate 9 | */ 10 | public class FindNxtGreatest { 11 | public static void main(String[] args) { 12 | int numArray[] = {5, 41, 3, 7, 18}; 13 | List numbers = new ArrayList<>(); 14 | 15 | for (int i = 0; i < numArray.length; i++) { 16 | boolean isValueFound = false; 17 | for (int j = i + 1; j < numArray.length; j++) { 18 | if (numArray[i] < numArray[j]) { 19 | numbers.add(numArray[j]); 20 | isValueFound = true; 21 | break; 22 | } 23 | } 24 | if (!isValueFound) { 25 | numbers.add(-1); 26 | } 27 | } 28 | 29 | for (int number : numbers) { 30 | System.out.println(number); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/FindPairsInArraySum.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Find Pairs in an array, whose sum is X 7 | * Complexity - O(n), since we traverse the array only once 8 | */ 9 | public class FindPairsInArraySum { 10 | 11 | static void findPairs(int arr[], int sum) { 12 | HashSet set = new HashSet(); 13 | 14 | for(int i=0; i < arr.length; i++){ 15 | 16 | // calculate the required number which will form the sum in set 17 | int required = sum - arr[i]; 18 | 19 | // if the required number is present in set, current & required number will be a pair 20 | if(set.contains(required)){ 21 | System.out.println("["+required+", "+arr[i]+"]"); 22 | } 23 | 24 | // if required number is not present, add the current number to set. 25 | else { 26 | set.add(arr[i]); 27 | } 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | int A[] = {1, 4, 45, 6, 10, 8, 8, 7, 12}; 33 | int n = 16; 34 | findPairs(A, n); 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/FindPanagram.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Accolite - Find all Missing character in order missing from the String 8 | */ 9 | public class FindPanagram { 10 | public static void main(String[] args) { 11 | String s = "The quick brown fox jumps"; 12 | 13 | List asciiList = new ArrayList(); 14 | 15 | for (int i = 97; i <= 122; i++) { 16 | asciiList.add((char) i); 17 | } 18 | 19 | for (int i = 0; i < s.length(); i++) { 20 | try { 21 | int index = asciiList.indexOf(s.charAt(i)); 22 | asciiList.remove(index); 23 | } catch (Exception e) { 24 | } 25 | } 26 | 27 | for (char ch : asciiList) { 28 | System.out.print(ch); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/FindRepeatedNumbers.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.HashSet; 4 | 5 | /** 6 | * Find if a number is repeated in an integer array 7 | */ 8 | public class FindRepeatedNumbers { 9 | 10 | public static void main(String[] args) { 11 | int[] array = {23, 7, 23, 8, 84, 93, 7, 9, 9}; 12 | 13 | HashSet < Integer > uniqueElement = new HashSet(); 14 | HashSet < Integer > repeatedElement = new HashSet(); 15 | 16 | for (int i = 0; i < array.length; i++) { 17 | if (uniqueElement.contains(array[i])) { 18 | repeatedElement.add(array[i]); 19 | } else { 20 | repeatedElement.add(array[i]); 21 | } 22 | } 23 | 24 | for (Integer number: uniqueElement) { 25 | System.out.println(number); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/FindSecondLargest.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | /** 4 | * Program to Find Second Largest in an Array - Accolite 5 | */ 6 | public class FindSecondLargest { 7 | 8 | public static void main(String[] args) { 9 | int array[] = {1, 9, 5, 11, 34, 38}; 10 | 11 | int result = secondLargest(array); 12 | System.out.println("Second Largest Value is : " + result); 13 | } 14 | 15 | /** 16 | * Method to print the second largest elements 17 | */ 18 | public static int secondLargest(int array[]) { 19 | int first = Integer.MIN_VALUE; 20 | int second = Integer.MIN_VALUE; 21 | 22 | int n = array.length; 23 | 24 | // There should be at-least two element in the array 25 | if (n < 2) { 26 | System.out.println("There should be at-least two elements in the array"); 27 | System.exit(0); 28 | } 29 | 30 | for (int i = 0; i < n; i++) { 31 | 32 | // If current element is greater than, first then update both first and second 33 | if (array[i] > first) { 34 | // store the previous max value to second variable 35 | second = first; 36 | first = array[i]; 37 | } 38 | 39 | // If arr[i] is greater than second, and not equals to first, update second */ 40 | else if (array[i] > second && array[i] != first) 41 | second = array[i]; 42 | } 43 | if(second == Integer.MIN_VALUE){ 44 | System.out.println("No Second Largest Element"); 45 | System.exit(0); 46 | } 47 | return second; 48 | } 49 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/FindSquareOfNumbersInAscending.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.Collections; 4 | import java.util.LinkedList; 5 | 6 | /** 7 | * Interview Company - 24/7 8 | * Find square of numbers in a ascending order of the number 9 | */ 10 | public class FindSquareOfNumbersInAscending { 11 | public static void main(String[] args) { 12 | int numArray[] = {-7, -5, 2, 5, 7, 8, 9}; 13 | LinkedList numbers = new LinkedList<>(); 14 | 15 | for (int number : numArray) { 16 | numbers.add(Math.abs(number)); 17 | } 18 | Collections.sort(numbers); 19 | for (int n : numbers) { 20 | System.out.println(Math.pow(n, 2)); 21 | } 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/FindXtoXPlusOne.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Codility - given two integers A and B, returns the number of integers from the range [A..B] 7 | */ 8 | public class FindXtoXPlusOne { 9 | 10 | public static int solution(int A, int B) { 11 | int counter = 0; 12 | int value = 0; 13 | int x = (int) Math.sqrt(A); 14 | 15 | while (value < B) { 16 | value = x * (x + 1); //3 , 6, 12, 15, 20, 30 17 | 18 | if (value >= A && value <= B) { 19 | System.out.println(x + " * " + (x + 1) + " = " + value); 20 | counter++; 21 | } 22 | x++; 23 | } 24 | return counter; 25 | } 26 | 27 | public static void main(String[] args) { 28 | Scanner scanner = new Scanner(System.in); 29 | System.out.println("Enter Number 1"); 30 | int numberA = scanner.nextInt(); 31 | System.out.println("Enter Number 2"); 32 | int numberB = scanner.nextInt(); 33 | System.out.println("Total occurrence for X*(X+1) for range " + numberA + " & " + numberB + " is : " + solution(numberA, numberB)); 34 | } 35 | } 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/GCFOfNumberList.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | /** 8 | * Interview Company - OLA Cabs 9 | * Find GCF of list of numbers 10 | */ 11 | public class GCFOfNumberList { 12 | 13 | public static void main(String[] args) { 14 | Integer number[] = {6, 12, 9}; 15 | List numberList = Arrays.asList(number); 16 | 17 | int maximum = Collections.min(numberList); 18 | for (int i = maximum; i > 0; i--) { 19 | 20 | boolean result = isListDivisible(numberList, i); 21 | if (result) { 22 | System.out.println("GCF for the Number : " + i); 23 | break; 24 | } 25 | } 26 | } 27 | 28 | public static boolean isModZero(int number, int max) { 29 | if ((number % max) == 0) { 30 | return true; 31 | } 32 | return false; 33 | } 34 | 35 | public static boolean isListDivisible(List list, int max) { 36 | boolean isModeZeroForAll = true; 37 | for (Integer number : list) { 38 | if (!isModZero(number, max)) { 39 | isModeZeroForAll = false; 40 | } 41 | } 42 | return isModeZeroForAll; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/HighestVersion.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | /** 9 | * Interview Company - Falabella 10 | * Find Latest version of each Entity 11 | *

12 | * Expected Output 13 | * customers-10.2.3 14 | * products-2.8.1 15 | * stores-2.7.10 16 | */ 17 | 18 | public class HighestVersion { 19 | public static void main(String[] args) { 20 | 21 | List entityDetails = new ArrayList<>(); 22 | entityDetails.add("customers-1.0.23"); 23 | entityDetails.add("products-2.8.1"); 24 | entityDetails.add("products-2.7.2"); 25 | entityDetails.add("customers-10.2.3"); 26 | entityDetails.add("stores-2.7.1"); 27 | entityDetails.add("stores-2.7.10"); 28 | 29 | Map latestEntityMap = new HashMap<>(); 30 | for (String entity : entityDetails) { 31 | String[] entityVersionKV = entity.split("-"); 32 | if (!latestEntityMap.containsKey(entityVersionKV[0])) { 33 | latestEntityMap.put(entityVersionKV[0], entityVersionKV[1]); 34 | } else { 35 | String storedVersion = latestEntityMap.get(entityVersionKV[0]); 36 | String currentVersion = latestEntityMap.get(entityVersionKV[1]); 37 | 38 | boolean isVersionHigher = versionComparison(storedVersion, currentVersion); 39 | if (isVersionHigher) { 40 | latestEntityMap.put(entityVersionKV[0], entityVersionKV[1]); 41 | } 42 | } 43 | } 44 | 45 | for (Map.Entry entry : latestEntityMap.entrySet()) { 46 | System.out.println(entry.getKey() + " -> " + entry.getValue()); 47 | } 48 | } 49 | 50 | public static boolean versionComparison(String stored, String current) { 51 | boolean isVersionHigher = false; 52 | String storedVersionSub[] = stored.split("."); 53 | String currentVersionSub[] = current.split("."); 54 | 55 | for (int i = 0; i < storedVersionSub.length; i++) { 56 | if (Integer.parseInt(currentVersionSub[i]) > Integer.parseInt(storedVersionSub[i])) { 57 | isVersionHigher = true; 58 | } 59 | } 60 | return isVersionHigher; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/MergeNumbers.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2. 7 | * 8 | * Example 1: 9 | * 10 | * Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 11 | * Output: [1,2,2,3,5,6] 12 | * Example 2: 13 | * 14 | * Input: nums1 = [1], m = 1, nums2 = [], n = 0 15 | * Output: [1] 16 | */ 17 | public class MergeNumbers { 18 | 19 | public static void main(String[] args) { 20 | 21 | int[] nums1 = {1, 2, 3, 0, 0, 0}; 22 | int[] nums2 = {2, 5, 6}; 23 | 24 | if (nums2.length == 0) { 25 | for (int n : nums1) { 26 | System.out.print(n + " "); 27 | } 28 | System.exit(0); 29 | } 30 | 31 | int numStartIndex = (nums1.length - nums2.length); 32 | 33 | int nums2Index = 0; 34 | for (int i = numStartIndex; i < nums1.length; i++) { 35 | nums1[i] = nums2[nums2Index]; 36 | nums2Index++; 37 | } 38 | Arrays.sort(nums1); 39 | 40 | for (int n : nums1) { 41 | System.out.print(n + " "); 42 | } 43 | 44 | } 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/MessageSplit.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Twilio - Split the message by 160 character, and also add the pagination 8 | */ 9 | public class MessageSplit { 10 | 11 | public static void main(String[] args) { 12 | 13 | String textMessage = "Lorem Ipsum is simply dummy text of the printing and typesetting industry." + 14 | " Lorem Ipsum has been the industry's standard dummy text ever since the 1500s," + 15 | " when an unknown printer took a galley of type and scrambled it to make a type specimen book." + 16 | " It has survived not only five centuries, but also the leap into electronic typesetting," + 17 | " remaining essentially unchanged. " + 18 | " It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages," + 19 | " and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."; 20 | 21 | System.out.println(segments(textMessage)); 22 | } 23 | 24 | static List segments(String message) { 25 | List messages = new ArrayList<>(); 26 | final int splitLength = 154; 27 | if (message.length() < 160) { 28 | messages.add(message); 29 | return messages; 30 | } 31 | int start = 0, end = start + splitLength; 32 | while (end < message.length()) { 33 | if (message.charAt(end) != ' ') { 34 | while (end >= start && message.charAt(end) != ' ' && message.charAt(end + 1) != ' ') { 35 | end--; 36 | } 37 | } 38 | messages.add(message.substring(start, end + 1)); 39 | start = end + 1; 40 | end = start + splitLength; 41 | } 42 | messages.add(message.substring(start, message.length())); 43 | 44 | for (int j = 0; j < messages.size(); j++) { 45 | messages.set(j, messages.get(j) + "(" + (j + 1) + "/" + (messages.size()) + ")"); 46 | } 47 | return messages; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/MinimumDifferencePermutations.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.Collections; 4 | import java.util.List; 5 | import java.util.Set; 6 | 7 | /** 8 | * Interview Company - CRISIL 9 | * Find the minimum number from permutations 10 | */ 11 | public class MinimumDifferencePermutations { 12 | 13 | public static void main(String[] args) { 14 | int arr[] = {7, 3, 2, 4, 12, 56}; 15 | int students = 3; 16 | Set> allPermutations = Collections.singleton(getAllPermutations(students)); 17 | System.out.println(findMinDifference(arr,allPermutations)); 18 | } 19 | 20 | public static int findMinDifference(int arr[], Set> allPermutations ) { 21 | int minValue = Integer.MAX_VALUE; 22 | for(List currentSet : allPermutations) 23 | { 24 | int min = Collections.min(currentSet); 25 | int max = Collections.max(currentSet); 26 | int result = max-min; 27 | if(result< minValue){ 28 | minValue = result; 29 | } 30 | } 31 | return minValue; 32 | } 33 | 34 | public static List getAllPermutations(int students){ 35 | return null; 36 | } 37 | 38 | 39 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/NonRepeatingCharacter.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.HashMap; 4 | import java.util.LinkedHashMap; 5 | import java.util.Map; 6 | 7 | /** 8 | * Accolite, Tavant - Find first non-repeating character in a String 9 | */ 10 | public class NonRepeatingCharacter { 11 | 12 | public static void main(String[] args) { 13 | String s = "abcadc"; 14 | 15 | HashMap charMap = new LinkedHashMap<>(); 16 | for (int i = 0; i < s.length(); i++) { 17 | if (!charMap.containsKey(s.charAt(i))) { 18 | charMap.put(s.charAt(i), 1); 19 | } else { 20 | int count = charMap.get(s.charAt(i)); 21 | charMap.put(s.charAt(i), ++count); 22 | } 23 | } 24 | 25 | for (Map.Entry entry : charMap.entrySet()) { 26 | if ((Integer) entry.getValue() == 1) { 27 | System.out.println(entry.getKey()); 28 | System.exit(0); 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Java Programming Challenges 4 | 5 | Here are a series of programming questions designed to test your problem-solving skills in Java. Each question is accompanied by a hint to guide you toward a solution. 6 | 7 | ## 1. Balanced Parentheses 8 | **Question**: 9 | Write a program that checks whether a given string containing various types of parentheses `()`, `[]`, `{}` is balanced. A string is considered balanced if every opening parenthesis has a corresponding closing parenthesis in the correct order. 10 | 11 | **Hint**: 12 | Use a stack to keep track of opening parentheses. When you encounter a closing parenthesis, check if it matches the type of the last opening parenthesis on the stack. 13 | 14 | --- 15 | 16 | ## 2. Character Count in a String 17 | **Question**: 18 | Develop a program that counts the number of occurrences of each character in a given string and displays the counts. 19 | 20 | **Hint**: 21 | Utilize a HashMap where the key is the character and the value is the count of its occurrences. 22 | 23 | --- 24 | 25 | ## 3. Find Pairs with Target Difference 26 | **Question**: 27 | Given an array of integers and a target number, find all pairs of integers in the array whose difference equals the target number. 28 | 29 | **Hint**: 30 | Sort the array to simplify finding pairs. Alternatively, use a HashSet to store elements and check if element ± target exists in the set. 31 | 32 | --- 33 | 34 | ## 4. Subarrays Summing to Zero 35 | **Question**: 36 | Write a program to find all contiguous subarrays within a given array of integers that sum up to zero. 37 | 38 | **Hint**: 39 | Use a HashMap to store the cumulative sum at each index. If the same cumulative sum appears more than once, the subarray between the indices sums to zero. 40 | 41 | --- 42 | 43 | ## 5. Minimum Number for Given Sum and Digits 44 | **Question**: 45 | Given a target sum and a number of digits, find the smallest possible number with the given number of digits whose digits add up to the target sum. 46 | 47 | **Hint**: 48 | Start filling the number from the most significant digit. Assign the smallest possible digit to each position while ensuring the total sum of the digits equals the target sum. 49 | 50 | --- 51 | 52 | ## 6. Sum of Non-Repetitive Numbers 53 | **Question**: 54 | Calculate the sum of all non-repetitive (unique) numbers in a given array of integers. 55 | 56 | **Hint**: 57 | Use a HashMap or HashSet to keep track of the frequency of each number. Sum only the numbers that appear exactly once. 58 | 59 | --- 60 | 61 | ## 7. Next Greatest Element 62 | **Question**: 63 | For each element in an array of integers, find the next greatest element to its right. If there is no greater element, assign -1 to that position. 64 | 65 | **Hint**: 66 | Traverse the array using a stack to keep track of indices whose next greater element hasn't been found yet. 67 | 68 | --- 69 | 70 | ## 8. Find Pairs with Given Sum 71 | **Question**: 72 | Given an array of integers and a target sum, find all unique pairs of numbers that add up to the target sum. 73 | 74 | **Hint**: 75 | Use a HashSet to store elements and check if the complement (target sum minus the current element) exists. 76 | 77 | --- 78 | 79 | ## 9. Check for Pangram 80 | **Question**: 81 | Write a program to determine if a given string is a pangram. A pangram is a sentence that contains every letter of the alphabet at least once. 82 | 83 | **Hint**: 84 | Use a boolean array or a HashSet to keep track of the letters present in the string. 85 | 86 | --- 87 | 88 | ## 10. Find Repeated Numbers 89 | **Question**: 90 | Identify all numbers that are repeated in a given array of integers. 91 | 92 | **Hint**: 93 | Use a HashMap to count the occurrences of each number and collect those with a count greater than one. 94 | 95 | --- 96 | 97 | ## 11. Second Largest Element 98 | **Question**: 99 | Find the second largest element in an unsorted array of integers. 100 | 101 | **Hint**: 102 | Iterate through the array while keeping track of the largest and second-largest elements. 103 | 104 | --- 105 | 106 | ## 12. Sorted Squares of Numbers 107 | **Question**: 108 | Given a sorted array of integers (which may include negative numbers), create a new array containing the squares of each number, also sorted in ascending order. 109 | 110 | **Hint**: 111 | Use two pointers starting from the ends of the array to compare squares and fill the new array from the highest index down. 112 | 113 | --- 114 | 115 | ## 13. Find Consecutive Number Sequences Summing to N 116 | **Question**: 117 | Given a positive integer `N`, find all sequences of consecutive positive integers that sum up to `N`. 118 | 119 | **Hint**: 120 | Use a sliding window approach with two pointers to find all such sequences. 121 | 122 | --- 123 | 124 | ## 14. Greatest Common Factor of a List 125 | **Question**: 126 | Write a program to compute the Greatest Common Factor (GCF) of a list of positive integers. 127 | 128 | **Hint**: 129 | Use the Euclidean algorithm iteratively on the list by finding the GCF of pairs of numbers. 130 | 131 | --- 132 | 133 | ## 15. Highest Version Number 134 | **Question**: 135 | Given a list of software version numbers (e.g., "1.2.3", "1.2.10", "1.3.0"), determine the highest version number. 136 | 137 | **Hint**: 138 | Split each version string by the dot delimiter and compare each segment numerically. 139 | 140 | --- 141 | 142 | ## 16. Merge Two Sorted Arrays 143 | **Question**: 144 | Merge two sorted arrays of integers into a single sorted array without duplicates. 145 | 146 | **Hint**: 147 | Use two pointers to traverse both arrays and compare elements, adding the smaller one to the new array and skipping duplicates. 148 | 149 | --- 150 | 151 | ## 17. Split Messages with Character Limit 152 | **Question**: 153 | Given a long message and a maximum character limit per message (including a suffix like (1/3)), split the message into multiple parts without breaking words, ensuring each part is within the character limit. 154 | 155 | **Hint**: 156 | While splitting, account for the length of the suffix. Use string manipulation to ensure words aren't split between messages. 157 | 158 | --- 159 | 160 | ## 18. Minimum Difference Permutation 161 | **Question**: 162 | Given two arrays of equal length, permute one array so that the sum of absolute differences between corresponding elements of the two arrays is minimized. 163 | 164 | **Hint**: 165 | Sort both arrays in ascending order and then calculate the sum of absolute differences. 166 | 167 | --- 168 | 169 | ## 19. First Non-Repeating Character 170 | **Question**: 171 | Find the first non-repeating character in a given string. 172 | 173 | **Hint**: 174 | Use a LinkedHashMap to preserve insertion order while counting character occurrences. 175 | 176 | --- 177 | 178 | ## 20. Element Repeated N Times 179 | **Question**: 180 | An array of size `2N` contains `N+1` unique elements, where one element is repeated `N` times. Find the element that is repeated. 181 | 182 | **Hint**: 183 | Use a HashMap or a HashSet to track element frequencies. The element with a count of `N` is your answer. 184 | 185 | --- 186 | 187 | ## 21. Word Count in Text 188 | **Question**: 189 | Write a program that counts the number of occurrences of each word in a given text. 190 | 191 | **Hint**: 192 | Normalize the text by converting it to lowercase and removing punctuation. Use a HashMap where keys are words and values are their counts. 193 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/ReturnNRepeated.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * In an array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. 8 | * 9 | * Return the element repeated N times. 10 | * 11 | * Input: [1,2,3,3] 12 | * Output: 3 13 | * 14 | * Input: [2,1,2,5,3,2] 15 | * Output: 2 16 | * 17 | * Input: [5,1,5,2,5,3,5,4] 18 | * Output: 5 19 | */ 20 | public class ReturnNRepeated { 21 | 22 | public static void main(String[] args) { 23 | 24 | int arrayofN[] = {5,1,5,2,5,3,5,4}; 25 | int sizeOfArray = arrayofN.length; 26 | 27 | int nValue = sizeOfArray / 2; 28 | 29 | Map countStore = new HashMap<>(); 30 | 31 | for (int number : arrayofN) { 32 | if (!countStore.containsKey(number)) { 33 | countStore.put(number, 1); 34 | } else { 35 | int value = countStore.get(number); 36 | countStore.put(number, ++value); 37 | } 38 | } 39 | 40 | for (Map.Entry e : countStore.entrySet()) { 41 | if((Integer)e.getValue()==nValue){ 42 | System.out.println(e.getKey()); 43 | break; 44 | } 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/askedprograms/WordCounts.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.askedprograms; 2 | 3 | import java.io.*; 4 | 5 | public class WordCounts { 6 | 7 | public static void main(String[] args) throws IOException { 8 | String[] words; 9 | int wordCount = 0; 10 | //Create a File Object,to read the file from System. 11 | File file = new File("word-count.txt"); 12 | //Create a FileReader Object by inputting file name. 13 | FileReader fileReader = new FileReader(file); 14 | // Create a BufferReader object by passing the file. 15 | BufferedReader bufferedReader = new BufferedReader(fileReader); 16 | String line; 17 | while ((line = bufferedReader.readLine()) != null) { 18 | words = line.split(" "); 19 | wordCount = wordCount + words.length; 20 | } 21 | System.out.println(wordCount); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/crunch/CrunchPersonRecordsToAvro.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.crunch; 2 | 3 | import org.apache.crunch.*; 4 | import org.apache.crunch.impl.mr.MRPipeline; 5 | import org.apache.crunch.io.To; 6 | import org.apache.crunch.types.avro.Avros; 7 | import org.apache.hadoop.conf.Configuration; 8 | 9 | public class CrunchPersonRecordsToAvro { 10 | public static void main(String[] args) { 11 | 12 | // Input and Output path 13 | String inputPath = args[0]; 14 | String outputPath = args[1]; 15 | 16 | //Create a new Hadoop Job Configuration 17 | Configuration configuration = new Configuration(); 18 | 19 | //Create a Pipeline 20 | Pipeline pipeline = getPipeline(configuration); 21 | 22 | //Read PCollection of String from Text file. 23 | PCollection personDataEachLine = pipeline.readTextFile(inputPath); 24 | 25 | //Create a PCollection of Person record. 26 | PCollection personRecord = personDataEachLine.parallelDo(DoFnCreatePerson(), Avros.records(Person.class)); 27 | 28 | //Write collection to avro file. 29 | personRecord.write(To.avroFile(outputPath)); 30 | 31 | PipelineResult result = pipeline.done(); 32 | System.exit(result.succeeded() ? 0 : 1); 33 | } 34 | 35 | public static DoFn DoFnCreatePerson() { 36 | return new DoFn() { 37 | @Override 38 | public void process(String input, Emitter emitter) { 39 | String inputParts[] = input.split(","); 40 | String name = inputParts[0]; 41 | String roll = inputParts[1]; 42 | String city = inputParts[2]; 43 | emitter.emit(new Person(name, roll, city)); 44 | } 45 | }; 46 | } 47 | 48 | public static Pipeline getPipeline(final Configuration conf) { 49 | conf.setBoolean("mapred.output.compress", false); 50 | return new MRPipeline(Person.class, conf); 51 | } 52 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/crunch/Person.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.crunch; 2 | 3 | public class Person { 4 | 5 | String name; 6 | String roll; 7 | String city; 8 | 9 | public String getName() { 10 | return name; 11 | } 12 | 13 | public void setName(String name) { 14 | this.name = name; 15 | } 16 | 17 | public String getRoll() { 18 | return roll; 19 | } 20 | 21 | public void setRoll(String roll) { 22 | this.roll = roll; 23 | } 24 | 25 | public String getCity() { 26 | return city; 27 | } 28 | 29 | public void setCity(String city) { 30 | this.city = city; 31 | } 32 | 33 | public Person(String name, String roll, String city) { 34 | this.name = name; 35 | this.roll = roll; 36 | this.city = city; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/datastructures/array/SmallestNumber.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.datastructures.array; 2 | 3 | public class SmallestNumber { 4 | 5 | static int[] arr = {34, 36, 2, 9, 47, 7, 1}; 6 | static int smallest = arr[0]; 7 | 8 | public static void main(String args[]) { 9 | for (int i = 1; i < arr.length; i++) { 10 | if (arr[i] < smallest) { 11 | smallest = arr[i]; 12 | } 13 | } 14 | System.out.println(smallest); 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/datastructures/linkedlist/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.datastructures.linkedlist; 2 | 3 | public class Caller { 4 | 5 | public static void main(String[] args) { 6 | 7 | LinkedList linkedList = new LinkedList<>(); 8 | linkedList.addAtEnd("2"); 9 | linkedList.addAtEnd("4"); 10 | linkedList.addAtEnd("6"); 11 | linkedList.addAtEnd("7"); 12 | 13 | //delete by value from linkedlist 14 | linkedList.deleteByValue("4"); 15 | 16 | //print all elements of the linkedlist 17 | System.out.println("All Elements of LinkedList"); 18 | linkedList.printAll(); 19 | 20 | //print from middle to last 21 | System.out.println("Middle to Last of LinkedList"); 22 | linkedList.midToLast(); 23 | 24 | //reverse the linkedlist 25 | linkedList.reverse(); 26 | System.out.println("LinkedList Reversed"); 27 | 28 | //prints the size of the linkedlist 29 | System.out.println("Size of the List : " + linkedList.size()); 30 | 31 | //prints the size of the linkedlist using recursion 32 | System.out.println("Size of the List using Recursion : " + linkedList.recursiveSize()); 33 | 34 | //insert at end of the linkedlist 35 | linkedList.addAtEnd("15"); 36 | linkedList.addAtEnd("9"); 37 | linkedList.addAtEnd("23"); 38 | linkedList.addAtEnd("2"); 39 | 40 | //create and detect a loop in the linkedlist 41 | //linkedList.createLoop(); 42 | System.out.println("Does LinkedList has Loop : " + linkedList.detectLoop()); 43 | 44 | LinkedList linkedListTwo = new LinkedList<>(); 45 | linkedListTwo.addAtEnd("2"); 46 | linkedListTwo.addAtEnd("4"); 47 | linkedListTwo.addAtEnd("6"); 48 | linkedListTwo.addAtEnd("7"); 49 | linkedListTwo.addAtEnd("33"); 50 | 51 | LinkedList linkedListThree = new LinkedList<>(); 52 | linkedListThree.addAtEnd("91"); 53 | linkedListThree.addAtEnd("88"); 54 | linkedListThree.addAtEnd("53"); 55 | 56 | createIntersection(linkedListTwo.headNode, linkedListThree.headNode); 57 | linkedListThree.printAll(); 58 | 59 | if (findIntersection(linkedListTwo.headNode, linkedListThree.headNode) != null) { 60 | System.out.println("Intersection "+findIntersection(linkedListTwo.headNode, linkedListThree.headNode).data); 61 | } 62 | } 63 | 64 | /** 65 | * method which accepts headNode of Two LinkedList and creates intersection 66 | * The 3rd Node points to the Second Node of the 2nd Node of First LinkedList as headNode 67 | * 68 | * @param headNodeOne 69 | * @param headNodeTwo 70 | */ 71 | public static void createIntersection(LinkedList.Node headNodeOne, LinkedList.Node headNodeTwo) { 72 | headNodeTwo.nextNode.nextNode.nextNode = headNodeOne.nextNode.nextNode; 73 | } 74 | 75 | /** 76 | * Method which finds the intersection of the two node. 77 | * Video Explanation : https://www.youtube.com/watch?v=IpBfg9d4dmQ 78 | * 79 | * @param headNodeOne 80 | * @param headNodeTwo 81 | */ 82 | public static LinkedList.Node findIntersection(LinkedList.Node headNodeOne, LinkedList.Node headNodeTwo) { 83 | LinkedList.Node pointerA = headNodeOne; 84 | LinkedList.Node pointerB = headNodeTwo; 85 | 86 | // If one of the head is null 87 | if (pointerA == null || pointerB == null) 88 | return null; 89 | 90 | // Continue until we find intersection node 91 | while ( pointerA != pointerB) { 92 | 93 | // If A pointer reaches to null, assign headNode of LinkedListTwo 94 | if (pointerA == null) 95 | pointerA = headNodeTwo; 96 | else { 97 | pointerA = pointerA.nextNode; 98 | } 99 | 100 | // If B pointer reaches to null, assign headNode of LinkedListOne 101 | if (pointerB == null) 102 | pointerB = headNodeOne; 103 | else { 104 | pointerB = pointerB.nextNode; 105 | } 106 | } 107 | 108 | return pointerA; 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/datastructures/linkedlist/LinkedList.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.datastructures.linkedlist; 2 | 3 | /** 4 | * A linked list is formed by nodes that are linked together like a chain. 5 | * Each node holds data, along with a pointer to the next node in the list. 6 | * The Singly Linked List is type of LL where each node has only one pointer that stores reference to the next value. 7 | */ 8 | public class LinkedList { 9 | 10 | // size should be public, as it needs to accessed easily 11 | public int size; 12 | // headNode is the node which points to all other node 13 | public Node headNode; 14 | 15 | public LinkedList() { 16 | size = 0; 17 | headNode = null; 18 | } 19 | 20 | /** 21 | * @return true or false 22 | * Checks if the LinkedList is empty. 23 | */ 24 | public boolean isEmpty() { 25 | if (headNode == null) { 26 | return true; 27 | } 28 | return false; 29 | } 30 | 31 | /** 32 | * Add a Node at the head. 33 | */ 34 | public void addAtHead(T data) { 35 | //Create a tempNode, tempNode.data will refer to passed data 36 | Node tempNode = new Node(); 37 | tempNode.data = data; 38 | 39 | //tempNode.nextNode will point to headNode 40 | tempNode.nextNode = headNode; 41 | 42 | //re-assign the headNode to tempNode 43 | headNode = tempNode; 44 | 45 | //increment the size to 1 46 | size++; 47 | } 48 | 49 | /** 50 | * Add elements at the end of the LinkedList 51 | * 52 | * @param data 53 | */ 54 | public void addAtEnd(T data) { 55 | 56 | //If the list is empty add it using addAtHead() 57 | if (isEmpty()) { 58 | addAtHead(data); 59 | return; 60 | } 61 | 62 | //Create a temp node 63 | Node tempNode = new Node(); 64 | tempNode.data = data; 65 | tempNode.nextNode = null; 66 | 67 | //Let the last node reference to headNode 68 | Node lastNode = headNode; 69 | 70 | while (lastNode.nextNode != null) { 71 | lastNode = lastNode.nextNode; 72 | } 73 | 74 | lastNode.nextNode = tempNode; 75 | size++; 76 | } 77 | 78 | /** 79 | * print all the element of the linkedList. 80 | */ 81 | public void printAll() { 82 | while (isEmpty()) { 83 | System.out.println("List is empty"); 84 | return; 85 | } 86 | 87 | Node tempNode = headNode; 88 | while (tempNode != null) { // tempNode becomes null, will not enter in the loop. 89 | System.out.println(tempNode.data); 90 | tempNode = tempNode.nextNode; 91 | } 92 | } 93 | 94 | /** 95 | * Returns the size of the LinkedList using recursive approach. 96 | * 97 | * @return size of the linkedlist 98 | */ 99 | public int recursiveSize() { 100 | int counter =0; 101 | if (headNode == null) { 102 | return 0; 103 | } else { 104 | counter = 1 + lengthOfList(headNode.nextNode); 105 | return counter; 106 | } 107 | } 108 | 109 | /** 110 | * Searches if a given data exists in the LinkedList. 111 | * returns true if yes or false if it does not. 112 | * 113 | * @param data 114 | * @return 115 | */ 116 | public boolean searchNode(T data) { 117 | Node tempNode = headNode; 118 | while (tempNode != null) { 119 | if (tempNode.data.equals(data)) { 120 | return true; 121 | } 122 | tempNode = tempNode.nextNode; 123 | } 124 | return false; 125 | } 126 | 127 | /** 128 | * @param data 129 | * @param previous 130 | */ 131 | public void insertAfter(T data, T previous) { 132 | 133 | Node addUpNode = new Node(); 134 | addUpNode.data = data; 135 | 136 | Node searchedNode = headNode; 137 | while (searchedNode != null) { 138 | if (searchedNode.data.equals(previous)) { 139 | addUpNode.nextNode = searchedNode.nextNode; 140 | searchedNode.nextNode = addUpNode; 141 | size++; 142 | return; 143 | } 144 | searchedNode = searchedNode.nextNode; 145 | } 146 | } 147 | 148 | /** 149 | * Returns the size of the LinkedList. 150 | * 151 | * @return 152 | */ 153 | public int size() { 154 | return size; 155 | } 156 | 157 | private void deleteAtHead() { 158 | if (isEmpty()) { 159 | return; 160 | } 161 | headNode = headNode.nextNode; 162 | size--; 163 | } 164 | 165 | /** 166 | * Deletes a node by value 167 | * 168 | * @param data 169 | */ 170 | public void deleteByValue(T data) { 171 | 172 | if (isEmpty()) { 173 | return; 174 | } 175 | Node tempNode = headNode; 176 | Node prev = null; 177 | 178 | if (tempNode.data.equals(data)) { 179 | deleteAtHead(); 180 | return; 181 | } 182 | 183 | while (tempNode != null) { 184 | if (tempNode.data.equals(data)) { 185 | prev.nextNode = tempNode.nextNode; 186 | size--; 187 | } 188 | //used to save the previous pointer, and then go to the another pointer. 189 | prev = tempNode; 190 | tempNode = tempNode.nextNode; 191 | } 192 | } 193 | 194 | /** 195 | * This will reverse the LinkedList 196 | */ 197 | public void reverse() { 198 | 199 | //previous node, to keep track of the previous node, to set the pointer to previous node 200 | Node previous = null; 201 | //currentNode be the headNode 202 | Node current = headNode; 203 | //to save the state of the next node, as we assign the value of current.nextNode to previous node. 204 | Node next = null; 205 | 206 | while (current != null) { 207 | //save the upcoming node's address to next 208 | next = current.nextNode; 209 | //make the current node point to previous node, initially it would point to null, and gradually it will move one step ahead 210 | current.nextNode = previous; 211 | //make a move of the previous node to the current node. 212 | previous = current; 213 | //let the current node be, now to the nextNode of the current Node. 214 | current = next; 215 | } 216 | //after we have done all the traversing, set the headNode as the previous node. 217 | headNode = previous; 218 | 219 | } 220 | 221 | /** 222 | * Creates a loop in the LinkedList. 223 | */ 224 | public void createLoop() { 225 | Node tempNode = headNode; 226 | while (tempNode.nextNode != null) { 227 | tempNode = tempNode.nextNode; 228 | } 229 | tempNode.nextNode = headNode; 230 | } 231 | 232 | /** 233 | * detect a loop in the LinkedList. 234 | */ 235 | public boolean detectLoop() { 236 | Node slow = headNode; 237 | Node fast = headNode; 238 | 239 | while (slow != null && fast != null && fast.nextNode != null) { 240 | slow = slow.nextNode; 241 | fast = fast.nextNode.nextNode; 242 | if (slow == fast) { 243 | return true; 244 | } 245 | } 246 | return false; 247 | } 248 | 249 | /** 250 | * Method which can find the middle of the element. 251 | * 252 | * @param 253 | * @return 254 | */ 255 | public Object midElement() { 256 | Node slow = headNode; 257 | Node fast = headNode; 258 | 259 | while (slow != null && fast != null && fast.nextNode != null) { 260 | slow = slow.nextNode; 261 | fast = fast.nextNode.nextNode; 262 | } 263 | return slow.data; 264 | } 265 | 266 | /* Returns count of nodes in linked list */ 267 | public int lengthOfList(Node headNode) { 268 | // Base case 269 | if (headNode == null) { 270 | return 0; 271 | } 272 | // Recursive case 273 | else { 274 | return 1 + lengthOfList(headNode.nextNode); 275 | } 276 | } 277 | 278 | /** 279 | * Method which prints data from middle to last. 280 | * 281 | * @param 282 | * @return 283 | */ 284 | public void midToLast() { 285 | Node lastNode = headNode; 286 | Node midNode = headNode; 287 | 288 | if (headNode != null) { 289 | while (lastNode != null && lastNode.nextNode != null) { 290 | lastNode = lastNode.nextNode.nextNode; 291 | midNode = midNode.nextNode; 292 | } 293 | } 294 | 295 | while (midNode.nextNode != null) { 296 | System.out.println(midNode.data); 297 | midNode = midNode.nextNode; 298 | } 299 | System.out.println(midNode.data); 300 | } 301 | 302 | /** 303 | * @param All the class and attribute should be public. 304 | */ 305 | public class Node { 306 | public T data; 307 | public Node nextNode; 308 | } 309 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/datastructures/queue/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.datastructures.queue; 2 | 3 | public class Caller { 4 | public static void main(String[] args) { 5 | Queue queue = new Queue(3); 6 | queue.enqueue("Football"); 7 | queue.enqueue("Cricket"); 8 | queue.dequeue(); 9 | queue.dequeue(); 10 | queue.enqueue("Tennis"); 11 | queue.dequeue(); 12 | queue.enqueue("Rugby"); 13 | queue.dequeue(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/datastructures/queue/PrintNBinaryNumber.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.datastructures.queue; 2 | 3 | public class PrintNBinaryNumber { 4 | public static void main(String[] args) { 5 | 6 | int number = 6; 7 | String[] result = new String[number]; 8 | 9 | /** 10 | * We Choose, capacity = number+1, because we will enqueue all new element in loop 11 | * Also, we will enqueue as starting element 12 | */ 13 | Queue queue = new Queue(number + 1); 14 | 15 | queue.enqueue(1); 16 | 17 | for (int i = 0; i < number; i++) { 18 | 19 | // dequeue element from queue , append 0 and 1 and add it to array. 20 | result[i] = String.valueOf(queue.dequeue()); 21 | 22 | String s1 = result[i] + "0"; 23 | String s2 = result[i] + "1"; 24 | queue.enqueue(Integer.parseInt(s1)); 25 | queue.enqueue(Integer.parseInt(s2)); 26 | } 27 | 28 | for (int i = 0; i < result.length; i++) { 29 | System.out.print(result[i] + " "); 30 | } 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/datastructures/queue/Queue.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.datastructures.queue; 2 | 3 | /** 4 | * Queue is another linear data structure that stores the elements in a sequential manner. 5 | * Main between Stack and Queue is that instead of using the LIFO principle, 6 | * Queue implements the FIFO method, which is short for First in First Out. 7 | * 8 | * @param 9 | */ 10 | public class Queue { 11 | T array[]; 12 | int maxSize; 13 | int front; 14 | int back; 15 | int currentSize; 16 | 17 | Queue(int capacity) { 18 | array = (T[]) new Object[capacity]; 19 | maxSize = capacity; 20 | front = 0; 21 | back = -1; 22 | currentSize = 0; 23 | } 24 | 25 | public boolean isEmpty() { 26 | return currentSize == 0; 27 | } 28 | 29 | public int getCurrentSize() { 30 | return currentSize; 31 | } 32 | 33 | public boolean isFull() { 34 | return currentSize == maxSize; 35 | } 36 | 37 | public void enqueue(T value) { 38 | if (isFull()) { 39 | System.out.println("Queue Full"); 40 | return; 41 | } 42 | // Using the MOD operator, resets the position to 0, When there is room to enqueue 43 | back = (back + 1) % maxSize; 44 | array[back] = value; 45 | currentSize++; 46 | } 47 | 48 | public T dequeue() { 49 | if (isEmpty()) { 50 | System.out.println("Queue is Empty"); 51 | return null; 52 | } 53 | T value = array[front]; 54 | 55 | // Using the MOD operator, resets the position to 0, When there is room to dequeue 56 | front = (front + 1) % maxSize; 57 | currentSize--; 58 | return value; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/datastructures/stack/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.datastructures.stack; 2 | 3 | public class Caller { 4 | 5 | public static void main(String[] args) { 6 | Stack stack = new Stack(5); 7 | System.out.println(stack.isEmpty()); 8 | System.out.println(stack.isFull()); 9 | 10 | stack.push("Stack"); 11 | stack.push("Queue"); 12 | 13 | System.out.println(stack.pop()); 14 | System.out.println(stack.pop()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/datastructures/stack/Stack.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.datastructures.stack; 2 | 3 | /** 4 | * Stack is a container, in which we can add items and remove them. 5 | * Only the top of this container is open, so the item we put in first will be taken out last, 6 | * The items we put in last will be taken out first. This is called the last in first out (LIFO) ordering. 7 | * 8 | * @param 9 | */ 10 | public class Stack { 11 | int top; 12 | int maxSize; 13 | T arr[]; 14 | 15 | public Stack(int capacity) { 16 | maxSize = capacity; 17 | top = -1; 18 | arr = (T[]) new Object[maxSize]; 19 | } 20 | 21 | public int getCapacity() { 22 | return maxSize; 23 | } 24 | 25 | public boolean isEmpty() { 26 | return top == -1; 27 | } 28 | 29 | public boolean isFull() { 30 | if (top == maxSize) { 31 | return true; 32 | } 33 | return false; 34 | } 35 | 36 | public T getTop() { 37 | if (isEmpty()) { 38 | return null; 39 | } 40 | return arr[top]; 41 | } 42 | 43 | public void push(T value){ 44 | if(isFull()){ 45 | System.out.println("Stack is Full"); 46 | return; 47 | } 48 | // Increment the top index and assign the value. 49 | arr[++top] = value; 50 | } 51 | 52 | public T pop(){ 53 | if(isEmpty()){ 54 | System.out.println("Stack is Empty"); 55 | return null; 56 | } 57 | // return value and index top, and decrement the top index after that 58 | return arr[top--]; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/datastructures/tree/BinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.datastructures.tree; 2 | 3 | /** 4 | * Binary Search Tree - (Ordered Binary Tree) 5 | * BST - is a variant of Binary Tree with a strict condition based on node value. 6 | * Left Child will always have lesser value than the node, while right has greater value. 7 | */ 8 | public class BinarySearchTree { 9 | 10 | private Node root; 11 | 12 | public Node getRoot() { 13 | return root; 14 | } 15 | 16 | public void setRoot(Node root) { 17 | this.root = root; 18 | } 19 | 20 | /** 21 | * Iterative Function to insert a value in BST 22 | */ 23 | public boolean add(int value) { 24 | 25 | //If Tree is empty then insert Root with the given value inside Tree 26 | if (isEmpty()) { 27 | root = new Node(value); 28 | return true; 29 | } 30 | //Starting from root 31 | Node currentNode = root; 32 | 33 | //Traversing the tree until valid position to insert the value 34 | while (currentNode != null) { 35 | 36 | Node leftChild = currentNode.getLeftChild(); 37 | Node rightChild = currentNode.getRightChild(); 38 | 39 | //If the value to insert is less than root value then move to left subtree 40 | //else move to right subtree of root 41 | //and before moving check if the subtree is null, if it's then insert the value. 42 | if (currentNode.getData() > value) { 43 | if (leftChild == null) { 44 | leftChild = new Node(value); 45 | currentNode.setLeftChild(leftChild); 46 | return true; 47 | } 48 | currentNode = leftChild; 49 | } else { 50 | if (rightChild == null) { 51 | rightChild = new Node(value); 52 | currentNode.setRightChild(rightChild); 53 | return true; 54 | } 55 | currentNode = rightChild; 56 | } 57 | } 58 | return false; 59 | } 60 | 61 | //Function to check if Tree is empty or not 62 | public boolean isEmpty() { 63 | return root == null; 64 | } 65 | 66 | public void printTree(Node current) { 67 | if (current == null) return; 68 | System.out.println(current.getData()); 69 | printTree(current.getLeftChild()); 70 | printTree(current.getRightChild()); 71 | 72 | } 73 | 74 | /** 75 | * Searches a Node in the Tree, returns true if present or false if not present 76 | * @param value 77 | * @return 78 | */ 79 | public boolean booleanSearch(int value) { 80 | 81 | if (isEmpty()) { 82 | return false; 83 | } 84 | Node current = root; 85 | 86 | while (current != null) { 87 | 88 | if (current.getData() == value) { 89 | return true; 90 | } 91 | if (current.getData() > value) { 92 | current = current.getLeftChild(); 93 | } else { 94 | current = current.getRightChild(); 95 | } 96 | } 97 | return false; 98 | } 99 | 100 | /** 101 | * Searches a value in the Tree 102 | * @param value 103 | * @return 104 | */ 105 | public Node nodeSearch(int value) { 106 | 107 | if (isEmpty()) return null; // if tree is empty simply return null 108 | 109 | Node currentNode = this.root; 110 | 111 | while (currentNode != null) { 112 | 113 | if (currentNode.getData() == value) return currentNode; // compare data from current node 114 | 115 | if (currentNode.getData() > value) //if data from current node is greater than value 116 | currentNode = currentNode.getLeftChild(); // then move towards left subtree 117 | else 118 | currentNode = currentNode.getRightChild(); //else move towards right subtree 119 | } 120 | 121 | System.out.println(value + " Not found in the Tree!"); 122 | return null; 123 | } 124 | 125 | public boolean insert(Node node, int value){ 126 | 127 | if(node == null){ 128 | node = new Node(value); 129 | } 130 | 131 | Node current = node; 132 | 133 | if(current.getData()>value){ 134 | insert(current.getLeftChild(),value); 135 | } 136 | else { 137 | insert(current.getRightChild(),value); 138 | } 139 | return false; 140 | } 141 | 142 | public Node recursiveInsert(Node node, int value){ 143 | 144 | if(node == null){ 145 | return new Node(value); 146 | } 147 | 148 | if(node.getData() > value){ 149 | node.setLeftChild(recursiveInsert(node.getLeftChild(), value)); 150 | } 151 | else if(node.getData() < value){ 152 | node.setRightChild(recursiveInsert(node.getRightChild(), value)); 153 | } 154 | else { 155 | return node; 156 | } 157 | 158 | return node; 159 | } 160 | 161 | /** 162 | * 163 | * @param root 164 | * @return 165 | * Find Height of a Binary Search Tree 166 | * 167 | * Find Height of left subtree right subtree 168 | * Return greater height value of left or right subtree (plus 1) 169 | */ 170 | public int findHeight(Node root) { 171 | //Base case, leaf nodes have 0 height 172 | if (root == null) return -1; 173 | else { 174 | return 1 + Math.max(findHeight(root.getLeftChild()),findHeight(root.getRightChild())); 175 | } 176 | } 177 | 178 | /** 179 | * 3 conditions for delete 180 | * 1. Node is Leaf Node. 181 | * 2. Node has 1 Child. 182 | * 3. Node has 2 Children. 183 | **/ 184 | boolean delete(int value, Node currentNode) { 185 | 186 | // If there are no elements in the tree, return false 187 | if (root == null) { 188 | return false; 189 | } 190 | 191 | // Create a Node Parent, which hold the Previous/Parent Node of Current 192 | Node parent = null; 193 | 194 | // Traverse until Tree fully traversed or We find the Correct Node 195 | while(currentNode != null && (currentNode.getData() != value)) { 196 | parent = currentNode; 197 | if (currentNode.getData() > value) 198 | currentNode = currentNode.getLeftChild(); 199 | else 200 | currentNode = currentNode.getRightChild(); 201 | } 202 | 203 | // If the traversal is complete, and there was no node with the value, return false. 204 | if(currentNode == null) { 205 | return false; 206 | } 207 | 208 | // Suppose, we got the matching data, and it appears to be a leaf node. 209 | else if(currentNode.getLeftChild() == null && currentNode.getRightChild() == null) { 210 | //1. Node is Leaf Node 211 | 212 | //if that leaf node is the root (a tree with just root) 213 | if(root.getData() == currentNode.getData()){ 214 | setRoot(null); 215 | return true; 216 | } 217 | else if(currentNode.getData() < parent.getData()){ 218 | parent.setLeftChild(null); 219 | return true; 220 | } 221 | else{ 222 | parent.setRightChild(null); 223 | return true; 224 | } 225 | } 226 | 227 | // 2. Node has 1 Child 228 | else if(currentNode.getRightChild() == null) { 229 | 230 | if(root.getData() == currentNode.getData()){ 231 | setRoot(currentNode.getLeftChild()); 232 | return true; 233 | } 234 | else if(currentNode.getData() < parent.getData()){ 235 | parent.setLeftChild(currentNode.getLeftChild()); 236 | return true; 237 | } 238 | else{ 239 | parent.setRightChild(currentNode.getLeftChild()); 240 | return true; 241 | } 242 | } 243 | 244 | else if(currentNode.getLeftChild() == null) { 245 | 246 | if(root.getData() == currentNode.getData()){ 247 | setRoot(currentNode.getRightChild()); 248 | return true; 249 | } 250 | else if(currentNode.getData() < parent.getData()){ 251 | parent.setLeftChild(currentNode.getRightChild()); 252 | return true; 253 | } 254 | else{ 255 | parent.setRightChild(currentNode.getRightChild()); 256 | return true; 257 | } 258 | 259 | } 260 | 261 | // 3. Node has 2 Children. 262 | else { 263 | //Find Least Value Node in right-subtree of current Node 264 | Node leastNode = findLeastNode(currentNode.getRightChild()); 265 | //Set CurrentNode's Data to the least value in its right-subtree 266 | int temp = leastNode.getData(); 267 | delete(temp, root); 268 | currentNode.setData(temp); 269 | //Delete the leafNode which had the least value 270 | return true; 271 | } 272 | 273 | } 274 | 275 | //Helper function to find least value node in right-subtree of currentNode 276 | private Node findLeastNode(Node currentNode) { 277 | Node temp = currentNode; 278 | 279 | while (temp.getLeftChild() != null) { 280 | temp = temp.getLeftChild(); 281 | } 282 | return temp; 283 | } 284 | } 285 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/datastructures/tree/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.datastructures.tree; 2 | 3 | public class Caller { 4 | 5 | public static void main(String[] args) { 6 | BinarySearchTree binarySearchTree = new BinarySearchTree(); 7 | 8 | binarySearchTree.add(6); 9 | binarySearchTree.add(4); 10 | binarySearchTree.add(9); 11 | binarySearchTree.add(5); 12 | binarySearchTree.add(2); 13 | binarySearchTree.add(8); 14 | binarySearchTree.add(12); 15 | binarySearchTree.add(10); 16 | binarySearchTree.add(14); 17 | 18 | // recursive 19 | binarySearchTree.recursiveInsert(binarySearchTree.getRoot(),95); 20 | binarySearchTree.recursiveInsert(binarySearchTree.getRoot(),47); 21 | binarySearchTree.recursiveInsert(binarySearchTree.getRoot(),99); 22 | binarySearchTree.recursiveInsert(binarySearchTree.getRoot(),35); 23 | binarySearchTree.recursiveInsert(binarySearchTree.getRoot(),202); 24 | binarySearchTree.recursiveInsert(binarySearchTree.getRoot(),132); 25 | 26 | 27 | System.out.println(binarySearchTree.nodeSearch(108)); 28 | System.out.println(binarySearchTree.nodeSearch(12)); 29 | 30 | binarySearchTree.printTree(binarySearchTree.getRoot()); 31 | } 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/datastructures/tree/Node.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.datastructures.tree; 2 | 3 | public class Node { 4 | //Variables 5 | private int data; 6 | private Node leftChild; 7 | private Node rightChild; 8 | 9 | //Constructor 10 | Node(int value) { 11 | this.data = value; 12 | leftChild = null; 13 | rightChild = null; 14 | } 15 | 16 | //Getter-Setter 17 | public Node getLeftChild() { 18 | return leftChild; 19 | } 20 | 21 | public Node getRightChild() { 22 | return rightChild; 23 | } 24 | 25 | public int getData() { 26 | return data; 27 | } 28 | 29 | public void setData(int value) { 30 | this.data = value; 31 | } 32 | 33 | public void setLeftChild(Node left) { 34 | this.leftChild = left; 35 | } 36 | 37 | public void setRightChild(Node right) { 38 | this.rightChild = right; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/designpatterns/builder/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.designpatterns.builder; 2 | 3 | public class Caller { 4 | 5 | public static void main(String[] args) { 6 | Person person = new Person.PersonBuilder(1, "Amar") 7 | .setPhone(910860000) 8 | .setAddress("BLR") 9 | .build(); 10 | System.out.println(person.getName()); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/designpatterns/builder/PersonBuilder.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.designpatterns.builder; 2 | 3 | class Person { 4 | 5 | private int id; 6 | private String name; 7 | 8 | private int phone; 9 | private String address; 10 | 11 | // The constructor is private and can only be called by the Builder Class 12 | private Person(PersonBuilder builder) { 13 | this.id = builder.id; 14 | this.name = builder.name; 15 | } 16 | 17 | public int getId() { 18 | return id; 19 | } 20 | 21 | public String getName() { 22 | return name; 23 | } 24 | 25 | public int getPhone() { 26 | return phone; 27 | } 28 | 29 | public String getAddress() { 30 | return address; 31 | } 32 | 33 | //Builder Class 34 | public static class PersonBuilder { 35 | private int id; 36 | private String name; 37 | 38 | private int phone; 39 | private String address; 40 | 41 | public PersonBuilder(int id, String name) { 42 | this.id = id; 43 | this.name = name; 44 | } 45 | 46 | public PersonBuilder setPhone(int phone) { 47 | this.phone = phone; 48 | return this; 49 | } 50 | 51 | public PersonBuilder setAddress(String address) { 52 | this.address = address; 53 | return this; 54 | } 55 | 56 | public Person build() { 57 | return new Person(this); 58 | } 59 | 60 | } 61 | 62 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/designpatterns/factory/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.designpatterns.factory; 2 | 3 | public class Caller { 4 | public static void main(String[] args) { 5 | /** 6 | * Create a new Instance of CarFactory, and pass the type of the object you want. 7 | * The instance would return an object type of implemented =type. 8 | */ 9 | CarFactory carFactory = new CarFactory(); 10 | 11 | /** 12 | * getInstance() is a public method, which returns an object of Car Type 13 | */ 14 | Car car = carFactory.getInstance("heavy"); 15 | 16 | /** 17 | * type() is a method in the interface, which is implemented in Class of Car Type 18 | */ 19 | car.type(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/designpatterns/factory/Car.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.designpatterns.factory; 2 | 3 | public interface Car { 4 | void type(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/designpatterns/factory/CarFactory.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.designpatterns.factory; 2 | 3 | /** 4 | * Car Factory which returns an instance of respective carType using the string value of getInstance method 5 | */ 6 | public class CarFactory { 7 | 8 | /** 9 | * the getInstance() is a public method returns a new object of car type. 10 | * @param carType 11 | * @return an object car Type 12 | */ 13 | public Car getInstance(String carType) { 14 | if (carType.equalsIgnoreCase("Small")) { 15 | return new HatchBack(); 16 | 17 | } else if (carType.equalsIgnoreCase("Big")) { 18 | return new Sedan(); 19 | 20 | } else if (carType.equalsIgnoreCase("Heavy")) { 21 | return new SUV(); 22 | 23 | } else 24 | return null; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/designpatterns/factory/HatchBack.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.designpatterns.factory; 2 | 3 | public class HatchBack implements Car { 4 | @Override 5 | public void type() { 6 | System.out.println("Car Type : HatchBack"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/designpatterns/factory/SUV.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.designpatterns.factory; 2 | 3 | public class SUV implements Car { 4 | @Override 5 | public void type() { 6 | System.out.println("Car Type : SUV"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/designpatterns/factory/Sedan.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.designpatterns.factory; 2 | 3 | public class Sedan implements Car { 4 | @Override 5 | public void type() { 6 | System.out.println("Car Type : Sedan Class"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/designpatterns/singleton/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.designpatterns.singleton; 2 | 3 | public class Caller { 4 | public static void main(String[] args) throws InterruptedException { 5 | //calling the getInstance() of Singleton class returns the same heap object. 6 | System.out.println(Singleton.getInstance()); 7 | System.out.println(Singleton.getInstance()); 8 | 9 | //calling the getInstance() of LazySingleton class returns the same heap object. 10 | System.out.println(LazySingleton.getInstance()); 11 | System.out.println(LazySingleton.getInstance()); 12 | 13 | //ThreadSafe Singleton has been called by two threads. 14 | //It results in returning only instance of the thread, because we have used synchronized block. 15 | Thread threadOne = new Thread(new Runnable() { 16 | @Override 17 | public void run() { 18 | System.out.println(ThreadSafeSingleton.getInstance()); 19 | } 20 | }); 21 | Thread threadTwo = new Thread(new Runnable() { 22 | @Override 23 | public void run() { 24 | System.out.println(ThreadSafeSingleton.getInstance()); 25 | } 26 | }); 27 | threadOne.start(); 28 | threadTwo.start(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/designpatterns/singleton/DoubleCheckedSingleton.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.designpatterns.singleton; 2 | 3 | public class DoubleCheckedSingleton { 4 | 5 | private DoubleCheckedSingleton() { 6 | } 7 | 8 | // we create the variable as volatile, as it tells the JVM to follow order of creating an object 9 | private static volatile DoubleCheckedSingleton doubleCheckedSingleton; 10 | 11 | public static DoubleCheckedSingleton getInstance() { 12 | 13 | /** 14 | * we don't want other thread to wait in multi-threaded environment. 15 | * if singleton instance is not null, give the thread object of the singleton, let the thread execute normally. 16 | * but if it's null, make the inner block as synchronized as two parallel threads don't create 2 different object. 17 | * check if the object is null and assign the reference a object in heap. 18 | */ 19 | if (doubleCheckedSingleton == null) { 20 | synchronized (DoubleCheckedSingleton.class) { 21 | if (doubleCheckedSingleton == null) { 22 | doubleCheckedSingleton = new DoubleCheckedSingleton(); 23 | } 24 | } 25 | } 26 | return doubleCheckedSingleton; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/designpatterns/singleton/LazySingleton.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.designpatterns.singleton; 2 | 3 | public class LazySingleton { 4 | 5 | /** 6 | * It just creates the memory reference of the class. 7 | * The object is initialized and allocated heap space when it is required. 8 | */ 9 | private static LazySingleton lazySingleton; 10 | 11 | /** 12 | * we must declare constructor as private to prohibit creating object of it. 13 | */ 14 | private LazySingleton() { 15 | } 16 | 17 | //method to return instance of class 18 | public static LazySingleton getInstance() { 19 | if (lazySingleton == null) { 20 | // if instance is null, initialize 21 | lazySingleton = new LazySingleton(); 22 | } 23 | return lazySingleton; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/designpatterns/singleton/Singleton.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.designpatterns.singleton; 2 | 3 | public class Singleton { 4 | 5 | /** 6 | * Generic Singleton implementation. 7 | * This creates a new Instance of Singleton object, when the JVM is run. 8 | * static and final makes it immutable. 9 | */ 10 | private static final Singleton singleton = new Singleton(); 11 | 12 | /** 13 | * creating constructor as private makes prohibits creating new object of the class. 14 | */ 15 | private Singleton() { 16 | } 17 | 18 | public static Singleton getInstance() { 19 | return singleton; 20 | } 21 | 22 | /** 23 | * prints the object's hex value. 24 | */ 25 | public void show(){ 26 | System.out.println(singleton); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/designpatterns/singleton/ThreadSafeSingleton.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.designpatterns.singleton; 2 | 3 | public class ThreadSafeSingleton { 4 | 5 | /** 6 | * private instance, so that it can be accessed by only by getInstance() method 7 | * 8 | */ 9 | private static ThreadSafeSingleton threadSafeSingleton; 10 | 11 | private ThreadSafeSingleton() { 12 | System.out.println("threadSafeSingleton Initialized"); 13 | } 14 | 15 | /** 16 | * "synchronized" keyword prohibits simultaneous access of the method by threads 17 | */ 18 | synchronized public static ThreadSafeSingleton getInstance() { 19 | if (threadSafeSingleton == null) { 20 | // if instance is null, initialize 21 | threadSafeSingleton = new ThreadSafeSingleton(); 22 | } 23 | return threadSafeSingleton; 24 | } 25 | 26 | public void show(){ 27 | System.out.println(threadSafeSingleton); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/exceptions/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.exceptions; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Caller { 6 | public static void main(String[] args) { 7 | int value; 8 | Scanner scanner = new Scanner(System.in); 9 | System.out.println("Enter Number"); 10 | value = Integer.parseInt(scanner.nextLine()); 11 | if (value % 2 == 0) { 12 | System.out.println("Even Number"); 13 | } else { 14 | throw new OddNumberException("Odd Number Passed"); 15 | } 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/exceptions/OddNumberException.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.exceptions; 2 | 3 | public class OddNumberException extends RuntimeException { 4 | 5 | OddNumberException(String message){ 6 | super(message); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/garbagecollection/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.garbagecollection; 2 | 3 | import java.io.IOException; 4 | 5 | public class Caller { 6 | public static void main(String[] args) throws IOException { 7 | 8 | /** 9 | * Runtime is a Singleton class, where instance of runtime is instantiated as a new JVM is created. 10 | * calling the getRuntime() method would return a static instance of runtime. 11 | */ 12 | Runtime runtime = Runtime.getRuntime(); 13 | 14 | System.out.println(runtime.availableProcessors()); 15 | for(int i=0;i<10000;i++){ 16 | new Caller(); 17 | } 18 | /** 19 | *Memory left after creation of 1000 Caller() object. 20 | */ 21 | System.out.println(runtime.freeMemory()); 22 | 23 | /** 24 | * Call the garbage collector using System.gc() 25 | */ 26 | System.gc(); 27 | 28 | /** 29 | * Check the free memory after garbage is collected. 30 | */ 31 | System.out.println(runtime.freeMemory()); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/hive/HelloUDF.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.hive; 2 | 3 | import org.apache.hadoop.hive.ql.exec.UDF; 4 | import org.apache.hadoop.io.Text; 5 | 6 | /** 7 | * The simple API (org.apache.hadoop.hive.ql.exec.UDF) can be used so long as function reads and returns primitive types. 8 | * By this I mean basic Hadoop & Hive writable types - Text, IntWritable, LongWritable, DoubleWritable, etc. 9 | * However, if you plan on writing a UDF that can manipulate embedded data structures, such as Map, List, and Set, 10 | * then you’re stuck using org.apache.hadoop.hive.ql.udf.generic.GenericUDF, which is a little more involved. 11 | */ 12 | class HelloUDF extends UDF { 13 | 14 | /** 15 | * 16 | * @param input 17 | * @return Text 18 | * 19 | * UDF class is @deprecated, Hive Expects us to extend GenericUDF instead. 20 | */ 21 | public Text evaluate(Text input) { 22 | return new Text("Hello " + input.toString()); 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javacollection/CollectionDataStructure.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javacollection; 2 | 3 | import java.util.*; 4 | 5 | public class CollectionDataStructure { 6 | public static void main(String[] args) { 7 | 8 | /** 9 | * List, Queue, Set - implements interface - which implements interface 10 | * List - ArrayList, LinkedList, Vector, Stack 11 | * Queue - PriorityQueue, ArrayDeque implements Deque 12 | * Set - HashSet, LinkedHashSet , TreeSet implements SortedSet 13 | */ 14 | 15 | /** 16 | * Popular Method of Collection Interface 17 | * 18 | * iterator() 19 | * size() 20 | * add() 21 | * remove 22 | * toArray() 23 | * stream() 24 | * 25 | */ 26 | 27 | // List 28 | 29 | //1. LinkedList 30 | System.out.println("\nList - ArrayList \n"); 31 | /** 32 | * ArrayList - 33 | * The ArrayList class implements the List interface. 34 | * It uses a dynamic array to store the duplicate element of different data types. 35 | * The ArrayList class maintains the insertion order and is non-synchronized. 36 | * The elements stored in the ArrayList class can be randomly accessed 37 | */ 38 | ArrayList gameList = new ArrayList();//Creating arrayList 39 | gameList.add("Cricket"); 40 | gameList.add("FootBall"); 41 | gameList.add("Rugby"); 42 | gameList.add("Tennis"); 43 | 44 | Iterator arrayListIterator = gameList.iterator(); 45 | while (arrayListIterator.hasNext()) { 46 | System.out.println(arrayListIterator.next()); 47 | } 48 | 49 | //2. LinkedList 50 | System.out.println("\nList - LinkedList \n"); 51 | /** 52 | * LinkedList - 53 | * LinkedList implements the Collection interface.It uses a doubly linked list internally to store the elements. 54 | * It can store the duplicate elements. It maintains the insertion order and is not synchronized. 55 | * In LinkedList, the manipulation is fast because no shifting is required. 56 | */ 57 | LinkedList linkedList = new LinkedList(); 58 | linkedList.add("Table"); 59 | linkedList.add("Fan"); 60 | linkedList.add("Lamp"); 61 | linkedList.add("Bed"); 62 | 63 | Iterator linkedListIterator = linkedList.iterator(); 64 | while (linkedListIterator.hasNext()) { 65 | System.out.println(linkedListIterator.next()); 66 | } 67 | 68 | //3. Vector 69 | System.out.println("\nList - Vector \n"); 70 | /** 71 | * Vector - 72 | * Vector uses a dynamic array to store the data elements. It is similar to ArrayList. 73 | * However, It is synchronized and contains many methods that are not the part of Collection framework. 74 | */ 75 | Vector vector = new Vector(); 76 | vector.add("Amar"); 77 | vector.add("Sneha"); 78 | vector.add("Shailaja"); 79 | vector.add("Sooraj"); 80 | Iterator vectorIterator = vector.iterator(); 81 | while (vectorIterator.hasNext()) { 82 | System.out.println(vectorIterator.next()); 83 | } 84 | 85 | //4. Stack 86 | System.out.println("\nList - Stack \n"); 87 | /** 88 | * Stack - 89 | * The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. 90 | * The stack contains all of the methods of Vector class. 91 | * It also provides methods e.g push(), peek(), push(object o), which defines its properties. 92 | */ 93 | Stack stack = new Stack(); 94 | stack.push("IQIVIA"); 95 | stack.push("Epsilon"); 96 | stack.push("Cerner"); 97 | stack.push("OpenText"); 98 | stack.pop(); 99 | Iterator stackIterator = stack.iterator(); 100 | while (stackIterator.hasNext()) { 101 | System.out.println(stackIterator.next()); 102 | } 103 | 104 | // QUEUE 105 | 106 | //1. Priority Queue 107 | System.out.println("\nQUEUE - Priority Queue \n"); 108 | /** 109 | * Priority Queue - 110 | * The PriorityQueue class implements the Queue interface. 111 | * It holds the elements or objects which are to be processed by their priorities. 112 | * PriorityQueue doesn't allow null values to be stored in the queue. 113 | */ 114 | PriorityQueue priorityQueue = new PriorityQueue(); 115 | priorityQueue.add("Amar Kumar"); 116 | priorityQueue.add("Sooraj Jain"); 117 | priorityQueue.add("V Sushma"); 118 | priorityQueue.add("Vedanth"); 119 | priorityQueue.add("Richie V"); 120 | priorityQueue.add("Abhishek Singh"); 121 | 122 | /** 123 | * The element() - method of Queue Interface returns the element at the front the container. 124 | * It does not deletes the element in the container. This method returns the head of the queue. 125 | * This method differs from peek() only in that it throws an Exception if this queue is empty 126 | */ 127 | System.out.println("head:" + priorityQueue.element()); 128 | 129 | /** 130 | * The peek() - method of Queue Interface returns the element at the front the container. 131 | * It does not deletes the element in the container. This method returns the head of the queue. 132 | * The method does not throws an exception when the Queue is empty, it returns null instead. 133 | */ 134 | System.out.println("head:" + priorityQueue.peek()); 135 | System.out.println("\nIterating the queue elements:"); 136 | 137 | Iterator queueIterator = priorityQueue.iterator(); 138 | while (queueIterator.hasNext()) { 139 | System.out.println(queueIterator.next()); 140 | } 141 | 142 | /** 143 | * The remove() - method of Queue Interface returns and removes the element at the front the container. 144 | * It deletes the head of the container. The method throws an NoSuchElementException when the Queue is empty. 145 | */ 146 | priorityQueue.remove(); 147 | System.out.println("\nAfter removing one element:"); 148 | Iterator queueIterator1 = priorityQueue.iterator(); 149 | while (queueIterator1.hasNext()) { 150 | System.out.println(queueIterator1.next()); 151 | } 152 | 153 | /** 154 | * The poll() method of Queue Interface returns and removes the element at the front the container. 155 | * It deletes the element in the container. 156 | * The method does not throws an exception when the Queue is empty, it returns null instead. 157 | */ 158 | priorityQueue.poll(); 159 | System.out.println("\nAfter removing one element:"); 160 | Iterator queueIterator2 = priorityQueue.iterator(); 161 | while (queueIterator2.hasNext()) { 162 | System.out.println(queueIterator2.next()); 163 | } 164 | 165 | //2. Array Dequeue implements Deque implements Queue 166 | System.out.println("\nQUEUE - Array Dequeue implements Deque\n"); 167 | /** 168 | * Array Dequeue - 169 | * ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. 170 | * Unlike queue, we can add or delete the elements from both the ends. 171 | * ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.. 172 | */ 173 | Deque deque = new ArrayDeque(); 174 | deque.add("Gautam"); 175 | deque.add("Karan"); 176 | deque.add("Ajay"); 177 | 178 | for (String name : deque) { 179 | System.out.println(name); 180 | } 181 | 182 | // SET 183 | 184 | //1. HashSet 185 | System.out.println("\nSET - HashSet \n"); 186 | 187 | /** HashSet - 188 | * HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. 189 | * Hashing is used to store the elements in the HashSet. It contains unique items. 190 | */ 191 | HashSet hashSet = new HashSet(); 192 | hashSet.add("Amar"); 193 | hashSet.add("Shailaja"); 194 | hashSet.add("Amar"); 195 | hashSet.add("Puja"); 196 | hashSet.add("Sneha"); 197 | hashSet.add("Sooraj"); 198 | hashSet.add("Dixit"); 199 | 200 | Iterator hashSetIterator = hashSet.iterator(); 201 | while (hashSetIterator.hasNext()) { 202 | System.out.println(hashSetIterator.next()); 203 | } 204 | 205 | //2. LinkedHashSet 206 | System.out.println("\nSET - LinkedHashSet \n"); 207 | 208 | /** LinkedHashSet - 209 | * LinkedHashSet class represents the LinkedList implementation of Set Interface. 210 | * It extends the HashSet class and implements Set interface. Like HashSet, It also contains unique elements. 211 | * It maintains the insertion order and permits null elements. 212 | */ 213 | LinkedHashSet linkedHashSet = new LinkedHashSet(); 214 | linkedHashSet.add("Amar"); 215 | linkedHashSet.add("Shailaja"); 216 | linkedHashSet.add("Amar"); 217 | linkedHashSet.add("Puja"); 218 | linkedHashSet.add(null); 219 | linkedHashSet.add("Sneha"); 220 | linkedHashSet.add("Sooraj"); 221 | linkedHashSet.add("Dixit"); 222 | Iterator linkedHashSetIterator = linkedHashSet.iterator(); 223 | while (linkedHashSetIterator.hasNext()) { 224 | System.out.println(linkedHashSetIterator.next()); 225 | } 226 | 227 | //2. TreeSet 228 | System.out.println("\nSET - TreeSet \n"); 229 | 230 | /** TreeSet - 231 | * TreeSet class implements the SortedSet implement Set interface that uses a tree for storage. 232 | * Like HashSet, TreeSet also contains unique elements. 233 | * However, the access and retrieval time of TreeSet is quite fast. 234 | * The elements in TreeSet stored in ascending order. 235 | * 236 | * Sorting 237 | * When we don't provide a Comparator class it follows natural Ordering - 238 | * Which means the Class in the Generic should implement Comparable 239 | * If not, We must provide a Comparator instance when creating a new TreeSet instance 240 | */ 241 | TreeSet treeSet = new TreeSet(); 242 | treeSet.add("Ravi"); 243 | treeSet.add("Vijay"); 244 | treeSet.add("Ravi"); 245 | treeSet.add("Ajay"); 246 | treeSet.add("Sneha"); 247 | treeSet.add("Sooraj"); 248 | treeSet.add("Dixit"); 249 | 250 | Iterator treeSetIterator = treeSet.iterator(); 251 | while (treeSetIterator.hasNext()) { 252 | System.out.println(treeSetIterator.next()); 253 | } 254 | } 255 | } 256 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javacollection/HashMapVsHashTable.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javacollection; 2 | 3 | import java.util.HashMap; 4 | import java.util.Hashtable; 5 | import java.util.Map; 6 | 7 | public class HashMapVsHashTable { 8 | 9 | public static void main(String[] args) { 10 | 11 | // HashMap 12 | System.out.println("HashMap"); 13 | 14 | Map hashMap = new HashMap(); 15 | 16 | hashMap.put(54561,"Amar Kumar"); 17 | hashMap.put(53115,"Shailaja Kumari"); 18 | hashMap.put(51234, "Sneha S"); 19 | hashMap.put(55323,"Dixit"); 20 | 21 | //HashMap Allow only null Key and Multiple NULL values 22 | hashMap.put(null,"Ramesh K"); 23 | hashMap.put(null,"Suresh K"); 24 | 25 | hashMap.put(65433,null); 26 | hashMap.put(77544,null); 27 | 28 | for(Map.Entry entry : hashMap.entrySet()){ 29 | System.out.println("Employee ID : "+entry.getKey()+" | Name : "+entry.getValue()); 30 | } 31 | 32 | // Hashtable 33 | System.out.println("Hashtable"); 34 | 35 | Hashtable hashtable = new Hashtable(); 36 | /** 37 | * It will throw an exception, if we try to add a null key or value to HashTable 38 | * Exception in thread "main" java.lang.NullPointerException 39 | * at java.util.Hashtable.put(Hashtable.java:460) 40 | */ 41 | // hashtable.put(null, Amar); 42 | // hashtable.put(1, null); 43 | 44 | hashtable.put(54561, "Amar"); 45 | hashtable.put(51534017, "Kumar"); 46 | 47 | for(Map.Entry entry : hashtable.entrySet()){ 48 | System.out.println("Employee ID : "+entry.getKey()+" | Name : "+entry.getValue()); 49 | } 50 | 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javacollection/LinkedListAsStack.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javacollection; 2 | 3 | import java.util.LinkedList; 4 | 5 | public class LinkedListAsStack { 6 | public static void main(String[] args) { 7 | 8 | // LinkedList Implements Queue, so it follow FIFO - First In First Out 9 | LinkedList stack = new LinkedList(); 10 | 11 | // Add values to the LinkedList. 12 | stack.add("1"); 13 | stack.add("2"); 14 | 15 | // Add to the first of the LinkedList 16 | stack.addFirst("0"); 17 | 18 | // Returns the first element of the LinkedList 19 | System.out.println(stack.getFirst()); 20 | 21 | // Returns the last element of the LinkedList 22 | System.out.println(stack.getLast()); 23 | 24 | // Add few More Elements 25 | stack.addLast("3"); 26 | stack.addLast("4"); 27 | 28 | System.out.println(stack); // 0, 1, 2, 3, 4 29 | 30 | // pop removes the element from the front of the LinkedList 31 | System.out.println(stack.pop()); 32 | 33 | System.out.println(stack); // 0, 1, 2, 3, 4 34 | 35 | // peek OR peekFirst - Returns the first element of the LinkedList, doesn't delete the element in LinkedList 36 | System.out.println(stack.peek()); // Returns 0 37 | 38 | // poll OR pollFirst - deletes element at the start of the LinkedList 39 | System.out.println(stack.poll()); // Returns 0 and Removes 0 40 | 41 | System.out.println(stack); // 1, 2, 3, 4 42 | 43 | // pollLast - Deletes the elements at the End of the LinkedList 44 | System.out.println(stack.pollLast()); // Removes 4 45 | 46 | System.out.println(stack); // 1, 2, 3 47 | 48 | // offer - Adds elements at last of the stack 49 | stack.offer("4"); 50 | stack.offer("5"); 51 | 52 | System.out.println(stack); // 1, 2, 3, 4, 5 53 | 54 | // peakLast - Returns the last element of the LinkedList, doesn't delete the element in LinkedList 55 | System.out.println(stack.peekLast()); // 5 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javacollection/MapDataStructure.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javacollection; 2 | 3 | import java.util.HashMap; 4 | import java.util.LinkedHashMap; 5 | import java.util.Map; 6 | import java.util.TreeMap; 7 | 8 | public class MapDataStructure { 9 | public static void main(String[] args) { 10 | 11 | /** 12 | * MAP - 13 | * A map contains values on the basis of key, i.e. key and value pair. 14 | * Each key and value pair is known as an entry. 15 | * A Map contains UNIQUE keys. (HashMap and LinkedHashMap allow null keys and values) 16 | * A Map is useful if you have to search, update or delete elements on the basis of a key. 17 | * A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method. 18 | * entrySet() - method is used to store all the pair as the set of 's 19 | * entrySet() returns Set 20 | * 21 | */ 22 | 23 | 24 | /** 25 | * 1. HashMap - HashMap is the implementation of Map, but it doesn't maintain any order. 26 | * 2. LinkedHashMap - LinkedHashMap is implementation of Map which inherits HashMap class. It maintains insertion order. 27 | * 3. TreeMap - TreeMap is the implementation of Map and SortedMap. It maintains ascending order. 28 | */ 29 | 30 | // 1. HashMap 31 | 32 | System.out.println("\nHashMap - No insertion order maintained.\n"); 33 | /** 34 | * HashMap - It doesn't maintain insertion Order 35 | */ 36 | Map hashMap=new HashMap(); 37 | hashMap.put(54561,"Amar Kumar"); 38 | hashMap.put(53115,"Shailaja Kumari"); 39 | hashMap.put(51234,"Sneha S"); 40 | hashMap.put(55323,"Dixit"); 41 | 42 | for(Map.Entry entry : hashMap.entrySet()){ 43 | System.out.println("Employee ID : "+entry.getKey()+" | Name : "+entry.getValue()); 44 | } 45 | 46 | // 2. LinkedHashMap 47 | 48 | System.out.println("\nLinkedHashMap - Insertion Order retained.\n"); 49 | /** 50 | * LinkedHashMap - LinkedHashMap is implementation of Map which inherits HashMap class. 51 | * It maintains insertion order. 52 | */ 53 | Map linkedHashMap=new LinkedHashMap<>(); 54 | linkedHashMap.put(54561,"Amar Kumar"); 55 | linkedHashMap.put(53115,"Shailaja Kumari"); 56 | linkedHashMap.put(51234, "Sneha S"); 57 | linkedHashMap.put(55323,"Dixit"); 58 | 59 | for(Map.Entry entry : linkedHashMap.entrySet()){ 60 | System.out.println("Employee ID : "+entry.getKey()+" | Name : "+entry.getValue()); 61 | } 62 | 63 | // 3. TreeMap 64 | 65 | System.out.println("\nTreeMap - Ascending Order based on the key.\n"); 66 | /** 67 | * TreeMap - TreeMap is the implementation of Map and SortedMap. It maintains ascending order. 68 | */ 69 | Map treeMap=new TreeMap(); 70 | treeMap.put(54561,"Amar Kumar"); 71 | treeMap.put(53115,"Shailaja Kumari"); 72 | treeMap.put(51234,"Sneha S"); 73 | treeMap.put(55323,"Dixit"); 74 | for(Map.Entry entry : treeMap.entrySet()){ 75 | System.out.println("Employee ID : "+entry.getKey()+" | Name : "+entry.getValue()); 76 | } 77 | 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javacollection/StackInDS.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javacollection; 2 | 3 | import java.util.Stack; 4 | 5 | public class StackInDS { 6 | 7 | public static void main(String[] args) { 8 | 9 | // Stack works on LIFO - Last In First Out 10 | Stack stack = new Stack<>(); 11 | 12 | // push - is used to add elements to the stack 13 | stack.push("1"); 14 | stack.push("2"); 15 | 16 | System.out.println(stack); 17 | 18 | // peek - It returns the last elements of the stack. This does not delete the element in the stack 19 | System.out.println(stack.peek()); 20 | 21 | // pop - It returns the last elements of the stack. This also deletes the element in the stack 22 | System.out.println(stack.pop()); 23 | 24 | System.out.println(stack); 25 | 26 | // Remove the last left elements 27 | stack.pop(); 28 | 29 | // Returns True if stack is Empty 30 | System.out.println(stack.isEmpty()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javacollection/comparable/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javacollection.comparable; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | public class Caller { 8 | public static void main(String[] args) { 9 | List employees = new ArrayList<>(); 10 | Employee employee1 = new Employee(4,"Amar",1995); 11 | Employee employee2 = new Employee(1,"Rakesh",1992); 12 | Employee employee3 = new Employee(3,"Suresh",1991); 13 | Employee employee4 = new Employee(2,"Amar Kumar",1995); 14 | 15 | /** 16 | * Added up all the employee information in the employees list 17 | */ 18 | employees.add(employee1); 19 | employees.add(employee2); 20 | employees.add(employee3); 21 | employees.add(employee4); 22 | /** 23 | * prints the unordered list of employees 24 | */ 25 | System.out.println(employees); 26 | /** 27 | * sorts the collection object 28 | */ 29 | Collections.sort(employees); 30 | /** 31 | * prints the employee details 32 | */ 33 | System.out.println(employees); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javacollection/comparable/Employee.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javacollection.comparable; 2 | 3 | /** 4 | * Comparable is used for natural ordering of the Object. 5 | * In order to enable the ordering, we must implement Comparable Interface - compareTo() method. 6 | */ 7 | public class Employee implements Comparable{ 8 | private int id; 9 | private String name; 10 | private int year; 11 | 12 | public Employee(int id, String name, int year) { 13 | this.id = id; 14 | this.name = name; 15 | this.year = year; 16 | } 17 | 18 | public int getId() { 19 | return id; 20 | } 21 | 22 | public void setId(int id) { 23 | this.id = id; 24 | } 25 | 26 | public String getName() { 27 | return name; 28 | } 29 | 30 | public void setName(String name) { 31 | this.name = name; 32 | } 33 | 34 | public int getYear() { 35 | return year; 36 | } 37 | 38 | public void setYear(int year) { 39 | this.year = year; 40 | } 41 | 42 | @Override 43 | public String toString() { 44 | return "Employee{" + 45 | "id=" + id + 46 | ", name='" + name + '\'' + 47 | ", year=" + year + 48 | '}'; 49 | } 50 | 51 | /** 52 | * If this.vale is lesser than the passed it should return a negative value 53 | * If this.value is greater than the passed value it should return a positive value 54 | * If it's Equal should use Zero 55 | */ 56 | 57 | @Override 58 | public int compareTo(Employee employee) { 59 | /** 60 | * if you want to return a comparison between string, call out compareTo() method of String 61 | * e.g return this.name.compareTo(employee.name); 62 | */ 63 | if (this.getId() < employee.getId()) return -1; 64 | if (this.getId() > employee.getId()) return 1; 65 | else return 0; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javacollection/comparator/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javacollection.comparator; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | public class Caller { 8 | 9 | public static void main(String[] args) { 10 | List movies = new ArrayList<>(); 11 | Movie movie1 = new Movie(5, 2010, 2, "Die Another Day"); 12 | Movie movie2 = new Movie(6, 2002, 5, "Harry Potter"); 13 | Movie movie3 = new Movie(2, 2015, 3, "Dracula"); 14 | Movie movie4 = new Movie(3, 2006, 5, "Double Dragon"); 15 | movies.add(movie1); 16 | movies.add(movie2); 17 | movies.add(movie3); 18 | movies.add(movie4); 19 | System.out.println(movies); 20 | Collections.sort(movies, new RatingComparator()); 21 | //Collections.sort(movies); 22 | System.out.println(movies); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javacollection/comparator/Movie.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javacollection.comparator; 2 | 3 | public class Movie implements Comparable{ 4 | 5 | private int id; 6 | private int year; 7 | private int rating; 8 | private String name; 9 | 10 | public Movie(int id, int year, int rating, String name) { 11 | this.id = id; 12 | this.year = year; 13 | this.rating = rating; 14 | this.name = name; 15 | } 16 | 17 | public int getId() { 18 | return id; 19 | } 20 | 21 | public void setId(int id) { 22 | this.id = id; 23 | } 24 | 25 | public int getYear() { 26 | return year; 27 | } 28 | 29 | public void setYear(int year) { 30 | this.year = year; 31 | } 32 | 33 | @Override 34 | public String toString() { 35 | return "Movie{" + 36 | "id=" + id + 37 | ", year=" + year + 38 | ", rating=" + rating + 39 | ", name='" + name + '\'' + 40 | '}'; 41 | } 42 | 43 | public int getRating() { 44 | return rating; 45 | } 46 | 47 | public void setRating(int rating) { 48 | this.rating = rating; 49 | } 50 | 51 | public String getName() { 52 | return name; 53 | } 54 | 55 | public void setName(String name) { 56 | this.name = name; 57 | } 58 | 59 | @Override 60 | public int compareTo(Movie o) { 61 | return this.id-o.getId(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javacollection/comparator/RatingComparator.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javacollection.comparator; 2 | 3 | import java.util.Comparator; 4 | 5 | /** 6 | * If we want to sort an object with different or with the custom fields, we can use Comparator interface 7 | * ~~ Comparable - compareTo() method - comparison between this and the Model object | Model class implements the overridden compareTo Method() 8 | * ~~ Comparator - compare() method - comparison between two Model object | Model class implements the overridden compare Method() 9 | */ 10 | public class RatingComparator implements Comparator { 11 | 12 | /** 13 | * 14 | * Once we implement ComparatorModel we must override compare() method. 15 | * Return a positive, 0 or a negative integer as to denote the equality. 16 | */ 17 | @Override 18 | public int compare(Movie m1, Movie m2) { 19 | return m1.getYear()-m2.getYear(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javarefresher/immutable/Address.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javarefresher.immutable; 2 | 3 | /** 4 | * Let the Non-Immutable Class implement Clonable interface. 5 | * @override clone() method 6 | */ 7 | public class Address implements Cloneable { 8 | public String addressType; 9 | public String address; 10 | public String city; 11 | 12 | public Address(String addressType, String address, String city) { 13 | super(); 14 | this.addressType = addressType; 15 | this.address = address; 16 | this.city = city; 17 | } 18 | 19 | public String getAddressType() { 20 | return addressType; 21 | } 22 | 23 | public void setAddressType(String addressType) { 24 | this.addressType = addressType; 25 | } 26 | 27 | public String getAddress() { 28 | return address; 29 | } 30 | 31 | public void setAddress(String address) { 32 | this.address = address; 33 | } 34 | 35 | public String getCity() { 36 | return city; 37 | } 38 | 39 | public void setCity(String city) { 40 | this.city = city; 41 | } 42 | 43 | public Object clone() throws CloneNotSupportedException { 44 | return super.clone(); 45 | } 46 | 47 | @Override 48 | public String toString() { 49 | return "Address{" + 50 | "addressType='" + addressType + '\'' + 51 | ", address='" + address + '\'' + 52 | ", city='" + city + '\'' + 53 | '}'; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javarefresher/immutable/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javarefresher.immutable; 2 | 3 | public class Caller { 4 | public static void main(String[] args) throws CloneNotSupportedException { 5 | Employee emp = new Employee("Amar Kumar", 27, new Address("Home", "Crystal Dew Apartments", "Bangalore")); 6 | Address address = emp.getAddress(); 7 | System.out.println(address); 8 | address.setAddressType("Office"); 9 | address.setAddress("EGL Tech Park"); 10 | address.setCity("Hyderabad"); 11 | System.out.println(emp.getAddress()); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javarefresher/immutable/Employee.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javarefresher.immutable; 2 | 3 | final class Employee{ 4 | /** 5 | * To make the Class as immutable, make all the fields as private and final. 6 | * Let the constructor set the value of it as once, and it can't be modified. 7 | */ 8 | private final String empName; 9 | private final int age; 10 | private final Address address; 11 | 12 | public Employee(String name, int age, Address address) { 13 | super(); 14 | this.empName = name; 15 | this.age = age; 16 | this.address = address; 17 | } 18 | 19 | public String getEmpName() { 20 | return empName; 21 | } 22 | public int getAge() { 23 | return age; 24 | } 25 | public Address getAddress() throws CloneNotSupportedException { 26 | return (Address) address.clone(); 27 | } 28 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/javarefresher/strings/Strings.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.javarefresher.strings; 2 | 3 | /** 4 | * Java program to demonstrate difference between String, StringBuilder and StringBuffer 5 | */ 6 | 7 | public class Strings { 8 | 9 | /** 10 | * The static block is executed first. 11 | */ 12 | static { 13 | System.out.println("Hello"); 14 | } 15 | 16 | // Concatenates to String 17 | public static void concat1(String s1) { 18 | //even though we store the s1 with new value. 19 | //it won't change 20 | s1 = s1 + "+Append"; 21 | } 22 | 23 | // Concatenates to StringBuilder 24 | public static void concat2(StringBuilder s2) { 25 | s2.append("+Append"); 26 | } 27 | 28 | // Concatenates to StringBuffer 29 | public static void concat3(StringBuffer s3) { 30 | s3.append("+Append"); 31 | } 32 | 33 | public static void main(String[] args) { 34 | 35 | String string1 = new String("abc"); 36 | String string2 = new String("abc"); 37 | System.out.println(string1 == string2); 38 | 39 | System.out.println(System.identityHashCode(string1)); 40 | System.out.println(System.identityHashCode(string2)); 41 | 42 | 43 | String s1 = "TestString"; 44 | concat1(s1); // s1 is not changed, as a copy of it is passed to method 45 | System.out.println("String: " + s1); 46 | 47 | StringBuilder s2 = new StringBuilder("TestString"); 48 | concat2(s2); // s2 is changed 49 | System.out.println("StringBuilder: " + s2); 50 | 51 | StringBuffer s3 = new StringBuffer("TestString"); 52 | concat3(s3); // s3 is changed 53 | System.out.println("StringBuffer: " + s3); 54 | } 55 | } 56 | 57 | 58 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/jdk/Executable.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.jdk; 2 | 3 | /** 4 | * Functional Interface is used, so that the interface do not add more methods by accident. 5 | * If we add up more methods, it will give compilation error. 6 | */ 7 | @FunctionalInterface 8 | public interface Executable { 9 | void execute(); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/jdk/FirstInterface.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.jdk; 2 | 3 | @FunctionalInterface 4 | public interface FirstInterface { 5 | void show(); 6 | 7 | default void log() { 8 | System.out.println("Log method called out from FirstInterface"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/jdk/JDK8InterfaceFeature.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.jdk; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | 7 | public class JDK8InterfaceFeature implements FirstInterface,SecondInterface { 8 | 9 | public static void main(String[] args) { 10 | 11 | // 1. Functional Interface 12 | 13 | /** 14 | * If the interface has only single method, it can be instantiated right away 15 | */ 16 | Executable e1 = new Executable() { 17 | @Override 18 | public void execute() { 19 | System.out.println("Regular Implementation of Function Interface"); 20 | } 21 | }; 22 | 23 | //call execute method, with e1 will call the method currently implemented. 24 | e1.execute(); 25 | 26 | /** 27 | * The implementation is give out by Lambda Expression. 28 | */ 29 | Executable e2 = () -> System.out.println("Lambda Expression implementation of Functional Interface"); 30 | 31 | //Now the e2 has the implementation of execute() method, you can call it. 32 | e2.execute(); 33 | 34 | 35 | // 2. forEach() method in Collection 36 | 37 | //creating a sample Collection - ArrayList 38 | List myList = new ArrayList(); 39 | for(int i=0; i<10; i++) 40 | myList.add(i); 41 | 42 | /** 43 | * traversing using Iterator - before Java 1.8 44 | * Though using iterator we can make changes to the ArrayList 45 | */ 46 | Iterator iterator = myList.iterator(); 47 | while(iterator.hasNext()){ 48 | Integer i = iterator.next(); 49 | System.out.println(i); 50 | } 51 | 52 | /** 53 | * traversing using forEach - Java 1.8 Onwards 54 | * Though it creates an implicit iterator, it doesn't allow to perform or edit value of collection 55 | */ 56 | myList.forEach(x -> System.out.println(x)); 57 | 58 | 59 | } 60 | 61 | //3. Default and Static method 62 | 63 | @Override 64 | public void show() { 65 | System.out.println("Show"); 66 | } 67 | 68 | @Override 69 | public void hide() { 70 | System.out.println("Hide"); 71 | } 72 | 73 | /** 74 | * Apart from Implementing method, which needs to be which is present in Interface 75 | * We must provide implementation of default method which exists in both interface. 76 | * 77 | * Compiler Error - Which Stops from Diamond Problem. 78 | * com.interview.brushups.jdk.JDK8Feature inherits unrelated defaults for log() from 79 | * types com.interview.brushups.jdk.FirstInterface and com.interview.brushups.jdk.SecondInterface 80 | */ 81 | @Override 82 | public void log() { 83 | System.out.println("Log"); 84 | } 85 | } 86 | 87 | 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/jdk/JDK8StreamTimeAPI.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.jdk; 2 | 3 | import java.time.LocalDate; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.Stream; 8 | 9 | public class JDK8StreamTimeAPI { 10 | 11 | public static void main(String[] args) { 12 | 13 | //4. Stream APIs 14 | 15 | // create a list of string 16 | List listOfCharacter = Arrays.asList(90, 60, 20, 10, 25, 60); 17 | 18 | //Create a sequential stream of String by calling the stream() method 19 | Stream characterStream = listOfCharacter.stream(); 20 | 21 | //Create a parallel stream of String by calling the parallelStream() method 22 | Stream characterParallelStream = listOfCharacter.parallelStream(); 23 | 24 | // call out the forEach() method in the stream 25 | characterStream.forEach(x -> System.out.print(x + " ")); 26 | System.out.println("<-- Sequential Stream of characterStream "); 27 | 28 | //using lambda with Stream API, filter example 29 | Stream numberGreater20 = characterParallelStream.filter(p -> p > 20); 30 | 31 | /** 32 | * using lambda in forEach 33 | * Note : If we perform forEach Operation on Stream. 34 | * We can't perform another operation such as collect() or forEach again 35 | */ 36 | 37 | // numberGreater20.forEach(p -> System.out.print(p+" ")); 38 | // System.out.println("<-- Filter and parallel Stream of characterStream "); 39 | 40 | List filteredList = numberGreater20.collect(Collectors.toList()); 41 | for (Integer number : filteredList) { 42 | System.out.print(number + " "); 43 | } 44 | 45 | //4. Date and Time API - java.time.* 46 | System.out.println("Java Date and Time\n"); 47 | 48 | /** 49 | * Java has introduced a new Date and Time API since Java 8. 50 | * The java.time package contains Java 8 Date and Time classes. 51 | */ 52 | LocalDate date = LocalDate.now(); 53 | LocalDate yesterday = date.minusDays(1); 54 | LocalDate tomorrow = yesterday.plusDays(2); 55 | System.out.println("Today's date: " + date); 56 | System.out.println("Yesterday's date: " + yesterday); 57 | System.out.println("Tomorrow's date: " + tomorrow); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/jdk/SecondInterface.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.jdk; 2 | 3 | @FunctionalInterface 4 | public interface SecondInterface { 5 | void hide(); 6 | default void log(){ 7 | System.out.println("Log method called out from SecondInterface"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/kafka/ConsumerClient.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.kafka; 2 | 3 | import org.apache.kafka.clients.consumer.ConsumerConfig; 4 | import org.apache.kafka.clients.consumer.ConsumerRecord; 5 | import org.apache.kafka.clients.consumer.ConsumerRecords; 6 | import org.apache.kafka.clients.consumer.KafkaConsumer; 7 | import org.apache.kafka.common.serialization.StringDeserializer; 8 | 9 | import java.util.Arrays; 10 | import java.util.Properties; 11 | 12 | public class ConsumerClient { 13 | 14 | public static void main(String args[]) throws Exception { 15 | 16 | //Kafka consumer configuration settings 17 | Properties props = new Properties(); 18 | 19 | props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); 20 | props.put(ConsumerConfig.GROUP_ID_CONFIG, "application-one"); 21 | props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true"); 22 | 23 | props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); 24 | props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); 25 | 26 | props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest"); 27 | props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000"); 28 | props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "300000"); 29 | 30 | KafkaConsumer consumer = new KafkaConsumer(props); 31 | 32 | String topicName = "test-topic"; 33 | 34 | //Kafka Consumer subscribes list of topics here. 35 | consumer.subscribe(Arrays.asList(topicName)); 36 | 37 | //print the topic name 38 | System.out.println("Subscribed to topic " + topicName); 39 | 40 | while (true) { 41 | ConsumerRecords records = consumer.poll(100); 42 | for (ConsumerRecord record : records) 43 | // print the offset,key and value for the consumer records. 44 | System.out.printf("partition = %d, offset = %d, key = %s, value = %s\n",record.partition(), record.offset(), record.key(), record.value()); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/kafka/ProducerClient.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.kafka; 2 | 3 | import org.apache.kafka.clients.producer.ProducerConfig; 4 | import org.apache.kafka.clients.producer.Callback; 5 | import org.apache.kafka.clients.producer.RecordMetadata; 6 | import org.apache.kafka.clients.producer.KafkaProducer; 7 | import org.apache.kafka.clients.producer.ProducerRecord; 8 | import org.apache.kafka.common.serialization.StringSerializer; 9 | 10 | import java.util.Properties; 11 | import java.util.Scanner; 12 | 13 | public class ProducerClient { 14 | 15 | public static void main(String args[]) throws Exception { 16 | 17 | // create instance for properties to access producer configs 18 | Properties props = new Properties(); 19 | 20 | //Assign localhost id 21 | props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); 22 | 23 | //Set acknowledgements for producer requests. 24 | props.put(ProducerConfig.ACKS_CONFIG, "all"); 25 | 26 | //If the request fails, the producer can automatically retry, 27 | props.put(ProducerConfig.RETRIES_CONFIG, 10000000); 28 | 29 | //Specify buffer size in config 30 | props.put(ProducerConfig.LINGER_MS_CONFIG, 1000); 31 | 32 | //The buffer.memory controls the total amount of memory available to the producer for buffering. 33 | props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432); 34 | props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); 35 | props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); 36 | 37 | // Create a Kafka Producer, put in the configuration properties. 38 | KafkaProducer producer = new KafkaProducer(props); 39 | 40 | //Assign topicName to string variable 41 | String topicName = "test-topic"; 42 | 43 | Scanner scanner = new Scanner(System.in); // Create a Scanner object 44 | System.out.println("Enter # of msg to produce"); 45 | Integer number = scanner.nextInt(); // Read user input 46 | 47 | int count = 0; 48 | for (int i = 1; i <= number; i++) { 49 | count++; 50 | 51 | //Create a new Producer Record | (topicName, Value) OR (topicName, Key, Value) 52 | ProducerRecord record; 53 | record = new ProducerRecord(topicName, Integer.toString(count), "Hello " + count); 54 | 55 | // Handle sent records 56 | producer.send(record, (recordMetadata, e) -> { 57 | if (e != null) { 58 | System.out.println("Record Sent Failed"); 59 | } else { 60 | System.out.println("Topic :" + recordMetadata.topic()); 61 | System.out.println("Partition :" + recordMetadata.partition()); 62 | System.out.println("Offset :" + recordMetadata.offset()); 63 | System.out.println("TimeStamp :" + recordMetadata.timestamp()); 64 | } 65 | }); 66 | } 67 | producer.close(); 68 | } 69 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/kafka/TweetProducer.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.kafka; 2 | 3 | import com.google.common.collect.Lists; 4 | import com.twitter.hbc.ClientBuilder; 5 | import com.twitter.hbc.core.Client; 6 | import com.twitter.hbc.core.Constants; 7 | import com.twitter.hbc.core.Hosts; 8 | import com.twitter.hbc.core.HttpHosts; 9 | import com.twitter.hbc.core.endpoint.StatusesFilterEndpoint; 10 | import com.twitter.hbc.core.processor.StringDelimitedProcessor; 11 | import com.twitter.hbc.httpclient.auth.Authentication; 12 | import com.twitter.hbc.httpclient.auth.OAuth1; 13 | import org.apache.kafka.clients.producer.*; 14 | import org.apache.kafka.common.serialization.StringSerializer; 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | 18 | import java.util.List; 19 | import java.util.Properties; 20 | import java.util.concurrent.BlockingQueue; 21 | import java.util.concurrent.LinkedBlockingQueue; 22 | import java.util.concurrent.TimeUnit; 23 | 24 | public class TweetProducer { 25 | 26 | Logger logger = LoggerFactory.getLogger(TweetProducer.class.getName()); 27 | 28 | // Twitter Credential 29 | String consumerKey = ""; 30 | String consumerSecret = ""; 31 | String token = ""; 32 | String secret = ""; 33 | 34 | List terms = Lists.newArrayList("carryminati"); 35 | 36 | public TweetProducer(){} 37 | 38 | public static void main(String[] args) { 39 | new TweetProducer().run(); 40 | } 41 | 42 | public void run(){ 43 | 44 | logger.info("Setup"); 45 | 46 | /** Set up your blocking queues: Be sure to size these properly based on expected TPS of your stream */ 47 | BlockingQueue msgQueue = new LinkedBlockingQueue(1000); 48 | 49 | // create a twitter client 50 | Client client = createTwitterClient(msgQueue); 51 | // Attempts to establish a connection. 52 | client.connect(); 53 | 54 | // create a kafka producer 55 | KafkaProducer producer = createKafkaProducer(); 56 | 57 | // add a shutdown hook 58 | Runtime.getRuntime().addShutdownHook(new Thread(() -> { 59 | logger.info("stopping application..."); 60 | logger.info("shutting down client from twitter..."); 61 | client.stop(); 62 | logger.info("closing producer..."); 63 | producer.close(); 64 | logger.info("done!"); 65 | })); 66 | 67 | // loop to send tweets to kafka 68 | // on a different thread, or multiple different threads.... 69 | while (!client.isDone()) { 70 | String msg = null; 71 | try { 72 | msg = msgQueue.poll(5, TimeUnit.SECONDS); 73 | } catch (InterruptedException e) { 74 | e.printStackTrace(); 75 | client.stop(); 76 | } 77 | if (msg != null){ 78 | logger.info(msg); 79 | producer.send(new ProducerRecord<>("tweets", null, msg), new Callback() { 80 | @Override 81 | public void onCompletion(RecordMetadata recordMetadata, Exception e) { 82 | if (e != null) { 83 | logger.error("Something bad happened", e); 84 | } 85 | } 86 | }); 87 | } 88 | } 89 | logger.info("End of application"); 90 | } 91 | 92 | public Client createTwitterClient(BlockingQueue msgQueue){ 93 | 94 | /** Declare the host you want to connect to, the endpoint, and authentication (basic auth or oauth) */ 95 | Hosts hosebirdHosts = new HttpHosts(Constants.STREAM_HOST); 96 | StatusesFilterEndpoint hosebirdEndpoint = new StatusesFilterEndpoint(); 97 | 98 | hosebirdEndpoint.trackTerms(terms); 99 | 100 | // These secrets should be read from a config file 101 | Authentication hosebirdAuth = new OAuth1(consumerKey, consumerSecret, token, secret); 102 | 103 | ClientBuilder builder = new ClientBuilder() 104 | .name("Hosebird-Client-01") // optional: mainly for the logs 105 | .hosts(hosebirdHosts) 106 | .authentication(hosebirdAuth) 107 | .endpoint(hosebirdEndpoint) 108 | .processor(new StringDelimitedProcessor(msgQueue)); 109 | 110 | Client hosebirdClient = builder.build(); 111 | return hosebirdClient; 112 | } 113 | 114 | public KafkaProducer createKafkaProducer(){ 115 | String bootstrapServers = "localhost:9092"; 116 | 117 | // create Producer properties 118 | Properties properties = new Properties(); 119 | properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); 120 | properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); 121 | properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); 122 | 123 | // create safe Producer 124 | properties.setProperty(ProducerConfig.ACKS_CONFIG, "all"); 125 | properties.setProperty(ProducerConfig.RETRIES_CONFIG, Integer.toString(Integer.MAX_VALUE)); 126 | properties.setProperty(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "5"); // kafka 2.0 >= 1.1 so we can keep this as 5. Use 1 otherwise. 127 | 128 | // high throughput producer (at the expense of a bit of latency and CPU usage) 129 | properties.setProperty(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy"); 130 | properties.setProperty(ProducerConfig.LINGER_MS_CONFIG, "20"); 131 | properties.setProperty(ProducerConfig.BATCH_SIZE_CONFIG, Integer.toString(32*1024)); // 32 KB batch size 132 | 133 | // create the producer 134 | KafkaProducer producer = new KafkaProducer(properties); 135 | return producer; 136 | } 137 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/kafkaspark/KafkaSparkStream.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.kafkaspark; 2 | 3 | import org.apache.kafka.clients.consumer.ConsumerConfig; 4 | import org.apache.kafka.clients.consumer.ConsumerRecord; 5 | import org.apache.kafka.common.serialization.StringDeserializer; 6 | import org.apache.spark.SparkConf; 7 | import org.apache.spark.streaming.Durations; 8 | import org.apache.spark.streaming.api.java.JavaInputDStream; 9 | import org.apache.spark.streaming.api.java.JavaStreamingContext; 10 | import org.apache.spark.streaming.kafka010.ConsumerStrategies; 11 | import org.apache.spark.streaming.kafka010.KafkaUtils; 12 | import org.apache.spark.streaming.kafka010.LocationStrategies; 13 | 14 | import java.util.Arrays; 15 | import java.util.Collection; 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | public class KafkaSparkStream { 20 | 21 | public static void main(String[] args) throws InterruptedException { 22 | Map kafkaParams = new HashMap<>(); 23 | kafkaParams.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); 24 | kafkaParams.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); 25 | kafkaParams.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); 26 | kafkaParams.put(ConsumerConfig.GROUP_ID_CONFIG, "consumer-group"); 27 | kafkaParams.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true); 28 | 29 | kafkaParams.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest"); 30 | kafkaParams.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000"); 31 | kafkaParams.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "300000"); 32 | 33 | Collection topics = Arrays.asList("test-topic"); 34 | 35 | SparkConf sparkConf = new SparkConf(); 36 | sparkConf.setMaster("local[*]"); 37 | sparkConf.setAppName("MessageLoggingApp"); 38 | 39 | JavaStreamingContext streamingContext = new JavaStreamingContext(sparkConf, Durations.seconds(1)); 40 | JavaInputDStream> inputDStream = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies.Subscribe(topics, kafkaParams)); 41 | 42 | inputDStream.foreachRDD(rdd -> { 43 | rdd.foreach(record -> 44 | System.out.printf("partition = %d, offset = %d, key = %s, value = %s\n", 45 | record.partition(), 46 | record.offset(), 47 | record.key(), 48 | record.value())); 49 | } 50 | ); 51 | 52 | streamingContext.start(); 53 | streamingContext.awaitTermination(); 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/mapreduce/BixiMontrealAnalysis.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.mapreduce; 2 | 3 | import org.apache.hadoop.conf.Configuration; 4 | import org.apache.hadoop.fs.Path; 5 | import org.apache.hadoop.io.IntWritable; 6 | import org.apache.hadoop.io.LongWritable; 7 | import org.apache.hadoop.io.Text; 8 | import org.apache.hadoop.mapreduce.Job; 9 | import org.apache.hadoop.mapreduce.Mapper; 10 | import org.apache.hadoop.mapreduce.Reducer; 11 | import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; 12 | import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; 13 | 14 | import java.io.IOException; 15 | 16 | public class BixiMontrealAnalysis { 17 | 18 | public static void main(String args[]) throws IOException, ClassNotFoundException, InterruptedException { 19 | Configuration conf = new Configuration(); 20 | Job job = Job.getInstance(conf,"bix-montreal-job"); 21 | 22 | job.setJarByClass(BixiMontrealAnalysis.class); 23 | job.setMapperClass(BixiMapper.class); 24 | 25 | //job.setCombinerClass(BixiReducer.class); 26 | job.setReducerClass(BixiReducer.class); 27 | 28 | job.setMapOutputKeyClass(IntWritable.class); 29 | job.setMapOutputValueClass(IntWritable.class); 30 | 31 | job.setOutputKeyClass(IntWritable.class); 32 | job.setOutputValueClass(LongWritable.class); 33 | 34 | FileInputFormat.addInputPath(job, new Path(args[0])); 35 | FileOutputFormat.setOutputPath(job, new Path(args[1])); 36 | System.exit(job.waitForCompletion(true) ? 0 : 1); 37 | } 38 | 39 | public static class BixiMapper extends Mapper { 40 | public void map(LongWritable offset, Text line, Context context) throws IOException, InterruptedException { 41 | String csvAttributes[] = line.toString().split(","); 42 | int isMember = 0; 43 | int duration = 0; 44 | try { 45 | duration = Integer.parseInt(csvAttributes[4]); //345 46 | isMember = Integer.parseInt(csvAttributes[5]); //0 or 1 47 | } catch (Exception e) { 48 | // System.out.println("Will Emit 0,0"); 49 | } 50 | System.out.println("isMember : " + isMember + "duration : " + duration); 51 | 52 | context.write(new IntWritable(isMember), new IntWritable(duration)); 53 | } 54 | } 55 | 56 | public static class BixiReducer extends Reducer { 57 | public void reduce(IntWritable isMember, Iterable combinedDurationByIsMember, Context context) throws IOException, InterruptedException { 58 | 59 | long sum = 0L; 60 | int isMemType = isMember.get(); 61 | for (IntWritable duration : combinedDurationByIsMember) { 62 | sum = sum + (long) duration.get(); 63 | } 64 | System.out.println("isMemType : " + isMemType + "sum : " + sum); 65 | context.write(new IntWritable(isMemType), new LongWritable(sum)); 66 | } 67 | } 68 | 69 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/mapreduce/SalesCount.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.mapreduce; 2 | 3 | import org.apache.hadoop.conf.Configuration; 4 | import org.apache.hadoop.fs.Path; 5 | import org.apache.hadoop.io.IntWritable; 6 | import org.apache.hadoop.io.Text; 7 | import org.apache.hadoop.mapreduce.Job; 8 | import org.apache.hadoop.mapreduce.Mapper; 9 | import org.apache.hadoop.mapreduce.Reducer; 10 | import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; 11 | import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; 12 | 13 | import java.io.IOException; 14 | 15 | public class SalesCount { 16 | public static void main(String[] args) throws Exception { 17 | Configuration conf = new Configuration(); 18 | Job job = Job.getInstance(conf, "sales-job"); 19 | job.setJarByClass(SalesCount.class); 20 | job.setMapperClass(SalesMapMapper.class); 21 | job.setCombinerClass(SalesReportReducer.class); 22 | job.setReducerClass(SalesReportReducer.class); 23 | job.setOutputKeyClass(Text.class); 24 | job.setOutputValueClass(IntWritable.class); 25 | 26 | FileInputFormat.addInputPath(job, new Path(args[0])); 27 | FileOutputFormat.setOutputPath(job, new Path(args[1])); 28 | System.exit(job.waitForCompletion(true) ? 0 : 1); 29 | 30 | } 31 | 32 | public static class SalesMapMapper extends Mapper { 33 | public void map(IntWritable key, Text value, Context context) throws IOException, InterruptedException { 34 | String[] words = value.toString().split(","); 35 | for (String word : words) { 36 | context.write(new Text(word), new IntWritable(1)); 37 | } 38 | } 39 | } 40 | 41 | public static class SalesReportReducer extends Reducer { 42 | public void reduce(Text word, Iterable values, Context context) throws IOException, InterruptedException { 43 | int sum = 0; 44 | for (IntWritable value : values) { 45 | sum = sum + value.get(); 46 | } 47 | context.write(word, new IntWritable(sum)); 48 | } 49 | } 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/mapreduce/WordCountMapReduce.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.mapreduce; 2 | 3 | import org.apache.hadoop.conf.Configuration; 4 | import org.apache.hadoop.fs.Path; 5 | import org.apache.hadoop.io.IntWritable; 6 | import org.apache.hadoop.io.LongWritable; 7 | import org.apache.hadoop.io.Text; 8 | import org.apache.hadoop.mapreduce.Job; 9 | import org.apache.hadoop.mapreduce.Mapper; 10 | import org.apache.hadoop.mapreduce.Reducer; 11 | import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; 12 | import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; 13 | 14 | import java.io.IOException; 15 | import java.util.StringTokenizer; 16 | 17 | public class WordCountMapReduce { 18 | 19 | public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { 20 | /** 21 | * Create a new Configuration, add up whatever the values required in configuration. 22 | */ 23 | Configuration conf = new Configuration(); 24 | /** 25 | * Create a new Job Instance, get a new Job Instance via getInstance() 26 | */ 27 | Job job = Job.getInstance(conf,"word-count-job"); 28 | job.setMapperClass(WordCountMapper.class); 29 | job.setCombinerClass(WordCountReducer.class); 30 | job.setReducerClass(WordCountReducer.class); 31 | job.setJarByClass(WordCountMapReduce.class); 32 | 33 | /** 34 | * Set the output key and value class 35 | */ 36 | job.setOutputKeyClass(Text.class); 37 | job.setOutputValueClass(IntWritable.class); 38 | 39 | /** 40 | * Set the input and output path, 41 | */ 42 | FileInputFormat.addInputPath(job, new Path(args[0])); 43 | FileOutputFormat.setOutputPath(job, new Path(args[1])); 44 | 45 | System.exit(job.waitForCompletion(true) ? 0 : 1); 46 | } 47 | 48 | public static class WordCountMapper extends Mapper { 49 | public void map(LongWritable offset, Text line, Context context) throws IOException, InterruptedException { 50 | StringTokenizer iterator = new StringTokenizer(line.toString()); 51 | while (iterator.hasMoreTokens()) { 52 | Text word = new Text(iterator.nextToken()); 53 | context.write(word, new IntWritable(1)); 54 | } 55 | } 56 | } 57 | 58 | public static class WordCountReducer extends Reducer { 59 | public void reduce(Text key, Iterable values, Context context) throws IOException, InterruptedException { 60 | int sum = 0; 61 | for (IntWritable value : values) { 62 | sum = sum + value.get(); 63 | } 64 | context.write(key, new IntWritable(sum)); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/marker/cloneable/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.marker.cloneable; 2 | 3 | public class Caller { 4 | 5 | /** 6 | * 7 | * We can use clone() method on HashMap, HashSet, TreeSet, HashTable, Stack, IdentityHashMap 8 | */ 9 | public static void main(String args[]) { 10 | try { 11 | Student s1 = new Student(101, "amit"); 12 | Student s2 = (Student) s1.clone(); 13 | 14 | System.out.println(s1); 15 | System.out.println(s2); 16 | 17 | System.out.println(s1.getRoll() + " " + s1.getName()); 18 | System.out.println(s2.getRoll() + " " + s2.getName()); 19 | 20 | } catch (CloneNotSupportedException c) { 21 | System.out.println(c); 22 | } 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/marker/cloneable/Student.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.marker.cloneable; 2 | 3 | public class Student implements Cloneable { 4 | 5 | private int roll; 6 | private String name; 7 | 8 | Student(int roll, String name) { 9 | this.roll = roll; 10 | this.name = name; 11 | } 12 | 13 | public int getRoll() { 14 | return roll; 15 | } 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | public Object clone() throws CloneNotSupportedException { 22 | return super.clone(); 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/marker/externalizable/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.marker.externalizable; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.io.ObjectInputStream; 6 | import java.io.ObjectOutputStream; 7 | 8 | public class Caller { 9 | public static void main(String[] args) 10 | { 11 | Car car = new Car(10, "Ferrari", 1995); 12 | Car newCar = null; 13 | final String filename = "externalized.txt"; 14 | 15 | // Serialize the car 16 | try { 17 | FileOutputStream fo = new FileOutputStream(filename); 18 | ObjectOutputStream so = new ObjectOutputStream(fo); 19 | so.writeObject(car); 20 | so.flush(); 21 | } 22 | catch (Exception e) { 23 | System.out.println(e); 24 | } 25 | 26 | // De-serialize the car 27 | try { 28 | FileInputStream fi = new FileInputStream(filename); 29 | ObjectInputStream si = new ObjectInputStream(fi); 30 | newCar = (Car)si.readObject(); 31 | } 32 | catch (Exception e) { 33 | System.out.println(e); 34 | } 35 | 36 | System.out.println("The original car is:\n" + car); 37 | System.out.println("The new car is:\n" + newCar); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/marker/externalizable/Car.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.marker.externalizable; 2 | 3 | import java.io.Externalizable; 4 | import java.io.IOException; 5 | import java.io.ObjectInput; 6 | import java.io.ObjectOutput; 7 | 8 | public class Car implements Externalizable { 9 | 10 | /** 11 | * 1. In serialization object is constructed using Byte Stream. 12 | * 2. In Externalization there must be a no arg constructor, and object is constructed using the sequence of read 13 | * 3. Externalizeable gives us full freedom on what data member needs to be serialized, 14 | * writeExternal() & readExternal() should be written to draw the logic. 15 | * 4. Default no-arg constructor is must. 16 | */ 17 | public Car() 18 | { 19 | System.out.println("Default Constructor called"); 20 | } 21 | 22 | public Car(int age, String name, int year) { 23 | this.age = age; 24 | this.name = name; 25 | this.year = year; 26 | } 27 | 28 | int age; 29 | String name; 30 | int year; 31 | 32 | @Override 33 | public void writeExternal(ObjectOutput out) throws IOException { 34 | out.writeInt(age); 35 | out.writeObject(name); 36 | out.writeInt(year); 37 | } 38 | 39 | @Override 40 | public String toString() { 41 | return "Car{" + 42 | "age=" + age + 43 | ", name='" + name + '\'' + 44 | ", year=" + year + 45 | '}'; 46 | } 47 | 48 | @Override 49 | public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { 50 | age = in.readInt(); 51 | name = (String)in.readObject(); 52 | year = in.readInt(); 53 | 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/marker/serializable/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.marker.serializable; 2 | 3 | import java.io.*; 4 | 5 | public class Caller { 6 | 7 | public static void main(String[] args) { 8 | Car car = new Car(234, "Mustang","Passcode**123"); 9 | String filename = "serialized.txt"; 10 | 11 | // Serialization 12 | try { 13 | //Saving of object in a file 14 | FileOutputStream file = new FileOutputStream(filename); 15 | ObjectOutputStream out = new ObjectOutputStream(file); 16 | 17 | // Method for serialization of object 18 | out.writeObject(car); 19 | 20 | out.close(); 21 | file.close(); 22 | 23 | System.out.println("Object has been serialized"); 24 | 25 | } catch (IOException ex) { 26 | System.out.println("IOException is caught"); 27 | } 28 | 29 | 30 | Car deserializeCar = null; 31 | 32 | // Deserialization 33 | try { 34 | // Reading the object from a file 35 | FileInputStream file = new FileInputStream(filename); 36 | ObjectInputStream in = new ObjectInputStream(file); 37 | 38 | // Method for deserialization of object 39 | deserializeCar = (Car) in.readObject(); 40 | 41 | in.close(); 42 | file.close(); 43 | 44 | System.out.println("Object has been de-serialized "); 45 | System.out.println(deserializeCar); 46 | } catch (IOException ex) { 47 | System.out.println("IOException is caught"); 48 | } catch (ClassNotFoundException ex) { 49 | System.out.println("ClassNotFoundException is caught"); 50 | } 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/marker/serializable/Car.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.marker.serializable; 2 | 3 | import java.io.Serializable; 4 | 5 | 6 | /** 7 | * 1. Serializable is a marker interface. 8 | * 2. Only non-static data members are saved via Serialization process. 9 | * 3. Static data members and transient data members are not saved via Serialization process. 10 | * So, if you don’t want to save value of a non-static data member then make it transient. 11 | * 4. Constructor of object is never called when an object is de-serialized. 12 | */ 13 | public class Car implements Serializable { 14 | 15 | static final long serialVersionUID = 234L; 16 | 17 | private int topSpeed ; 18 | private String name; 19 | 20 | /** 21 | * variable with transient keyword will not be serialized. 22 | * Such as password etc. 23 | */ 24 | private transient String password; 25 | 26 | public Car(int topSpeed, String name, String password) { 27 | this.topSpeed = topSpeed; 28 | this.name = name; 29 | this.password = password; 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | return "Car{" + 35 | "topSpeed=" + topSpeed + 36 | ", name='" + name + '\'' + 37 | ", password='" + password + '\'' + 38 | '}'; 39 | } 40 | 41 | /* 42 | * When we deserialize, readResolve() method will be used to deserialize the object. 43 | * private Object readResolve() { 44 | * return new Car(23,"Ferrari", "f3r@rI'"); 45 | * } 46 | */ 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/multithreading/callable/CallableExecutor.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.multithreading.callable; 2 | 3 | import java.util.concurrent.Callable; 4 | import java.util.concurrent.ExecutorService; 5 | import java.util.concurrent.Executors; 6 | import java.util.concurrent.Future; 7 | 8 | import java.util.concurrent.ExecutionException; 9 | 10 | /** 11 | * execute(Runnable) does not return anything. 12 | * However, submit(Callable) returns a Future object 13 | * Future Objects - allows a way for you to programmatically cancel the running thread later. 14 | * It returns as get the V (Generics) that is returned when the Callable completes. 15 | */ 16 | public class CallableExecutor { 17 | 18 | public static void main(String args[]) { 19 | Callable callable = () -> "Return a String in Future Object"; 20 | 21 | ExecutorService executorService = Executors.newSingleThreadExecutor(); 22 | 23 | // Completion of Callable object will return Future Object of Type defined earlier 24 | Future future = executorService.submit(callable); 25 | 26 | // Check if Execution is done, using isDone() method 27 | if (future.isDone()) { 28 | try { 29 | System.out.println(future.get()); 30 | } catch (InterruptedException e) { 31 | e.printStackTrace(); 32 | } catch (ExecutionException e) { 33 | e.printStackTrace(); 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/multithreading/creation/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.multithreading.creation; 2 | 3 | public class Caller { 4 | public static void main(String[] args) { 5 | 6 | HelloThread threadOne = new HelloThread(); 7 | HelloThread threadTwo = new HelloThread(); 8 | HelloThread threadThree = new HelloThread(); 9 | threadOne.setName(" #1"); 10 | threadTwo.setName(" #2"); 11 | threadThree.setName(" #3"); 12 | threadOne.start(); 13 | threadTwo.start(); 14 | threadThree.start(); 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/multithreading/creation/HelloThread.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.multithreading.creation; 2 | 3 | public class HelloThread extends Thread { 4 | 5 | @Override 6 | public void run() { 7 | System.out.println("Hello"+Thread.currentThread().getName()); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/multithreading/deadlock/DeadLock.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.multithreading.deadlock; 2 | 3 | public class DeadLock { 4 | public static void main(String[] args) { 5 | final String resource1 = "ratan jaiswal"; 6 | final String resource2 = "vimal jaiswal"; 7 | // t1 tries to lock resource1 then resource2 8 | Thread t1 = new Thread() { 9 | public void run() { 10 | synchronized (resource1) { 11 | System.out.println("Thread 1: locked resource 1"); 12 | 13 | try { 14 | Thread.sleep(100); 15 | } catch (Exception e) { 16 | } 17 | 18 | synchronized (resource2) { 19 | System.out.println("Thread 1: locked resource 2"); 20 | } 21 | } 22 | } 23 | }; 24 | 25 | // t2 tries to lock resource2 then resource1 26 | Thread t2 = new Thread() { 27 | public void run() { 28 | synchronized (resource2) { 29 | System.out.println("Thread 2: locked resource 2"); 30 | try { 31 | Thread.sleep(100); 32 | } catch (Exception e) { 33 | } 34 | 35 | synchronized (resource1) { 36 | System.out.println("Thread 2: locked resource 1"); 37 | } 38 | } 39 | } 40 | }; 41 | 42 | 43 | t1.start(); 44 | t2.start(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/multithreading/executorservice/ThreadPool.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.multithreading.executorservice; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | 6 | public class ThreadPool { 7 | public static void main(String[] args) { 8 | 9 | /** 10 | * This will create a Thread Pool of 5 11 | * Any work will be handled 5 this set of 5 thread only 12 | * pass the thread to the ExecutorService instance for Execution 13 | * Threads will be re-used and will perform the task. 14 | */ 15 | ExecutorService executorService = Executors.newFixedThreadPool(5); 16 | 17 | for (int i = 1; i <= 20; i++) { 18 | Runnable worker = new WorkerThread("Task #"+i); 19 | executorService.execute(worker); 20 | } 21 | executorService.shutdown(); 22 | while (!executorService.isTerminated()) { } 23 | 24 | System.out.println("All Task has been completed"); 25 | } 26 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/multithreading/executorservice/WorkerThread.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.multithreading.executorservice; 2 | 3 | class WorkerThread implements Runnable { 4 | private String taskName; 5 | public WorkerThread(String number){ 6 | this.taskName=number; 7 | } 8 | public void run() { 9 | System.out.println(Thread.currentThread().getName()+" "+taskName+" Started"); 10 | try { 11 | Thread.sleep(2000); 12 | } catch (InterruptedException e) { 13 | e.printStackTrace(); 14 | } 15 | System.out.println(Thread.currentThread().getName()+" "+taskName+" Ended"); 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/multithreading/performance/SumRange.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.multithreading.performance; 2 | 3 | public class SumRange { 4 | 5 | public long getCounter() { 6 | return counter; 7 | } 8 | 9 | public void setCounter(long counter) { 10 | this.counter = counter; 11 | } 12 | 13 | long startRange; 14 | long endRange; 15 | long counter = 0; 16 | 17 | public SumRange(long startRange, long endRange) { 18 | this.startRange = startRange; 19 | this.endRange = endRange; 20 | } 21 | 22 | public void add() { 23 | for (long i = startRange; i <= endRange; i++) { 24 | counter += i; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/multithreading/performance/ThreadPerformance.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.multithreading.performance; 2 | 3 | import java.util.HashMap; 4 | import java.util.HashSet; 5 | 6 | class ThreadPerformance { 7 | 8 | static long MAX_NUM = Integer.MAX_VALUE; 9 | 10 | public static void main(String args[]) throws InterruptedException { 11 | oneThread(); 12 | twoThreads(); 13 | } 14 | 15 | public static void twoThreads() throws InterruptedException { 16 | 17 | long start = System.currentTimeMillis(); 18 | SumRange s1 = new SumRange(1, MAX_NUM / 2); 19 | SumRange s2 = new SumRange(1 + (MAX_NUM / 2), MAX_NUM); 20 | 21 | Thread t1 = new Thread(() -> { 22 | s1.add(); 23 | }); 24 | 25 | Thread t2 = new Thread(() -> { 26 | s2.add(); 27 | }); 28 | 29 | t1.start(); 30 | t2.start(); 31 | 32 | t1.join(); 33 | t2.join(); 34 | 35 | long finalCount = s1.getCounter() + s2.getCounter(); 36 | long end = System.currentTimeMillis(); 37 | System.out.println("Two threads final count = " + finalCount + " took " + (end - start)); 38 | } 39 | 40 | public static void oneThread() { 41 | 42 | long start = System.currentTimeMillis(); 43 | SumRange s = new SumRange(1, MAX_NUM); 44 | s.add(); 45 | long end = System.currentTimeMillis(); 46 | System.out.println("Single thread final count = " + s.getCounter() + " took " + (end - start)); 47 | } 48 | 49 | } 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/multithreading/producerconsumer/BlockingQueue.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.multithreading.producerconsumer; 2 | 3 | class BlockingQueue < T > { 4 | 5 | T[] array; 6 | Object lock = new Object(); 7 | int size = 0; 8 | int capacity; 9 | int head = 0; 10 | int tail = 0; 11 | 12 | public BlockingQueue(int capacity) { 13 | array = (T[]) new Object[capacity]; 14 | this.capacity = capacity; 15 | } 16 | 17 | public void enqueue(T item) throws InterruptedException { 18 | 19 | synchronized(lock) { 20 | 21 | while (size == capacity) { 22 | lock.wait(); 23 | } 24 | 25 | if (tail == capacity) { 26 | tail = 0; 27 | } 28 | 29 | array[tail] = item; 30 | size++; 31 | tail++; 32 | lock.notifyAll(); 33 | } 34 | } 35 | 36 | public T dequeue() throws InterruptedException { 37 | 38 | T item = null; 39 | synchronized(lock) { 40 | 41 | while (size == 0) { 42 | lock.wait(); 43 | } 44 | 45 | if (head == capacity) { 46 | head = 0; 47 | } 48 | 49 | item = array[head]; 50 | array[head] = null; 51 | head++; 52 | size--; 53 | 54 | lock.notifyAll(); 55 | } 56 | 57 | return item; 58 | } 59 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/multithreading/producerconsumer/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.multithreading.producerconsumer; 2 | 3 | public class Caller { 4 | 5 | public static void main(String[] args) throws InterruptedException { 6 | BlockingQueue q = new BlockingQueue<>(6); 7 | 8 | 9 | Thread t1 = new Thread(() -> { 10 | 11 | for (int i = 0; i<50; i++){ 12 | try { 13 | q.enqueue(new Integer(i)); 14 | System.out.println("Thread 1 enqueued <- " + i); 15 | } catch (InterruptedException e) { 16 | e.printStackTrace(); 17 | } 18 | } 19 | }); 20 | 21 | Thread t2 = new Thread(() -> { 22 | for(int i=0; i<25; i++){ 23 | try { 24 | System.out.println("Thread 2 dequeued -> " + q.dequeue()); 25 | } catch (InterruptedException e) { 26 | e.printStackTrace(); 27 | } 28 | } 29 | }); 30 | 31 | Thread t3 = new Thread(() -> { 32 | for(int i=0; i<25; i++){ 33 | try { 34 | System.out.println("Thread 3 dequeued -> " + q.dequeue()); 35 | } catch (InterruptedException e) { 36 | e.printStackTrace(); 37 | } 38 | } 39 | }); 40 | 41 | t1.start(); 42 | Thread.sleep(4000); 43 | t2.start(); 44 | 45 | // t2.join(); 46 | 47 | t3.start(); 48 | // t1.join(); 49 | // t3.join(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/multithreading/waitnotify/Caller.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.multithreading.waitnotify; 2 | 3 | public class Caller { 4 | 5 | public static void main(String args[]) { 6 | final Customer c = new Customer(); 7 | new Thread() { 8 | public void run() { 9 | c.withdraw(15000); 10 | } 11 | }.start(); 12 | new Thread() { 13 | public void run() { 14 | c.deposit(5000); 15 | } 16 | }.start(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/multithreading/waitnotify/Customer.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.multithreading.waitnotify; 2 | 3 | class Customer { 4 | int amount = 10000; 5 | synchronized void withdraw(int amount) { 6 | System.out.println("going to withdraw..."); 7 | 8 | if (this.amount < amount) { 9 | System.out.println("Current Balance :"+this.amount); 10 | System.out.println("Requested Withdraw Amount :"+amount); 11 | System.out.println("Less balance; waiting for deposit..."); 12 | try { 13 | wait(); //this will release the lock, and wait for notify() signal to resume 14 | } catch (Exception e) { 15 | } 16 | } 17 | this.amount -= amount; 18 | System.out.println("withdraw completed..."+"Left Balance "+this.amount); 19 | } 20 | 21 | synchronized void deposit(int amount) { 22 | System.out.println("going to deposit..."+amount); 23 | this.amount += amount; 24 | System.out.println("deposit completed... "+"New Total "+this.amount); 25 | notify(); 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/recursion/Factorial.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.recursion; 2 | 3 | public class Factorial { 4 | 5 | public static int factorial(int number){ 6 | if(number == 1){ 7 | return 1; 8 | } 9 | else { 10 | int value = number * factorial(number - 1); 11 | return value; 12 | } 13 | } 14 | 15 | public static void main(String[] args) { 16 | System.out.println(factorial(5)); 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/recursion/FibonacciSeries.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.recursion; 2 | 3 | import java.util.Scanner; 4 | 5 | public class FibonacciSeries { 6 | 7 | static int previous = 0; 8 | static int next = 1; 9 | static int temp = 0; 10 | 11 | public static void fibonacci(int number) { 12 | 13 | if (number > 0) { 14 | System.out.print(previous + " "); 15 | temp = previous + next; // temp will sum up the two values 16 | previous = next; // previous now holds the next value 17 | next = temp; // next will hold the sum up values for next run. 18 | fibonacci(number-1); 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | Scanner scan = new Scanner(System.in); 24 | int upTONumber = scan.nextInt(); 25 | fibonacci(upTONumber); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/recursion/HelloWorld.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.recursion; 2 | 3 | public class HelloWorld { 4 | 5 | static int counter = 0; 6 | 7 | static void print() { 8 | counter++;//print method will increment the counter. 9 | if (counter <= 5) { 10 | System.out.println("Hello World " + counter); 11 | print(); //call the print() method, if the value is <= 5. 12 | } 13 | } 14 | 15 | public static void main(String[] args) { 16 | print(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/recursion/RecursionCounter.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.recursion; 2 | 3 | public class RecursionCounter { 4 | 5 | private static void printNum(int n) { 6 | // Base case 7 | if (n == 0) { 8 | return; 9 | } 10 | 11 | /** 12 | * If we call the method first which is recursive, it will put up all the method calls on the Stack. 13 | * when the base condition is met and a return call is made, it starts executing the methods. 14 | * Output : 1 2 3 4 5 6 7 8 9 10 15 | */ 16 | printNum(n-1); 17 | System.out.println(n + " "); 18 | 19 | /** 20 | * If we have have business logic written, after which the call is made to recursive method. 21 | * It first executes the business logic, and the calls the method, 1 by 1. 22 | * Output : 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 23 | */ 24 | // System.out.println(n + " "); 25 | // printNum(n-1); 26 | } 27 | 28 | public static void main( String args[] ) { 29 | // Recursive method called here 30 | printNum(10); 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/spark/SparkRDDWordCount.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.spark; 2 | 3 | import org.apache.spark.SparkConf; 4 | import org.apache.spark.api.java.JavaPairRDD; 5 | import org.apache.spark.api.java.JavaRDD; 6 | import org.apache.spark.api.java.JavaSparkContext; 7 | import scala.Tuple2; 8 | 9 | import java.util.Arrays; 10 | 11 | public class SparkRDDWordCount { 12 | public static void main(String[] args) { 13 | 14 | /** 15 | * It allows your Spark Application to access Spark Cluster with the help of Resource Manager (YARN/Mesos). 16 | * To create SparkContext, first SparkConf should be made. 17 | * 18 | * The SparkConf has a configuration parameter that our Spark driver application will pass to SparkContext. 19 | */ 20 | SparkConf conf =new SparkConf().setMaster("local").setAppName("SparkRDDWordCount"); 21 | 22 | JavaSparkContext javaSparkContext = new JavaSparkContext(conf); 23 | 24 | JavaRDD inputData = javaSparkContext.textFile(System.getProperty("user.dir")+"/src/main/resources/notes/bigdata/hadoop.md"); 25 | 26 | JavaRDD words = inputData.flatMap(line -> Arrays.asList(line.split(" ")).iterator()); 27 | JavaPairRDD wordMapTo1 = words.mapToPair(word -> new Tuple2(word,1)); 28 | 29 | /* 30 | The above code can also be simplified an written as below. 31 | JavaPairRDD flattenPairs = inputData.flatMapToPair(text -> Arrays.asList(text.split(" ")) 32 | .stream().map(word -> new Tuple2(word,1)) 33 | .iterator()); 34 | */ 35 | 36 | JavaPairRDD wordCountRDD = wordMapTo1.reduceByKey((v1,v2) -> v1 + v2); 37 | wordCountRDD.saveAsTextFile(System.getProperty("user.dir")+"/src/main/resources/output/spark/wordcount"); 38 | } 39 | } -------------------------------------------------------------------------------- /src/main/java/com/interview/brushups/strings/StringCompareTo.java: -------------------------------------------------------------------------------- 1 | package com.interview.brushups.strings; 2 | 3 | public class StringCompareTo { 4 | 5 | public static void main(String[] args) { 6 | String first = "Agile"; 7 | String second = "Bootcamp"; 8 | 9 | //When calling compareTo() method of the String it gives the difference of the character of First String to Another String 10 | System.out.println(first.compareTo(second)); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/resources/images/concurrency/concurrency.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amarkum/interview-refresher-java-bigdata/4d0a3f68f4ec3d444c1c2d1eb2aebd4e5092ad90/src/main/resources/images/concurrency/concurrency.png -------------------------------------------------------------------------------- /src/main/resources/images/java/ collections.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amarkum/interview-refresher-java-bigdata/4d0a3f68f4ec3d444c1c2d1eb2aebd4e5092ad90/src/main/resources/images/java/ collections.png -------------------------------------------------------------------------------- /src/main/resources/images/java/maps.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amarkum/interview-refresher-java-bigdata/4d0a3f68f4ec3d444c1c2d1eb2aebd4e5092ad90/src/main/resources/images/java/maps.png -------------------------------------------------------------------------------- /src/main/resources/images/java/thread-lifecycle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amarkum/interview-refresher-java-bigdata/4d0a3f68f4ec3d444c1c2d1eb2aebd4e5092ad90/src/main/resources/images/java/thread-lifecycle.png -------------------------------------------------------------------------------- /src/main/resources/images/java/throwable.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amarkum/interview-refresher-java-bigdata/4d0a3f68f4ec3d444c1c2d1eb2aebd4e5092ad90/src/main/resources/images/java/throwable.png -------------------------------------------------------------------------------- /src/main/resources/interview-questions.md: -------------------------------------------------------------------------------- 1 | """ 2 | # Big Data, Java, SQL, and OS Interview Questions 3 | 4 | ## Hadoop Interview Questions 5 | 1. **What is a Combiner?** 6 | _Companies: Legato, Impetus_ 7 | 8 | 2. **What is the difference between `hadoop fs`, `hadoop dfs`, and `hdfs dfs` commands?** 9 | _Company: Legato_ 10 | 11 | 3. **What is the difference between `put`, `copyFromLocal`, `get`, and `copyToLocal` commands?** 12 | _Company: Legato_ 13 | 14 | 4. **Explain the difference between AVRO, ORC, and Parquet file formats.** 15 | _Companies: Fidelity, Paypal_ 16 | 17 | 5. **Which scheduler is used, and what is the version of Oozie?** 18 | _Company: ThoughtWorks_ 19 | 20 | 6. **How does ZooKeeper assign a follower when the leader goes down?** 21 | _Company: ThoughtWorks_ 22 | 23 | 7. **How can we create a Hive table on HBase?** 24 | _Company: Deloitte_ 25 | 26 | 8. **Will Hive continue executing a query if the cluster is back after failure?** 27 | _Company: Subex_ 28 | 29 | 9. **Write a Kafka Producer and Consumer program.** 30 | _Company: OpenText_ 31 | 32 | 10. **Explain Hive bucketing and partitioning.** 33 | _Company: Impetus_ 34 | 35 | 11. **When should we use bucketing vs partitioning in Hive?** 36 | _Company: Impetus_ 37 | 38 | 12. **What are UDFs (User Defined Functions) in Hive?** 39 | _Company: Deloitte_ 40 | 41 | 13. **Explain the `hdfs -getmerge` command.** 42 | _Company: Sear Holding_ 43 | 44 | 14. **Using HBase shell, how can we retrieve data from a column family?** 45 | _Company: Sear Holding_ 46 | 47 | 15. **How do we bulk load data from HDFS to HBase?** 48 | _Company: Rapido_ 49 | 50 | 16. **Describe the architecture of HBase.** 51 | _Companies: Rapido, Tavant_ 52 | 53 | 17. **What is Tombstoning in HBase?** 54 | _Company: Rapido_ 55 | 56 | --- 57 | 58 | ## Kafka Interview Questions 59 | 1. **What are offsets in Kafka?** 60 | _Company: Sianr Mas Group_ 61 | 62 | 2. **What are ISR (In-Sync Replicas)?** 63 | _Company: Sianr Mas Group_ 64 | 65 | 3. **List commands to list topics, delete a topic, and run a producer and consumer.** 66 | _Company: Sianr Mas Group_ 67 | 68 | 4. **Explain the concept of consumer and consumer group in Kafka.** 69 | _Company: Sianr Mas Group_ 70 | 71 | 5. **Describe the architecture of Kafka.** 72 | _Company: Rapido_ 73 | 74 | 6. **If a producer is producing faster than the consumer can handle, how can we fix this?** 75 | _Company: HappiestMinds_ 76 | 77 | --- 78 | 79 | ## Hive Interview Questions 80 | 1. **What is static partitioning and dynamic partitioning in Hive?** 81 | _Company: Yodlee_ 82 | 83 | 2. **What are the datatypes in Hive?** 84 | _Company: UST Global_ 85 | 86 | 3. **How do you load a CSV with 4 columns combined into 1 column in Hive?** 87 | _Company: Synechron_ 88 | 89 | --- 90 | 91 | ## Spark Interview Questions 92 | 1. **Explain cache and persist in Spark.** 93 | _Company: Virtusa_ 94 | 95 | 2. **What are the levels of cache in Spark?** 96 | _Company: Virtusa_ 97 | 98 | 3. **What is a sliding window in Spark?** 99 | _Company: Virtusa_ 100 | 101 | 4. **How to submit a Spark job?** 102 | _Company: Virtusa_ 103 | 104 | 5. **Explain joining an RDD in Spark.** 105 | _Company: Virtusa_ 106 | 107 | 6. **What are broadcast variables and accumulators in Spark?** 108 | _Company: Virtusa_ 109 | 110 | 7. **Explain the difference between repartition and coalesce.** 111 | _Company: Virtusa_ 112 | 113 | 8. **How do you join two columns in a DataFrame?** 114 | _Company: Lowe's_ 115 | 116 | 9. **How can you calculate the difference by the last row in Spark?** 117 | _Company: Virtusa_ 118 | 119 | 10. **At which phase does Spark load data into memory?** 120 | _Company: Synechron_ 121 | 122 | 11. **What is the difference between map and mapPartitions?** 123 | _Company: HappiestMinds_ 124 | 125 | 12. **How does Spark handle files larger than main memory?** 126 | _Company: Tavant_ 127 | 128 | 13. **What is lineage in Spark?** 129 | _Company: L&T_ 130 | 131 | 14. **What is lazy evaluation in Spark?** 132 | _Company: L&T_ 133 | 134 | 15. **What is narrow transformation in Spark?** 135 | _Company: L&T_ 136 | 137 | 16. **What is speculative execution in Spark?** 138 | _Company: Quantiphi_ 139 | 140 | --- 141 | 142 | ## Java Interview Questions 143 | 1. **How do you detect a loop in a LinkedList?** 144 | _Company: OpenText_ 145 | 146 | 2. **How to print the diagonal of a square matrix in Java?** 147 | _Company: OpenText_ 148 | 149 | 3. **How do you reverse a LinkedList?** 150 | _Company: Impetus_ 151 | 152 | 4. **How do you add a node after a given node in a LinkedList?** 153 | _Company: Ordr_ 154 | 155 | 5. **Explain the producer-consumer problem.** 156 | _Company: OpenText_ 157 | 158 | 6. **What is a singleton class with double locking?** 159 | _Company: OpenText_ 160 | 161 | 7. **How do you find an anagram of a word?** 162 | _Company: Subex_ 163 | 164 | 8. **How to find palindrome numbers in an array?** 165 | _Company: Epsilon_ 166 | 167 | 9. **What is try-with-resources in Java (introduced in Java 1.7)?** 168 | _Company: Genpact_ 169 | 170 | 10. **Explain deep cloning in Java.** 171 | _Company: Genpact_ 172 | 173 | 11. **What are executors in Java?** 174 | _Company: Sear Holding_ 175 | 176 | 12. **What is a Java semaphore?** 177 | _Company: Genpact_ 178 | 179 | 13. **Explain the concept of a cyclic barrier in Java.** 180 | _Company: Genpact_ 181 | 182 | 14. **What are the key differences between Java 6 and Java 7?** 183 | _Company: Genpact_ 184 | 185 | 15. **How do you create a custom exception in Java?** 186 | _Company: Sear Holdings_ 187 | 188 | 16. **What is the difference between final, finally, and finalize in Java?** 189 | _Company: Sear Holdings_ 190 | 191 | 17. **What are iterators and list iterators in Java?** 192 | _Company: Sear Holdings_ 193 | 194 | 18. **How do you implement the Fibonacci series using recursion?** 195 | _Company: Subex_ 196 | 197 | 19. **Explain composition and aggregation in Java.** 198 | _Company: Genpact_ 199 | 200 | 20. **How do you traverse and print data from the middle to the last of a LinkedList?** 201 | _Company: KPMG_ 202 | 203 | 21. **How do you find the maximum and minimum values in a HashMap?** 204 | _Company: KPMG_ 205 | 206 | 22. **How do you reverse a string using recursion in Java?** 207 | _Company: KPMG_ 208 | 209 | 23. **What is the difference between List, Set, and HashMap in Java?** 210 | _Company: KPMG_ 211 | 212 | 24. **Can an Integer hold a null value in Java?** 213 | _Company: Sianr Mas Group_ 214 | 215 | 25. **What is the performance comparison between an interface and an abstract class?** 216 | _Company: Sianr Mas Group_ 217 | 218 | 26. **What are the Diamond Problem and SOLID principles?** 219 | _Company: Sianr Mas Group_ 220 | 221 | 27. **What is a String pool in Java?** 222 | _Company: Sianr Mas Group_ 223 | 224 | 28. **Explain block-level and method-level synchronization in Java.** 225 | _Company: Sianr Mas Group_ 226 | 227 | 29. **What is the difference between ArrayList and LinkedList in Java?** 228 | _Company: Sianr Mas Group_ 229 | 230 | 30. **Explain Comparable and Comparator in Java.** 231 | _Company: Sianr Mas Group_ 232 | 233 | 31. **What is the difference between Runnable and Callable in Java?** 234 | _Company: Syncheron_ 235 | 236 | 32. **What are executor services in Java?** 237 | _Company: Syncheron_ 238 | 239 | 33. **What are the different ways to implement a thread in Java?** 240 | _Company: Syncheron_ 241 | 242 | 34. **What is TreeMap used for in Java?** 243 | _Company: Syncheron_ 244 | 245 | 35. **What is the difference between an abstract class and an interface in Java?** 246 | _Company: GlobalLogic_ 247 | 248 | 36. **How do you implement an immutable class in Java?** 249 | _Company: GlobalLogic_ 250 | 251 | 37. **What is a ConcurrentHashMap in Java?** 252 | _Company: Virtusa_ 253 | 254 | 38. **What is the difference between HashSet and TreeSet in Java?** 255 | _Company: Virtusa_ 256 | 257 | 39. **Why do we use lambda expressions in Java?** 258 | _Company: Virtusa_ 259 | 260 | 40. **Why do we use the Stream API in Java?** 261 | _Company: Virtusa_ 262 | 263 | 41. **What happens if we make `public static void main()` private in Java?** 264 | _Company: Virtusa_ 265 | 266 | 42. **What are Executor Services in Java, and how do we initialize them?** 267 | _Company: Virtusa_ 268 | 269 | 43. **How to create a Singleton class in Java for a multi-threading environment?** 270 | _Company: Virtusa_ 271 | 272 | 44. **What is try-with-resources in Java?** 273 | _Company: Virtusa_ 274 | 275 | 45. **What is fail-fast & fail-safe?** 276 | _Company: DansakeIT_ 277 | 278 | 46. **How do you implement a Concurrent HashMap?** 279 | _Company: DansakeIT_ 280 | 281 | 47. **With two threads printing odd and even numbers, how do you print the sequence of numbers?** 282 | _Company: Rapido_ 283 | 284 | 48. **What is composition, isA, and hasA relationship in Java?** 285 | _Company: Accolite_ 286 | 287 | 49. **What is the difference between HashMap and LinkedHashMap?** 288 | _Company: Accolite_ 289 | 290 | 50. **Why is the `wait()` method part of the Object class and not the Thread class?** 291 | _Company: Accolite_ 292 | 293 | 51. **What is Auto-Boxing and Unboxing in Java?** 294 | _Company: ProKarma_ 295 | 296 | 52. **What is Deadlock & Race Condition in Java?** 297 | _Company: Walmart_ 298 | 299 | 53. **Detect if a Tree is a Binary Search Tree (BST).** 300 | _Company: JP Morgan & Chase Co._ 301 | 302 | 54. **What are the different ways to traverse a tree?** 303 | _Company: JP Morgan & Chase Co._ 304 | 305 | 55. **Traverse a tree and link siblings of nodes at the same level.** 306 | _Company: OLA Cabs_ 307 | 308 | --- 309 | 310 | ## SQL Interview Questions 311 | 1. **How do you find the nth salary from a salary table?** 312 | _Company: Impetus_ 313 | 314 | 2. **How do you find the sum of spend by an ID?** 315 | _Company: KPMG_ 316 | 317 | 3. **What is the difference between PRIMARY key and UNIQUE key?** 318 | _Company: Virtusa_ 319 | 320 | 4. **Can a PRIMARY key have a NULL value?** 321 | _Company: Virtusa_ 322 | 323 | 5. **What is the difference between INNER JOIN and OUTER JOIN?** 324 | _Company: Virtusa_ 325 | 326 | 6. **How do you find the maximum salary in each department and the name of the employee?** 327 | _Companies: HappiestMinds, Lowe's_ 328 | 329 | --- 330 | 331 | ## Network & OS Interview Questions 332 | 1. **What happens if the directory file size is 20KB, but it occupies 90GB of data? What are iNodes in UNIX?** 333 | _Company: OLA Cabs_ 334 | 335 | 2. **What is context-switching in operating systems?** 336 | _Company: OLA Cabs_ 337 | 338 | 3. **What is the difference between processes and threads?** 339 | _Company: OLA Cabs_ 340 | 341 | 4. **What is the difference between TCP/IP and UDP?** 342 | _Company: OLA Cabs_ 343 | 344 | --- 345 | 346 | ## Miscellaneous Interview Questions 347 | 1. **What is Microservices Architecture?** 348 | _Company: Walmart_ 349 | 350 | 2. **What is the difference between Authentication and Authorization?** 351 | _Company: Walmart_ 352 | --------------------------------------------------------------------------------