Data Structures and Algorithm Interview Questions for Java Programmers
Data structures and algorithm questions are important part of any programming job interview, be it a Java interview, C++ interview or any other programming language. Since data structures is core programming concept, its mandatory for all programmers, to know basic data structures like stack, linked list, queue, array, tree and graph. Though tree and graph are on tough side, I still see programmers to get familiar will all these.
Any list of programming job interview questions is incomplete without questions from data structures and algorithms. Similarly while going on questions from data structure you may get some programming exercise as well e.g. swapping numbers without temp variable . Linked list and arrays are favorite topics in any data structure interview, questions like reversing linked list, traversing linked list or deleting nodes from linked list, which involves algorithm and data structures are quite common. Similarly, finding duplicates in array, finding missing numbers, sorting arrays are very popular. You can also expect questions from stack, queue, array, linked list, tree, graph and HashMap are most common in any data structure interview. In this tutorial, we will see couple of data structure questions answers from these topic. Let us know, if you have any interesting questions from data structures and algorithm, which you faced during any Java interviews.
This is combined list of questions from various data structure e.g. array, linked list, stack or queue. It includes some coding questions as well, which gel with data structures.
- How to find middle element of linked list in one pass?
One of the most popular question from data structures and algorithm, mostly asked on telephonic interview. Since many programmer know that, in order to find length of linked list we need to first traverse through linkedlist till we find last node, which is pointing to null, and then in second pass we can find middle element by traversing only half of length. They get confused when interviewer ask him to do same job in one pass. In order to find middle element of linked list in one pass you need to maintain two pointer, one increment at each node while other increments after two nodes at a time, by having this arrangement, when first pointer reaches end, second pointer will point to middle element of linked list. See this trick to find middle element of linked list in single pass for more details.
- How to find if linked list has loop?
This question has bit of similarity with earlier algorithm and data structure interview question. I mean we can use two pointer approach to solve this problem. If we maintain two pointers, and we increment one pointer after processing two nodes and other after processing every node, we are likely to find a situation where both the pointers will be pointing to same node. This will only happen if linked list has loop.
- How to find 3rd element from end in a linked list in one pass?
This is another frequently asked linked list interview question. This question is exactly similar to finding middle element of linked list in single pass. If we apply same trick of maintaining two pointers and increment other pointer, when first has moved upto 3rd element, than when first pointer reaches to the end of linked list, second pointer will be pointing to the 3rd element from last in a linked list.
- In an integer array, there is 1 to 100 number, out of one is duplicate, how to find?
This is a rather simple data structures question, especially for this kind of. In this case you can simply add all numbers stored in array, and total sum should be equal to n(n+1)/2. Now just subtract actual sum to expected sum, and that is your duplicate number. Of course there is a brute force way of checking each number against all other numbers, but that will result in performance of O(n^2) which is not good. By the way this trick will not work if array have multiple duplicates or its not numbers forming arithmetic progression. Here is example of one way to find duplicate number in array.
- How to reverse String in Java ?
This is one of my favorite question. Since String is one of the most important type in programming, you expect lot of question related to String any data structure interview. There are many ways to reverse Sting in Java or any other programming language, and interviewer will force you to solve this problem by using without API i.e. without using reverse() method of StringBuffer. In follow-up he may ask to reverse String using recursion as well. See 3 ways to reverse String in Java to learn reversing String using both loops and recursion in Java.
- Write a Java program to sort a array using Bubble Sort algorithm?
I have always send couple of questions from searching and sorting in data structure interviews. Bubble sort is one of the simplest sorting algorithm but if you ask anyone to implement on the spot it gives you an opportunity to gauge programming skills of a candidate. See How to sort array using Bubble Sort in Java for complete solution of this datastrucutre interview question.
- What is difference between Stack and Queue data structure?
One of the classical datastrucutre interview question. I guess every one know, No? Any way main difference is that Stack is LIFO(Last In First Out) data structure while Queue is a FIFO(First In First Out) data structure.
- How do you find duplicates in array if there is more than one duplicate?
Sometime this is asked as follow-up question of earlier datastrucutre interview question, related to finding duplicates in Array. One way of solving this problem is using a Hashtable or HashMap data structure. You can traverse through array, and store each number as key and number of occurrence as value. At the end of traversal you can find all duplicate numbers, for which occurrence is more than one. In Java if a number already exists in HashMap then calling get(index) will return number otherwise it return null. this property can be used to insert or update numbers in HashMap.
- What is difference between Singly Linked List and Doubly Linked List data structure?
This is another classical interview question on data structure, mostly asked on telephonic rounds. Main difference between singly linked list and doubly linked list is ability to traverse. In a single linked list, node only points towards next node, and there is no pointer to previous node, which means you can not traverse back on a singly linked list. On the other hand doubly linked list maintains two pointers, towards next and previous node, which allows you to navigate in both direction in any linked list.
- Write Java program to print Fibonacci series?
This is not a data structures question, but a programming one, which many times appear during data structure interview. Fibonacci series is a mathematical series, where each number is sum of previous two numbers e.g. 1,1, 2, 3, 5, 8, 13, 21. Interviewer is often interested in two things, a function which returns nth number in Fibonacci series and solving this problem using recursion in Java. Though, its easy question, recursion part often confuses beginners. See this link to find nth Fibonacci number in Java.
- Write Java program to check if a number is palindrome or not?
This is similar to previous question, not directly related to data structures, but quite popular along with other questions. A number is called palindrome, if reverse of number is equal to number itself. Interviewer ask to solve this problem without taking help from Java API or any open source library. Any way it’s simple question, you can use division operator (/) and remainder operator (%) to solve this question. Just remember, division operator can be used to get rid of last digit e.g. 1234/10 will give you 123, and modulus operator can give you last digit e.g. 1234%10 will return 4. By the way, here is a Java program check if number is palindrome or not.
- What is binary search tree?
This is a data structure question from Tree data structures. Binary Search Tree has some special properties e.g. left nodes contains items whose value is less than root , right sub tree contains keys with higher node value than root, and there should not be any duplicates in the tree. Apart from definition, interview can ask you to implement binary search tree in Java and questions on tree traversal e.g. IN order, preorder, and post order traversals are quite popular data structure question.
- How to reverse linked list using recursion and iteration?
This is another good question on data structures. There are many algorithm to reverse linked list and you can search of them using google. I am thinking of writing another blog post to explain linked list reversal and will share with you later.
- Write a Java program to implement Stack in Java?
You can implement Stack by using array or linked list. This question expect you to implement standard method provided by stack data structure e.g. push() and pop(). Both push() and pop() should be happen at top of stack, which you need to keep track. It’s also good if you can implement utility methods like contains(), isEmpty() etc. By the way JDK has java.util.Stack class and you can check it’s code to get an idea. You can also check Effective Java book, where Josh Bloch has explains how an incorrect implementation of stack can cause memory leak in Java.
That's all on this list of data structure interview questions and answers. This is one topic, which is always asked in any programming interview, doesn't matter if you are C, C++, or Java developer, basic knowledge of data structure like array, linked list, stack, queue, tree are must to clear any programming interview.
- The N by N Queens Problem
In chess, a queen can move as far as she pleases, horizontally, vertically, or diagonally. A chess board has 8 rows and 8 columns. The standard 8 by 8 Queen's problem asks how to place 8 queens on an ordinary chess board so that none of them can hit any other in one move.
Besides being an amusing puzzle this problem is interesting because kids love it and it's a great teaching tool in the upper grades of Elementary School. It also provides great programming exercises.
One solution - the prettiest in my opinion - is given in the figure nearby. It turns out that there are 12 essentially distinct solutions. (Two solutions are not essentially distinct if you can obtain one from another by rotating your chess board, or placing in in front of a mirror, or combining these two operations.)
Even though the solution shown here looks pretty natural and straightforward, it is not that simple to find any others, or even this one if I hadn't displayed it here. As an exercise you may want to find the other solutions. If you are impatient, you can look them up by clicking here. Our particular solution is configuration 10.
An obvious modification of the 8 by 8 problem is to consider an N by N "chess board" and ask if one can place N queens on such a board. It's pretty easy to see that this is impossible if N is 2 or 3, and it's reasonably straightforward to find solutions when N is 4, 5, 6, or 7. The problem begins to become difficult for manual solution precisely when N is 8. Probably the fact that this number coincidentally equals the dimensions of an ordinary chess board has contributed to the popularity of the problem.
The interactive applet on this page let's you find solutions of the N by N Queen's Puzzle for arbitrary values of N. You may find it interesting to watch your computer find the solutions.
- Tower Of Hanoi Algorithm
You can find the complete Java source code for Tower of Hanoi algorithm. Given the number of discs as input, you can get the print out of the list of steps you need to solve the problem.
This program is developed in Java application and takes the number of discs as input. It uses recursive logic to find the number of steps required to solve thr problem. Initially the discs are getting added into the stack. I have 3 stacks A, B and C for 3 towers A, B and C. The function SolveTOH is used to compute all possible steps to solve the problem. Note that it uses the recursive logic and the output after each move is written on the screen.
The Big O notation for this problem is: 2^n - 1.