Some common types of data structures in Java: -Array -Linked List -Stack -Queue -Binary Tree -Binary Search Tree -Heap -Hashing -Graph
Java remains one of the most popular languages around the world, especially in financial fields. Companies like Goldman Sachs, eBay, Google, and Microsoft all hire Java developers.
Today, we’ll help you prepare for your next job interview at these and other popular companies by reviewing 50 of the most common Java data structure interview questions and answers.
By the end, you’ll have all the experience you need to answer the data structure questions that make up the bulk of most interviews.
Answer any Java interview problem by learning the patterns behind common questions.
With thousands of potential questions to account for, preparing for the coding interview can feel like an impossible challenge. Yet with a strategic approach, coding interview prep doesn’t have to take more than a few weeks. Stop drilling endless sets of practice problems, and prepare more efficiently by learning coding interview patterns. This course teaches you the underlying patterns behind common coding interview questions. By learning these essential patterns, you will be able to unpack and answer any problem the right way — just by assessing the problem statement. This approach was created by FAANG hiring managers to help you prepare for the typical rounds of interviews at major tech companies like Apple, Google, Meta, Microsoft, and Amazon. Before long, you will have the skills you need to unlock even the most challenging questions, grok the coding interview, and level up your career with confidence. This course is also available in JavaScript, Python, Go, and C++ — with more coming soon!
Get hands-on experience with all the best Java questions from across our course library.
What would you enter in the blank to run through all elements of the array?
int arr[] = {1,2,3,4};
for (int i = 0; i < _______ ; i++){
System.out.println(arr[i]);
}
Problem Statement
Implement the method int[] mergeArrays(int[] arr1, int[] arr2) that takes two chronologically sorted arrays and returns a new sorted array including all elements from the input arrays.
Solution and Explanation:
Time Complexity: where n and m are the sizes of arr1 and arr2.
In the solution above, we start by creating a new empty array of the size equal to the combined size of both input arrays.
Starting from the index 0 individually compare the elements at corresponding indexes of both arrays.
Place the element with a lower value in the resultant array, and increment the index of the array where you find the smallest element.
Keep repeating this until you hit the end of one array. Move the elements of the other array into the resultantArray as it is.
Problem Statement
Create a method int[] findSum(int[] arr, int n) that takes an integer array arr and returns an array of the two integer elements that add up to integer n.
If there are multiple, return only one. If there is no such pair, return the original array.
Solution and Explanation:
Time Complexity:
The best way to solve this is by first sorting the array.
Here, we use QuickSort to sort the array first. Then using two variables, one starting from the first index of the array and the second from size−1 index of the array.
If the sum of the elements on these indexes of the array is smaller than the given value n, then increment index from the start else decrement index from the end until the given value n is equal to the sum.
Store the elements on these indexes in the result array and return it.
Problem Statement
Create a method int findMinimum(int[] arr) that takes an array and returns the smallest element within the array.
Solution and Explanation:
Time Complexity:
Start with the first element, which is 9 in this example, and save it in minimum as the smallest value.
Then, iterate over the rest of the array and compare the minimum to each element.
If any element is smaller than the minimum, then set minimum to that element. By the end of the array, the number stored in the minimum will be the smallest integer in the whole array.
Enjoying the article? Scroll down to sign up for our free, bi-monthly newsletter.
Problem Statement
Create the method void reArrange(int[] arr) that takes an integer array and returns the same array sorted with all negative integers to the left of the middle element and all positive integers to the right.
Solution and Explanation:
Time Complexity:
In this solution, we rearrange the elements within the array rather than create a new array. To do this, we keep two variables i and j. Both of them are 0 initially.
i iterates over the array while j keeps track of the position where the next encountered negative number will be placed.
When we come across a negative number, the values at i and j indexes are swapped, and j is incremented. This continues until the end of the array is reached.
Problem Statement
Create the method void rotateArray(int[] arr) which takes an array of integers and rotates the position of each element one to the right. The right-most element will rotate to become the left-most element.
Solution and Explanation:
Time Complexity:
To rotate the array towards the right, we have to move the array elements towards the right by one index.
This means every element stored at index i will be moved to i + 1 position.
However, if we start shifting elements from the first element of the array, then the element at last index arr[arr.length - 1] is overwritten.
We fix this by saving the last element of the array in the variable lastElement.
Then we start shifting elements from index i - 1 to i, where the initial value of i will be arr.length - 1, and we will keep shifting the elements until i is greater than 0.
When the loop ends, we store the value of lastElement in arr[0].
What does the following fragment of code do?
Node currentNode = list.headNode;
while(currentNode != null){
currentNode = currentNode.nextNode;
}
Answer any Java interview problem by learning the patterns behind common questions
With thousands of potential questions to account for, preparing for the coding interview can feel like an impossible challenge. Yet with a strategic approach, coding interview prep doesn’t have to take more than a few weeks. Stop drilling endless sets of practice problems, and prepare more efficiently by learning coding interview patterns. This course teaches you the underlying patterns behind common coding interview questions. By learning these essential patterns, you will be able to unpack and answer any problem the right way — just by assessing the problem statement. This approach was created by FAANG hiring managers to help you prepare for the typical rounds of interviews at major tech companies like Apple, Google, Meta, Microsoft, and Amazon. Before long, you will have the skills you need to unlock even the most challenging questions, grok the coding interview, and level up your career with confidence. This course is also available in JavaScript, Python, Go, and C++ — with more coming soon!
Problem Statement
Create the method void insertAtEnd(T data) that will take a generic type T value called data and insert that value at the end of a linked list.
Solution and Explanation
Time Complexity:
If the list is empty, the situation is exactly like insertion at the head.
Otherwise, we can use a loop to reach the tail of the list and set our new node as the nextNode of the last node.
Problem Statement
Create the function searchNode (T data) that takes a generic type T value and searches the elements of our Singly Linked List for a node that matches T.
If it is within the linked list, return true. If value T is not in in the linked list, return false
Solution and Explanation:
Time Complexity:
In this function, we traverse through the list and check whether the currentNode’s value of data matches the searched value data.
If it does, we will return True. Otherwise, we will return False.
Problem Statement
Create the method Object nthElementFromEnd(SinglyLinkedList<T> list, int n) that takes a linked list and returns the nth element from the end of the linked list.
Solution and Explanation:
Time Complexity:
In the above solution, we first use the getter function list.getSize() to access the length of the list. Then we find the node which is at x position from the start using the equation:
Problem Statement
Create the method public static <T> void reverse(SinglyLinkedList<T> list) that will take a linked list as input and reverse its contents such that the final element from the input linked list is the first element of the output linked list.
Solution and Explanation:
Time Complexity:
The loop that iterates through the list is the key to this solution. For any current node, its link with the previous node is reversed, and the variable next stores the next node in the list:
current node’s nextNode in nextcurrent node’s nextNode to previous (reversal)current node the new previous so that it can be used for the next iterationnext to move on to the next nodeIn the end, we simply point the head to the last node in our loop.
Problem Statement
Create the method isPalindrome(DoublyLinkedList<T> list) that takes a doubly linked list and returns if the list is a palindrome (the same if written in reverse).
It will return true if the linked list is a palindrome, or false if it’s not.
Solution and Explanation
Time Complexity:
We start by taking pointers to headNode and tailNode (lines 3-4).
Next, we check for a corner-case, when the linked list is empty, an empty linked-list is a palindrome so we return true (lines 5-7).
Then, we simply traverse the linked list from both ends simultaneously and see if the traversals result in the same sequence of values (lines 8-14).
If that is not the case, the linked list is not a palindrome (lines 9-11), otherwise, it is.
Problem Statement
Create an algorithm that takes a string of multiple words and returns the same string with the words in reversed order.
Solution and Explanation:
Time Complexity:
This works in two general steps.
First, we reverse all characters in the string such that the final character becomes the first.
The final word will now be first, however, the word itself will also be in reverse order.
Next, we traverse the reversed string and now reverse each word in place.
The characters of each word will then be in the correct order while the position of each word is still reversed from the originally passed string.
Problem Statement
Write an algorithm that takes a string and finds all non-single letter palindromes within the input string.
Solution and Explanation:
Time Complexity:
For each letter in the input string, start expanding to the left and right while checking for even and odd length palindromes. Move to the next letter if we know a palindrome doesn’t exist.
We expand one character to the left and right and compare them. If both of them are equal, we print out the palindrome substring.
Problem Statement
Given an algorithm that takes a string and integer K and returns the length of the longest substring with no more than K distinct characters.
Solution and Explanation
Time Complexity:
This problem follows the Sliding Window pattern.
We can use a HashMap to remember the frequency of each character we have processed.
K distinct characters in the HashMap.K distinct characters. We will remember the length of this window as the longest window so far.K. We will shrink the window until we have no more than K distinct characters in the HashMap.Problem Statement
With a given array of characters where each character represents a fruit tree, place the maximum number of fruits in each of 2 baskets. The only restriction is that each basket can have only one type of fruit.
You can start with any tree, but you can’t skip a tree once you have started. You will pick one fruit from each tree until you cannot, i.e., you will stop when you have to pick from a third fruit type.
Write a function to return the maximum number of fruits in both the baskets.
Solution and Explanation:
Time Complexity:
This problem follows the Sliding Window pattern and is quite similar to the Longest Substring with K Distinct Characters.
In this problem, we need to find the length of the longest subarray with no more than two distinct characters (or fruit types!).
This transforms the current problem into the Longest Substring with K Distinct Characters where K=2.
Problem Statement
Given n pairs of parentheses, print all combinations of parentheses for a balanced, symmetrical pattern.
Solution and Explanation:
Time Complexity:
The key to this solution is a recursive approach. We’ll maintain counts of two variables left_braces and right_braces.
Each iteration, we’ll see if left_braces count is lower than n. If yes, we add to left_braces and recurse into the next step.
If right_braces is less than left_braces, we’ll add to right_braces and recurse.
We stop the recursion process when both left_braces and right_braces are equal to n.
Stack and Queue Data Structure Questions
n using QueueK Elements of a QueueTree Data Structure Questions
Congratulations on finishing those 50 questions!
The best way to prepare for coding interviews is the practice you’re doing right now. Soon, you’ll know all the question types you could encounter at your next interview.
To help you prepare for interviews, Educative has created the course Grokking Coding Interview Patterns in Java.
You’ll learn the 24 patterns behind every coding interview question, so you can be prepared to answer any problem you might face using Java.
Simplify your coding interview prep today! Get a structured, pattern-based approach to solving any coding interview question, without having to drill endless practice problems.
Happy learning!
What are the Types of Data Structures in Java?
How to prepare for a DSA interview?
How do I prepare for a data structure interview?