Java Interview Preparation questions and answers
Java Interview Preparation questions and answers
INTERVIEW QUESTIONS
1. What is Java? Explain its features.
2. What are the main principles of Object-Oriented Programming (OOP)?
3. Differentiate between JDK, JRE, and JVM.
4. Explain the concept of platform independence in Java.
5. What is the significance of the main method in Java?
35. What are design patterns? Name a few commonly used ones in Java.
36. Explain the Singleton design pattern and its implementation.
37. What is JDBC? How is it used in Java applications?
38. Discuss the differences between Statement and PreparedStatement.
11. What is an interface in Java, and how does it differ from an abstract
class?
• Interface: A collection of abstract methods and static constants.
• Can have default and static methods (since Java 8).
• A class can implement multiple interfaces.
Difference:
• Abstract class can have both abstract and concrete methods; an interface has abstract
methods by default (Java 7 and below).
• A class extends one abstract class but can implement multiple interfaces.
1. Two Sum: Given an array of integers, find two numbers that add up to a specific
target.
2. Reverse a String: Write a function to reverse a string without using built-in functions.
3. Palindrome Check: Determine if a given string is a palindrome.
4. Merge Two Sorted Lists: Merge two sorted linked lists and return it as a new sorted
list.
5. Longest Substring Without Repeating Characters: Find the length of the longest
substring without repeating characters.
6. Valid Parentheses: Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
7. Search in Rotated Sorted Array: Search for a target value in a rotated sorted array.
8. Container With Most Water: Given n non-negative integers, find two lines that
together with the x-axis form a container, such that the container contains the most
water.
9. 3Sum: Find all unique triplets in the array which gives the sum of zero.
10.Remove Nth Node From End of List: Remove the n-th node from the end of a
linked list and return its head.
11.Maximum Subarray: Find the contiguous subarray with the largest sum.
12.Climbing Stairs: You are climbing a staircase. It takes n steps to reach the top. Each
time you can either climb 1 or 2 steps. In how many distinct ways can you climb to
the top?
13.Set Matrix Zeroes: Given a m x n matrix, if an element is 0, set its entire row and
column to 0.
14.Group Anagrams: Given an array of strings, group anagrams together.
15.Merge Intervals: Given a collection of intervals, merge all overlapping intervals.
16.Linked List Cycle: Given a linked list, determine if it has a cycle in it.
17.Implement Stack using Queues: Implement a last-in-first-out (LIFO) stack using
only two queues.
18.Minimum Window Substring: Given two strings s and t, find the minimum window
in s which will contain all the characters in t.
19.Word Search: Given a 2D board and a word, find if the word exists in the grid.
20.Longest Increasing Subsequence: Find the length of the longest increasing
subsequence in an array.
21.Decode Ways: A message containing letters from A-Z is encoded to numbers using
'A' -> 1, 'B' -> 2, ..., 'Z' -> 26. Given an encoded message, determine the total number
of ways to decode it.
22.Coin Change: Given coins of different denominations and a total amount of money,
find the fewest number of coins needed to make up that amount.
23.House Robber: Given a list of non-negative integers representing the amount of
money of each house, determine the maximum amount of money you can rob tonight
without alerting the police.
24.Binary Tree Inorder Traversal: Given a binary tree, return the inorder traversal of
its nodes' values.
25.Validate Binary Search Tree: Determine if a given binary tree is a valid binary
search tree.
26.Lowest Common Ancestor of a Binary Tree: Given a binary tree, find the lowest
common ancestor of two given nodes in the tree.
27.Serialize and Deserialize Binary Tree: Design an algorithm to serialize and
deserialize a binary tree.
28.Kth Smallest Element in a BST: Find the kth smallest element in a binary search
tree.
29.Number of Islands: Given a 2D grid of '1's (land) and '0's (water), count the number
of islands.
30.Course Schedule: There are a total of numCourses you have to take, labeled from 0
to numCourses-1. Some courses may have prerequisites. Determine if you can finish
all courses.
31.Implement Trie (Prefix Tree): Implement a trie with insert, search, and startsWith
methods.
32.Add and Search Word - Data structure design: Design a data structure that
supports the addition of words and the search for a word in a dictionary.
33.Word Ladder: Given two words (beginWord and endWord), and a dictionary's word
list, find the length of the shortest transformation sequence from beginWord to
endWord.
34.Find Median from Data Stream: The median is the middle value in an ordered
integer list. Write a program that finds the median of input data stream.
35.Sliding Window Maximum: Given an array and an integer k, find the maximum for
each sliding window of size k.
36.Longest Consecutive Sequence: Given an unsorted array of integers, find the length
of the longest consecutive elements sequence.
37.Graph Valid Tree: Given n nodes labeled from 0 to n-1 and a list of undirected
edges, determine if these edges form a valid tree.
38.Number of Connected Components in an Undirected Graph
PROGRAMS
1. Two Sum
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
return new int[] {};
}
2. Reverse a String
public String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}
3. Palindrome Check
public boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left++) != s.charAt(right--)) return false;
}
return true;
}
6. Valid Parentheses
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else if (!stack.isEmpty() &&
((c == ')' && stack.peek() == '(') ||
(c == '}' && stack.peek() == '{') ||
(c == ']' && stack.peek() == '['))) {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
private boolean dfs(char[][] board, String word, int i, int j, int index) {
if (index == word.length()) return true;
if (i < 0 || j < 0 || i >= board.length || j >= board[0].length ||
board[i][j] != word.charAt(index)) return false;
char temp = board[i][j];
board[i][j] = '#';
boolean found = dfs(board, word, i + 1, j, index + 1) ||
dfs(board, word, i - 1, j, index + 1) ||
dfs(board, word, i, j + 1, index + 1) ||
dfs(board, word, i, j - 1, index + 1);
board[i][j] = temp;
return found;
}
class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
class TrieNode {
private TrieNode[] links;
private final int R = 26;
private boolean isEnd;
public TrieNode() {
links = new TrieNode[R];
}
class WordDictionary {
private TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
class MedianFinder {
private PriorityQueue<Integer> small = new
PriorityQueue<>(Collections.reverseOrder());
private PriorityQueue<Integer> large = new PriorityQueue<>();
class UnionFind {
private int[] parent;
public UnionFind(int n) {
parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
}
public int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
public boolean union(int x, int y) {
int rootX = find(x), rootY = find(y);
if (rootX == rootY) return false;
parent[rootX] = rootY;
return true;
}
}