Java Coding Interview QuestionsIn this tutorial, we are going to discuss a few popular Coding Interview Questions. Practicing the problems provided in this article will help in improving coding skills. The tutorial is helpful for the experienced as well as the fresher candidate. It also covers the complexity analysis and corner cases to give an idea to candidates how to deal with it. 1) Write a Java program for generating the nth Fibonacci Number using loop and O(1) space.In a Fibonacci series, the value of any term is the sum of the values of the last two terms. For example, if we want to compute the 3rd term of the series, then it is the sum of the 1st and the 2nd term. Note that the first two terms of the Fibonacci series are defined as 0 and 1. Thus, the 3rd term will be 0 + 1 = 1. The 4th term will be the sum of the 3rd and the 2nd terms, 1 + 1 = 2. The 5th term will be the sum of the 4th and the 3rd term, which is 2 + 1 = 3. Thus the Fibonacci series looks like the following. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, … (considering 1 - indexing) Therefore, in general, the nth term of the series can be written as F(n) = F(n - 1) + F(n - 2) Now, we can write the program for computing the nth term of the Fibonacci series as follows. Note that the value of n will be provided by the user. FileName: FibonacciSeries.java Input: Output: The 6th Fibonacci number is: 5 Complexity Analysis: The program takes O(n) time to compute the value of the Nth term of the Fibonacci series. The space complexity of the program is O(1), as no extra space is being used. Corner Cases: The corner of this problem is handling the negative values of N, which we have done in the if-condition. In a lot of cases, it is seen that candidates miss the handling of negative values of n. Follow-up: One can also solve this problem with the help of dynamic programming. It will consume O(n) time and O(n) space. Readers are advised to try it themselves. 2) Write a Java program for counting the digits present in a number.If we take a number 5647, we find that the number consists of 4 digits that are 5, 6, 4, and 7. When can find the total number of digits present in a number by consistently dividing the given number by 10 using a loop, till it becomes zero. In the loop, we keep incrementing a counter in each iteration. Observe the implementation in the following code. FileName: CountDigits.java Input: Output: The total digits in number 0 are: 1 Input: Output: The total digits in number -980 are: 3 Input: Output: The total digits in number 1983 are: 4 Complexity Analysis: The time complexity of the program is O(log_{10}(n)), where n is the input number. The space complexity of the program is O(1) because the program is not using any extra space. Corner Cases: Observe the loop mentioned in the above program. Its terminating condition is when n != 0. So, what will happen if the input number is 0? For the number 0, separate handling is required to give answer 1. Also, we have to take care of the numbers that are negative. 3) Calculate how many times a digit D occurs in the number N. One has to ask the user to give the values of N and D.The question is a modified form of the previous question. So, tweaking the above code will do the job for us, and the same is evident by looking at the following code. FileName: CountDigitsD.java Input: Output: The total count of digit 1 occurring in the number 121 is: 2 Input: Output: The total count of digit 9 occurring in the number -9931929 is: 4 Input: Output: The total count of digit 0 occurring in the number 0 is: 1 Complexity Analysis: The time complexity of the program is O(log_{10}(n)), where n is the input number. The space complexity of the program is O(1), because the program is not using any extra space. Corner Cases: We have to take care of cases when N and D both are 0. Also, we have to deal with situations when the user inputs a negative number. 4) Compute the value of an using recursion. It is not allowed to use any extra space apart from the recursion call stack.In a recursion, one needs to look for the relation between the larger problem and the smaller problem. In this problem, there is a relationship between the larger and the smaller problem. See the following mathematical relation. a^{n} = a x a^{n - 1} In the programming world, we can write the above as: (a to the power n) = a x (a to the power n - 1) For example, 3 to the power 4 = 81. It can be computed as 3 x (3 to the power 3) = 3 x 27 = 81. FileName: PowerN.java Input: Output: The value of 2.2 ^ 2 is: 4.840000000000001 Input: Output: The value of 3.33 ^ -4 is: 0.008132481162283954 Input: Output: The value of 0.0 ^ 1 is: 0.0 Complexity Analysis: The time complexity of the program is O(n), where n is the input number serving the power of number y. The space complexity of the program is O(1) because the program is not using any extra space. Corner Cases: We have to take care of cases when power is negative. 5) A string is given. Our task is to write a Java program to toggle the characters of the given string. For example, for the string "jaVaTpoiNt", the string after the toggle will be "JAvAtPOInT".It is a well-known fact that strings are immutable in Java. Therefore, it is required to create a new string. For toggling, we can use ASCII value, 'a' can be converted to 'A' by 'A' = 'a' - 32. Code For Toggling the Cases. FileName: ToggleString.java Input: Output: After toggling, the string jaVaTpoiNt becomes: JAvAtPOInT Input: Output: After toggling, the string J78trY becomes: j78TRy Complexity Analysis: The time complexity of the program is O(num). The space complexity of the program is also O(num) because the program is using extra for creating a new string, and num is the total number of characters present in the input string. Corner Cases: We have to take care of cases when the characters of the input string do not contain small capital letters. For example, consider the string "ut8Pmn". In this string, characters 'u', 't', 'P', 'm', 'n' gets toggled to 'U', 'T', 'p', 'M', and 'N'. However, character 8 can never be toggled as there is nothing called small 8 and capital 8. Therefore, this case requires special handling. 6) Write a Java program for printing all of the unique characters present in a String. For instance, for the string "pppdaf", print characters 'd', 'a', and 'f' since they are unique. The character 'p' is coming thrice in the program. Hence, it is not printed. It is given only small letters are present in the input string.We can create an integer array of the size 256 as there are 256 characters present in the input string. Now, we count the frequency of occurrence of every character present in the input string and update the integer array accordingly. Now iterate over the integer array to check which element has the value 1. The character corresponding to that element index is printed on the console. Note that the 0^{th} index of the array maps to 'a', the 1^{st} index maps to 'b', and so on. FileName: UniqueChar.java Input: Output: The unique characters present in the string: 'pppdaf' are: a d f Input: Output: There is no unqiue characters present in the string: 'jjgtrygtry' Complexity Analysis: The time complexity of the program is O(num), where num is the total number of characters present in the input string. The space complexity of the program is constant, even though we are using an integer array. Note that the size of the input array is constant. Corner Cases: We have to take care of cases when a null string is passed, or when a string is passed that has all the duplicate characters. We have to handle that case separately. 7) Write a program in Java to prove that the strings are immutable in Java.In order to check that strings are immutable in Java, we have to use the == operator. It is because the == compares the references or the addresses of the objects. If, after making a change in the string and comparing it with the unchanged one and we get a true value, then it means strings are not immutable; otherwise, they are immutable. True value means the changed string has the same address as compared to the previous one. The following program shows the immutability of strings. FileName: ImmutableStrings.java Output: Strings are immutable. 8) Print reverse array in Java using recursion for the given input array without using any extra space. Ignore the implicit stack used in recursion for computing the space complexity.FileName: ReverseArrUsingRec.java Input: Output: The input array is: 8 5 90 23 The reversed array is: 23 90 5 8 Input: Output: The input array is: 45 12 21 78 60 66 The reversed array is: 66 60 78 21 12 45 Complexity Analysis: The time complexity of the program is O(num), where num is the total number of elements present in the input array. The space complexity of the program is constant, which is O(1). 9) Write a Java program for finding the index of the first as well as the last occurrence of an element in the array using linear time without using any extra space. Consider one indexing.FileName: FindEle.java Input: Output: For the target element: 60, First Index = 5 Last Index = 7 Input: Output: For the target element: 12, First Index = 2 Last Index = 2 Input: Output: In the input array, the element 27 does not exist. Complexity Analysis: The time complexity of the program is O(num), where num is the total number of elements present in the input array. The space complexity of the program is constant, which is O(1). Corner Case: We have to take care of the case where the target element is not present in the array. It is because the index of the element becomes irrelevant if the element is absent. 10) Write a Java program to display the elements of the matrix in the Wave Order as mentioned below. (The matrix can have different numbers of columns and rows).By observing the image, it is evident that for columns that are even, the traversal is top to down, and when the columns are odd, the traversal is bottom to top direction. FileName: WaveOrder.java Input: Output: The wave order traversal of the input matrix is: 4 9 5 6 0 3 1 7 2 Input: Output: The wave order traversal of the input matrix is: 41 49 51 76 32 16 20 13 21 27 62 29 63 36 12 30 Complexity Analysis: The time complexity of the program is O(r x c), where r is the row size and c is the column size. The space complexity of the program is constant, which is O(1). 11) Implement a class "Developer". Write some methods and properties to it and find how one will use them in the main method by instantiating the class.Observe the following example. FileName: TestClass.java Output: Shiva writes code. Shiva drinks tea and then convert the quadratic complexity codes to linear. Explanation: Some things you should keep in mind: The properties must usually be set private, and we should have getter and setter methods to access and modify them. This is good OOPS practice. Also, always create a default constructor, as when we create a parameterized constructor, Java removes its own default constructor, and object creation without passing the parameters to the constructor would not be possible. 12) Write a Java program to count the consonants and vowels present in the input string. The string may contain numeric characters, and only lowercase letters are allowed in the input string.FileName: CountVowelConst.java Input: Output: Count of vowels in the String : 'abcd44iut' is: 3 Count of consonants in the String : 'abcd44iut' is: 4 Count of other characters in the String : 'abcd44iut' is: 2 Input: Output: Count of vowels in the String : 'aoiue' is: 5 Count of consonants in the String : 'aoiue' is: 0 Count of other characters in the String : 'aoiue' is: 0 Input: Output: Count of vowels in the String : 'aoiue' is: 5 Count of consonants in the String : 'aoiue' is: 0 Count of other characters in the String : 'aoiue' is: 0 Input: Output: Count of vowels in the String : '@51#$%290(){}' is: 0 Count of consonants in the String : '@51#$%290(){}' is: 0 Count of other characters in the String : '@51#$%290(){}' is: 13 Corner Cases: One might miss the case that what will happen if the string contains some numbers or special characters like '0', '5', '#', '@', etc. These characters are neither vowels nor consonants. For characters like these, separate handling is required. Generally, candidates find the vowels count and then subtract it from the size of the string to find consonants, which will give the wrong result if the string contains some characters that are not alphabetical. Complexity Analysis: The time complexity of the program is O(n), where n is the total number of characters present in the input string. The space complexity of the program is O(1) as the program uses the array of size 5, which will not change if we change the input string. 13) Write a Java program to demonstrate inheritance.The following program demonstrates inheritance with the help of extends keyword. The following program shows a SmartPhone class that extends the Mobile class and has the features like playing and stopping music player, making a call, taking photos, etc. FileName: TestInheritance.java Output: Count of vowels in the String : '@51#$%290(){}' is: 0 Phone number is: 94863472 Calling the dialled number. Music is getting Played. Music player Paused. Music player Stopped. A photo is clicked. 14) Demonstrate the basic "divide by 0 exception" with the help of a Java program.The divide by zero exception occurs when we try to divide a number by 0 in Java. The illustration of the same is mentioned in the following program. FileName: DivideByZeroException Input: Output: The number 3 is divided by zero. java.lang.ArithmeticException: / by zero Program is completed. Note: In the above program, the try-catch block is used for handling the divide-by-zero exception. Therefore, the program is executed completely. Otherwise, the program would have stopped at the point of exception, and the print statement (Program is completed) would not have been executed.15) Demonstrate single thread with the help of a Java program.FileName: MainThreadDemo.java Output: Thread[The Main Thread,7,main] The Main Thread 7 16) A string is given to us. Write a program to check whether the string is a palindrome or not. The string can contain white spaces, small and capital letters, and other characters too. Note that the program should be case-insensitive and should ignore the white space and other special characters. For example, a and A will be considered the same character. Also, "a&* A" is a palindrome because we ignore the &,*, and white spaces. Thus, "a&* A" can be written as "aa" as 'a' and 'A' both are the same as far as this question is concerned.The approach is to traverse the whole string and remove all those characters that are not alphanumeric. Also, remove the white space. Convert all the alphabetical letters to either small or capital letters. After that, with the help of a loop, check whether the updated string is the palindrome or not. FileName: CheckPalindrome.java Input: Output: The string 'a&* B BA b' is not a palindrome. Input: Output: The string 'a&* B BA bB a' is a palindrome. Corner case: It is important to note that we have to convert all the alphabets to either small or capital letters. Also, we need to take care of the case when the user inputs a string that consists of only white spaces. In our case, a string containing only white spaces should be a palindrome. Complexity Analysis: The time complexity of the program is O(n), where n is the total number of characters present in the string. The space complexity of the program is constant, i.e., O(1). 17) Two binary strings are given to us. Write a Java program to add the given binary string as per the binary addition rules and display the resulting binary string. Note that input strings only contain 0s and 1s and nothing else.Rules for the binary addition are mentioned below.
It is evident by looking at the fourth rule that whenever the result exceeds 1, the answer of addition becomes zero, and carry is 1. shows that whenever the result exceeds 1, the answer of addition becomes 0 and carry becomes 1. Using these four rules, we will do the addition starting from the rightmost index and will move towards the first or the leftmost index. The illustration of it is mentioned in the following program. FileName: AddBinaryStrings.java Input: Output: The addition of binary strings is: 11101 Input: Output: The addition of binary strings is: 100000 Input: Output: The addition of binary strings is: 1000110 Corner case: It is important to note that the user can enter strings of any length. It is not mentioned in the question that input strings will be of the same length. Therefore, the length of the first string can be either less or more or equal to the length of the second string. Also, one should note that the final answer may or may not contain an extra bit. For example, 100 + 1 = 101 but, 111 + 111 = 1000. 1000 contains one more bit as compared to the input stings. Complexity Analysis: The time complexity of the program is O(max(m, n)), where m is the total number of characters present in the first input string, and n is the total number of characters present in the second input string. The space complexity of the program is constant, i.e., O(1). 18) Two strings are given as input. Write a Java program to check whether they are anagrams or not. Two strings are considered anagrams if they have the same characters occurring the same number of times. However, the order in which they occur may or may not be different. For example: "javatpoint", and "ttaaniojvp" are considered as anagrams. Each character presents in "javatpoint" are also there in "ttaaniojvp". Also, the characters which are not present in "javatpoint" are also not there "ttaaniojvp".We will be using HashMap to store the number of times the characters occur in the first string. Note that character will be the key, and the number of times it occurs is its value. After that, we will traverse the second string and start reducing the frequency of occurrence of characters stored in the HashMap. If the frequency is already zero or the character is absent in the HashMap, we can say that the strings are not anagrams; else, they are anagrams. FileName: StringAnagrams.java Input: Output: Strings 'javatpoint' & 'ttaaniojvp' are anagrams. Input: Output: Strings 'india' & 'ddiaaa' are not anagrams. Corner Cases: It is necessary to check whether the strings are of the same length or not. If not, we can say that the given strings are not anagrams. Complexity Analysis: The time complexity of the program is O(m + n), where m and n are the sizes of the two strings. The space complexity of the program is O(1). 19) You are given a sorted array of unique integers. It is given that each element in the array is unique. Also, an element is given. Write a Java program to find the index of the element present in the array. If the element is not present in the array, then find the index where it should be put in the array so that the array remains sorted even after putting the element. Note that the program should be optimized in terms of space and time complexity. Consider zero indexing.It is given in the problem that the array is sorted. So, the best approach is to apply the binary search. The following code is an illustration of it. FileName: SortedArrayIndex.java Output: For the input array: 2 6 9 13 24 35 78 90 99 The index of the target element 7 is: 2 For the input array: -3 5 24 40 51 80 89 97 The index of the target element 51 is: 4 Complexity Analysis: The time complexity of the program is O(log_{2}(nums)), where nums is the total number of elements present in the input array. The space complexity of the program is O(1), as the program is not using any extra space. 20) An integer array is given to us. Write an optimized Java program to wave-sort the given array.The main objective is to generate the wave graph. It can be achieved by generating the peaks in the input array or looking at valley generation in the input array. So, we will try to make peaks in the array. We want the first element as the peak element, so the first element remains untouched, and we begin from the second index, leave it as it is and start from the index = 2. Here, since we want to generate a peak, we need to have the next and previous elements greater than the second element. In the similar fashion, we will have the fourth element smaller than the third and the fifth element. Thus, we need to take a jump of 2 indices every time until we reach the end of the given array. FileName: WaveSort.java Output: The input array is: 19 18 16 13 14 17 12 After the wave sort 19 16 18 13 17 12 14 The input array is: -45 45 -50 -60 0 34 9 12 After the wave sort 45 -50 -45 -60 34 0 12 9 Complexity Analysis: The time complexity of the program is O(nums), where nums is the total number of elements present in the input array. The space complexity of the program is O(1), as the program is not using any extra space. Corner Case: In the code, the previous and the next element are getting swapped; thus, it is required to take care of the index out-of-bounds condition. Note 1: The output shown above is not the only answer. For this problem, there can be other answers too. One has to show any one of them.Note 2: Another solution is to sort the array and then swap the adjacent element to get the answer. However, it can lead to O(nums * log(nums)) time complexity, and the solution provided above is more optimized and has O(nums) time complexity. Therefore, the sorting approach is not discussed above, as we have to write the most optimized program.21) Create a user-defined exception and demonstrate its working (when it raises an exception) with the help of a Java program.In the following program, A class called LowBalanceExcptn is created for the bank. Therefore, when a person creates a bank account, the minimum balance the person should maintain Rs. 7000. Therefore, when the bank balance becomes less than Rs. 7000, the exception is raised. The illustration of the same is mentioned below. FileName: BankBlance.java Output: The account can't be created. Account has the low balance: The bank balance can never be less than Rs.7000/- The account has been created and the bank balance has set to: 7000 The bank account is created and the balance is set to: 10000 account - 1 balance = 0 account - 2 balance = 7000 account - 3 balance = 10000 22) Show Multiple Inheritance using a Java program.In Java, it is not possible to have multiple inheritance. Therefore, we need to take the help of interfaces to make a multiple inheritance scenario. In the following example, a class called DemoClass is created that implements multiple interfaces, and by doing this, multiple inheritance is achieved. FileName: TestClass.java Output: Default Interface1 Default Interface2 Now Executing methods showOfInterface1() showOfInterface2() Default Interface1 Default Interface2 Note: If one removes the default method implementation from the class "TestClass", a compilation error is raised. If there exists a diamond through interfaces, then it is not an issue if the middle interfaces is not providing implementation of the topmost interface. If the middle interfaces provide an implementation, then the implementation can be fetched using the keyword super keyword.23) Demonstrate nesting of classes using a Java program.Defining a class inside another class is known as nesting of classes. Usually, in Java, the inner class is the static class. Observe the following program. FileName: NestedClass.java Output: The parameterized constructor of the Outer class is invoked. The parameterized constructor invoked of the second inner class. Z = 40 101 The parameterized constructor invoked of the third inner class. Z = 409 24) Demonstrate the Diamond Problem using a Java program.A diamond problem is a problem of multiple inheritances where one class extends two or more classes. In other words, when a child class has more than one parent class, then an error occurs. The diamond problem using a Java program is discussed below. FileName: DiamondProblem.java Output: /DiamondProblem.java:28: error: '{' expected class GC1 extends C1,C2 ^ 1 error Explanation: The problem with the above code is when we override the display() method in class GC1 which method is overridden, the compiler does not know whether the class C1 display() method is overridden or of the class C2 display() method is overridden. 25) Demonstrate the operations isAlive() or join() in the multithreading.The method isAlive() gives information about a thread, whether it is terminated or alive. These terminated and alive are the thread states in Java. Also, the operation join() joins a thread with another, which means that a thread will have to wait for the completion of the thread to which it is joined, even if the thread has accomplished its own work. Together both will terminate. FileName: DemoClass.java Output: Thread id: 14 Thread name: first Thread Thread priority: 10 Thread State: RUNNABLE Thread alive: false 1 2 3 4 5 6 26) Demonstrate Thread Synchronization using a Java program.We can achieve thread synchronization with the help of the synchronization keyword. The following is an example program. FileName: ThreadSynchronization.java Output: 11 22 33 44 55 66 77 88 99 110 12 24 36 48 60 72 84 96 108 120 27) Demonstrate a deadlock scenario with the help of a Java program.Whenever there is a scenario where two or more than two threads are locked forever, then that scenario is a deadlock scenario. Deadlocks usually occur in a multi-threaded environment. The following program gives demonstration of a deadlock scenario: FileName: ThreadSynchronization.java Output: th1 is taking control on the lock java.lang.Object@256f00b6 th1 acquired the lock on java.lang.Object@256f00b6 th2 is taking control on the lock java.lang.Object@5cdddb56 th2 acquired the lock on java.lang.Object@5cdddb56 th3 is taking control on the lock java.lang.Object@248f4cc7 th3 acquired the lock on java.lang.Object@248f4cc7 Explanation: All of the three threads are able to take a lock on the first object. But, they are also using the resources that is shared and are started in a way that the threads keep on indefinitely waiting in order to acquire the lock on the second object. 28) Solve the Sudoku puzzle with the help of a Java program.A sudoku puzzle is a popular Japanese puzzle that is based on the logical positioning of numbers from 1 to 9. The task is to fill the 9 x 9 grid with numbers from 1 to 9 such that all columns, rows and sub-grids (there will be 9 sub-grids of 3 x 3) contain each number from 1 to 9 with zero repeats. The program for solving the sudoku is mentioned below. FileName: Sudoku.java Output: 5 3 4 6 7 8 9 1 2 6 7 2 1 9 5 3 4 8 1 9 8 3 4 2 5 6 7 8 5 9 7 6 1 4 2 3 4 2 6 8 5 3 7 9 1 7 1 3 9 2 4 8 5 6 9 6 1 5 3 7 2 8 4 2 8 7 4 1 9 6 3 5 3 4 5 2 8 6 1 7 9 Time complexity: In the worst case, it is required to put every number in the empty cell and check whether it is a valid one or not. Thus, there are 9 choices for every cell, making the time complexity O(9^(n x n)). Auxiliary Space: O(n x n). |