Deloitte Java Developer Interview Questions and Answers
Deloitte is a global leader in consulting and professional services, offering numerous opportunities for tech professionals, including Java developers. Securing a role as a Java developer at Deloitte is a significant milestone for developers at any stage of their career. The interview process at Deloitte is structured to assess several key areas. It evaluates your technical proficiency in Java, including your problem-solving skills, understanding of best practices, and ability to contribute to complex projects. In this Deloitte Java developer interview questions guide, we will break down the types of questions you can expect based on your experience level to help you prepare for your next Deloitte interview.
Deloitte Java Developer Interview Questions for Freshers
For fresh graduates stepping into the tech industry, interviewing at Deloitte is an exciting chance to launch your career. This section of Deloitte Java developer interview questions focuses on essential questions that assess foundational Java knowledge, basic programming concepts, and analytical thinking.
Q1. How do you reverse a string in Java without using built-in methods?
Sample Answer: Reversing a string can be done manually by iterating through the characters and constructing the reverse sequence. For example:
public static String reverseString(String str) {
StringBuilder reversed = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
reversed.append(str.charAt(i));
}
return reversed.toString();
}
System.out.println(reverseString("hello")); // Output: olleh
Q2. Write a Java program to check if a number is even or odd.
Sample Answer: You can determine if a number is even by checking if it is divisible by 2. For example:
public static String checkEvenOdd(int num) {
return (num % 2 == 0) ? "Even" : "Odd";
}
System.out.println(checkEvenOdd(5)); // Output: Odd
Q3. Given an array, find the maximum element in Java.
Sample Answer: You can find the maximum element in an array by iterating through the array and comparing each element. Here is an example of how to solve this Deloitte Java developer interview question:
public static int findMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int[] arr = {1, 2, 3, 4, 5};
System.out.println(findMax(arr)); // Output: 5
Q4. How do you check if a string contains only digits in Java?
Sample Answer: We can check if a string contains only digits by iterating through each character and using Character.isDigit(). For example:
public static boolean isNumeric(String str) {
for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
System.out.println(isNumeric("12345")); // Output: true
Q5. Write a Java program to find the factorial of a number using iteration.
Sample Answer: The factorial of a number is the product of all positive integers less than or equal to the number, which can be calculated using a loop. Here is an example of how to do it:
public static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
System.out.println(factorial(5)); // Output: 120
Q6. How do you check if two strings are anagrams in Java?
Sample Answer: Two strings are anagrams if they contain the same characters in the same frequency. Sorting both strings and comparing them can help solve this. For example:
public static boolean areAnagrams(String s1, String s2) {
char[] arr1 = s1.toCharArray();
char[] arr2 = s2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
System.out.println(areAnagrams("listen", "silent")); // Output: true
Q7. Write a Java program to print Fibonacci series up to n numbers.
Sample Answer: The Fibonacci series is generated by adding the previous two numbers in the series. It starts with 0 and 1. For example:
public static void printFibonacci(int n) {
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
printFibonacci(7); // Output: 0 1 1 2 3 5 8
Also Read: How to get Job in Deloitte
Q8. How do you check if an integer is a power of two in Java?
Sample Answer: An integer is a power of two if it has only one bit set in its binary representation. Here is an example of how to do it:
public static boolean isPowerOfTwo(int num) {
return num > 0 && (num & (num - 1)) == 0;
}
System.out.println(isPowerOfTwo(16)); // Output: true
Q9. Write a Java program to reverse a number.
Sample Answer: Reversing a number involves extracting digits one by one and appending them in reverse order. Here is an example of how to do it:
public static int reverseNumber(int num) {
int reversed = 0;
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
return reversed;
}
System.out.println(reverseNumber(12345)); // Output: 54321
Q10. How do you find the second-largest number in an array?
Sample Answer: Finding the second largest number requires tracking both the maximum and the second maximum elements. For example:
public static int findSecondLargest(int[] arr) {
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
}
}
return second;
}
int[] arr = {1, 5, 2, 9, 8};
System.out.println(findSecondLargest(arr)); // Output: 8
Q11. Write a Java program to count occurrences of each character in a string.
Sample Answer: A HashMap can be used to store and count the frequency of each character in the string. Here is an example of how to do it:
public static void countCharOccurrences(String str) {
Map<Character, Integer> charCount = new HashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
System.out.println(charCount);
}
countCharOccurrences("hello world"); // Output: {d=1, e=1, h=1, l=3, o=2, r=1, w=1}
Q12. How do you remove duplicates from an array in Java?
Sample Answer: By using a Set that does not allow duplicates, we can easily eliminate duplicate values from an array. For example:
public static int[] removeDuplicates(int[] arr) {
Set<Integer> set = new LinkedHashSet<>();
for (int num : arr) {
set.add(num);
}
int[] result = new int[set.size()];
int i = 0;
for (int num : set) {
result[i++] = num;
}
return result;
}
int[] arr = {1, 2, 2, 3, 4, 4, 5};
System.out.println(Arrays.toString(removeDuplicates(arr))); // Output: [1, 2, 3, 4, 5]
Q13. Write a program to find the longest common prefix among an array of strings.
Sample Answer: The longest common prefix can be found by comparing the characters of each string from the beginning until a mismatch is found. Here is an example of how to do this Deloitte Java developer interview question:
public static String longestCommonPrefix(String[] strs) {
if (strs.length == 0) return "";
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) return "";
}
}
return prefix;
}
String[] strs = {"flower", "flow", "flight"};
System.out.println(longestCommonPrefix(strs)); // Output: "fl"
Q14. How do you check if a number is a perfect square in Java?
Sample Answer: A perfect square is a number that is the square of an integer. We can find this by checking if the square root of the number is an integer. Here is an example of how to do it:
public static boolean isPerfectSquare(int num) {
int sqrt = (int) Math.sqrt(num);
return sqrt * sqrt == num;
}
System.out.println(isPerfectSquare(16)); // Output: true
Q15. Write a program to merge two sorted arrays into one sorted array.
Sample Answer: Merging two sorted arrays is similar to the merge step in merge sort, where elements from both arrays are compared and inserted into a result array. For example:
public static int[] mergeSortedArrays(int[] arr1, int[] arr2) {
int[] result = new int[arr1.length + arr2.length];
int i = 0, j = 0, k = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}
while (i < arr1.length) result[k++] = arr1[i++];
while (j < arr2.length) result[k++] = arr2[j++];
return result;
}
int[] arr1 = {1, 3, 5};
int[] arr2 = {2, 4, 6};
System.out.println(Arrays.toString(mergeSortedArrays(arr1, arr2))); // Output: [1, 2, 3, 4, 5, 6]
Deloitte Java Developer Interview Questions for Mid-Level Candidates
Deloitte generally looks for candidates who have solid Java skills and experience throughout the software development lifecycle, especially with Agile methodologies. As a mid-level candidate pursuing developer job role, it’s important to showcase your experience and insights. Therefore, clearly articulating your technical background and contributions to previous projects is essential. This section of the blog highlights Deloitte Java interview questions that are frequently asked to evaluate your knowledge of Java frameworks, design patterns, and teamwork capabilities.
Q16. Write a program to detect a loop in a linked list using Floyd’s cycle detection algorithm.
Sample Answer: Floyd’s Cycle Detection Algorithm, also known as the Tortoise and Hare Algorithm, detects a cycle in a linked list by using two pointers moving at different speeds. For example:
class Node {
int data;
Node next;
Node(int data) { this.data = data; next = null; }
}
public static boolean hasCycle(Node head) {
if (head == null) return false;
Node slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
Q17. Write a Java program to find the intersection point of two linked lists.
Sample Answer: To find the intersection point of two linked lists, calculate the lengths of both lists and move the pointer of the longer list ahead by the difference in lengths. For example:
public static Node getIntersectionNode(Node headA, Node headB) {
int lenA = getLength(headA);
int lenB = getLength(headB);
while (lenA > lenB) {
headA = headA.next;
lenA--;
}
while (lenB > lenA) {
headB = headB.next;
lenB--;
}
while (headA != headB) {
headA = headA.next;
headB = headB.next;
}
return headA;
}
public static int getLength(Node head) {
int length = 0;
while (head != null) {
length++;
head = head.next;
}
return length;
}
Q18. Write a Java program to implement a simple LRU (Least Recently Used) Cache using a LinkedHashMap.
Sample Answer: An LRU Cache can be efficiently implemented using LinkedHashMap by overriding its removeEldestEntry method. Here is an example of how to do it:
class LRUCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
public LRUCache(int capacity) {
super(capacity, 0.75f, true);
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}
LRUCache<Integer, String> cache = new LRUCache<>(2);
cache.put(1, "one");
cache.put(2, "two");
cache.get(1); // Access to make it least recently used
cache.put(3, "three");
System.out.println(cache); // Output: {1=one, 3=three}
Q19. Implement a method to flatten a binary tree to a linked list in Java.
Sample Answer: To flatten a binary tree into a linked list, traverse the tree in a pre-order manner and rearrange nodes such that left children are set to null, and right children point to the next node in the list. For example:
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public static void flatten(TreeNode root) {
if (root == null) return;
flatten(root.left);
flatten(root.right);
TreeNode temp = root.right;
root.right = root.left;
root.left = null;
TreeNode current = root;
while (current.right != null) current = current.right;
current.right = temp;
}
Q20. Write a Java program to find the number of islands in a 2D matrix.
Sample Answer: To find the number of islands, use a Depth-First Search (DFS) algorithm to traverse the matrix and mark connected land cells (represented by ‘1’) as visited. Here is an example of how to solve this Deloitte Java developer interview question:
public static int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) return 0;
int count = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
count++;
dfs(grid, i, j);
}
}
}
return count;
}
public static void dfs(char[][] grid, int i, int j) {
if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == '0') return;
grid[i][j] = '0'; // Mark as visited
dfs(grid, i - 1, j);
dfs(grid, i + 1, j);
dfs(grid, i, j - 1);
dfs(grid, i, j + 1);
}
Q21. How do you implement a binary search in a sorted array?
Sample Answer: Binary search is an efficient algorithm to search for an element in a sorted array by repeatedly dividing the search interval in half. For example:
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
int[] arr = {1, 2, 3, 4, 5, 6};
System.out.println(binarySearch(arr, 4)); // Output: 3
Q22. Write a Java program to convert a binary tree into its mirror.
Sample Answer: The mirror of a binary tree is created by swapping the left and right child of every node. For example:
public static void mirror(TreeNode node) {
if (node == null) return;
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
mirror(node.left);
mirror(node.right);
}
Q23. Write a program to serialize and deserialize a binary tree in Java.
Sample Answer: Serialization is converting a tree to a string representation, and deserialization is reconstructing the tree from that string. We can use pre-order traversal for this task. Here is an example of how to do it:
public static String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serializeHelper(root, sb);
return sb.toString();
}
private static void serializeHelper(TreeNode node, StringBuilder sb) {
if (node == null) {
sb.append("null,");
return;
}
sb.append(node.val).append(",");
serializeHelper(node.left, sb);
serializeHelper(node.right, sb);
}
public static TreeNode deserialize(String data) {
Queue<String> nodes = new LinkedList<>(Arrays.asList(data.split(",")));
return deserializeHelper(nodes);
}
private static TreeNode deserializeHelper(Queue<String> nodes) {
String val = nodes.poll();
if (val.equals("null")) return null;
TreeNode node = new TreeNode(Integer.parseInt(val));
node.left = deserializeHelper(nodes);
node.right = deserializeHelper(nodes);
return node;
}
Q24. How do you find the lowest common ancestor (LCA) of two nodes in a binary search tree?
Sample Answer: The LCA of two nodes in a BST is the node that is common to both nodes and is the farthest from the root. Here is an example:
public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) return null;
if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
return root;
}
Q25. Write a Java program to sort a linked list using merge sort.
Sample Answer: Merge sort is a divide-and-conquer algorithm that recursively divides the list into two halves and sorts them, then merges the sorted halves. For example:
public static Node mergeSort(Node head) {
if (head == null || head.next == null) return head;
Node middle = getMiddle(head);
Node nextToMiddle = middle.next;
middle.next = null;
Node left = mergeSort(middle);
Node right = mergeSort(nextToMiddle);
return sortedMerge(left, right);
}
public static Node getMiddle(Node head) {
if (head == null) return head;
Node slow = head, fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public static Node sortedMerge(Node left, Node right) {
if (left == null) return right;
if (right == null) return left;
if (left.data <= right.data) {
left.next = sortedMerge(left.next, right);
return left;
} else {
right.next = sortedMerge(left, right.next);
return right;
}
}
Q26. Write a Java program to convert an integer to Roman numerals.
Sample Answer: This is one of the most asked Deloitte Java developer interview questions. Roman numerals are represented by combinations of letters from the Latin alphabet. To convert an integer to Roman numerals, start from the largest values and work downward. Here is an example of how to do it:
public static String intToRoman(int num) {
String[] thousands = {"", "M", "MM", "MMM"};
String[] hundreds = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
String[] tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
String[] ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return thousands[num / 1000] + hundreds[(num % 1000) / 100] + tens[(num % 100) / 10] + ones[num % 10];
}
System.out.println(intToRoman(1994)); // Output: MCMXCIV
Q27. How do you check if a binary tree is balanced?
Sample Answer: A balanced binary tree is one where the height difference between the left and right subtrees is not greater than 1 for any node. For example:
public static boolean isBalanced(TreeNode root) {
return checkHeight(root) != -1;
}
private static int checkHeight(TreeNode node) {
if (node == null) return 0;
int leftHeight = checkHeight(node.left);
if (leftHeight == -1) return -1;
int rightHeight = checkHeight(node.right);
if (rightHeight == -1) return -1;
if (Math.abs(leftHeight - rightHeight) > 1) return -1;
return Math.max(leftHeight, rightHeight) + 1;
}
Q28. Write a Java program to implement the Knuth-Morris-Pratt (KMP) string-matching algorithm.
Sample Answer: The KMP algorithm searches for occurrences of a word within a main text by using the information from previous matches to avoid unnecessary re-checks. Here is an example of how to do it:
public static void KMPSearch(String pattern, String text) {
int[] lps = computeLPSArray(pattern);
int i = 0, j = 0;
while (i < text.length()) {
if (pattern.charAt(j) == text.charAt(i)) {
i++;
j++;
}
if (j == pattern.length()) {
System.out.println("Found pattern at index " + (i - j));
j = lps[j - 1];
} else if (i < text.length() && pattern.charAt(j) != text.charAt(i)) {
if (j != 0) j = lps[j - 1];
else i++;
}
}
}
private static int[] computeLPSArray(String pattern) {
int[] lps = new int[pattern.length()];
int len = 0, i = 1;
lps[0] = 0;
while (i < pattern.length()) {
if (pattern.charAt(i) == pattern.charAt(len)) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) len = lps[len - 1];
else lps[i] = 0;
}
}
return lps;
}
Q29. Write a Java program to implement the Dijkstra algorithm for the shortest path.
Sample Answer: Dijkstra’s algorithm finds the shortest paths from a starting vertex to all other vertices in a weighted graph. Here is an example:
public static void dijkstra(int[][] graph, int src) {
int n = graph.length;
int[] dist = new int[n];
boolean[] visited = new boolean[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;
for (int i = 0; i < n - 1; i++) {
int u = minDistance(dist, visited);
visited[u] = true;
for (int v = 0; v < n; v++) {
if (!visited[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
printSolution(dist);
}
private static int minDistance(int[] dist, boolean[] visited) {
int min = Integer.MAX_VALUE, minIndex = -1;
for (int v = 0; v < dist.length; v++) {
if (!visited[v] && dist[v] <= min) {
min = dist[v];
minIndex = v;
}
}
return minIndex;
}
private static void printSolution(int[] dist) {
System.out.println("Vertex \t Distance from Source");
for (int i = 0; i < dist.length; i++) {
System.out.println(i + " \t\t " + dist[i]);
}
}
Q30. How do you solve the 0/1 Knapsack problem using dynamic programming?
Sample Answer: The 0/1 Knapsack problem can be solved using dynamic programming by building a 2D array to store maximum values at each subproblem level. Here is an example of how to do it:
public static int knapSack(int W, int[] weights, int[] values, int n) {
int[][] dp = new int[n + 1][W + 1];
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= W; w++) {
if (i == 0 || w == 0) dp[i][w] = 0;
else if (weights[i - 1] <= w) dp[i][w] = Math.max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]);
else dp[i][w] = dp[i - 1][w];
}
}
return dp[n][W];
}
int[] values = {60, 100, 120};
int[] weights = {10, 20, 30};
int W = 50;
System.out.println(knapSack(W, weights, values, values.length)); // Output: 220
Deloitte Coding Interview Questions for Experienced Java Developers
For an experienced Java professional, the hiring process at Deloitte is rigorous and broad. Deloitte coding questions for experienced Java developers are mainly based on your coding skills as well as system design and architecture skills. The typical questions are a mixture of advanced algorithms and system architecture and several aspects of code optimization techniques and best practices in software development. Here we have enlisted some questions to help you understand what to anticipate in this round of interviews as a coder:
Q31. Write a Java program to implement a thread-safe singleton pattern.
Sample Answer: The singleton pattern ensures that a class has only one instance and provides a global point of access to it. The thread-safe version can be implemented using synchronized blocks or other concurrency mechanisms. For example:
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Q32. Write a program to implement a blocking queue in Java.
Sample Answer: A blocking queue allows threads to add and remove elements in a synchronized manner, blocking if the queue is empty or full. This can be implemented using wait() and notify() methods. For example:
class BlockingQueue<T> {
private Queue<T> queue = new LinkedList<>();
private int capacity;
public BlockingQueue(int capacity) {
this.capacity = capacity;
}
public synchronized void enqueue(T item) throws InterruptedException {
while (queue.size() == capacity) {
wait();
}
queue.add(item);
notifyAll();
}
public synchronized T dequeue() throws InterruptedException {
while (queue.isEmpty()) {
wait();
}
T item = queue.remove();
notifyAll();
return item;
}
}
Q33. Write a Java program to implement a simple LRU (Least Recently Used) cache.
Sample Answer: An LRU cache evicts the least recently used items first. This can be efficiently implemented using a combination of a HashMap and a doubly linked list. Here is how you can solve this Deloitte Java developer interview question:
import java.util.*;
class LRUCache {
private final Map<Integer, Node> map;
private final int capacity;
private Node head, tail;
class Node {
int key, value;
Node prev, next;
Node(int key, int value) {
this.key = key;
this.value = value;
}
}
public LRUCache(int capacity) {
this.capacity = capacity;
this.map = new HashMap<>();
head = new Node(0, 0);
tail = new Node(0, 0);
head.next = tail;
tail.prev = head;
}
public int get(int key) {
if (!map.containsKey(key)) return -1;
Node node = map.get(key);
remove(node);
insert(node);
return node.value;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
remove(map.get(key));
}
Node newNode = new Node(key, value);
insert(newNode);
map.put(key, newNode);
if (map.size() > capacity) {
Node lru = tail.prev;
remove(lru);
map.remove(lru.key);
}
}
private void remove(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void insert(Node node) {
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
}
Q34. Write a Java program to find the longest palindromic substring in a given string.
Sample Answer: To find the longest palindromic substring, we can expand around potential centers and keep track of the maximum length found. For example:
public static String longestPalindrome(String s) {
if (s.length() < 1) return "";
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
private static int expandAroundCenter(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}
Q35. Write a Java program to perform topological sorting on a directed acyclic graph (DAG).
Sample Answer: Topological sorting is a linear ordering of vertices in a DAG such that for every directed edge UV from vertex U to vertex V, U comes before V in the ordering. This can be achieved using DFS or Kahn’s algorithm. Here is an example of how to do it:
import java.util.*;
public static List<Integer> topologicalSort(int numCourses, int[][] prerequisites) {
int[] inDegree = new int[numCourses];
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int[] prereq : prerequisites) {
inDegree[prereq[0]]++;
graph.computeIfAbsent(prereq[1], k -> new ArrayList<>()).add(prereq[0]);
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < numCourses; i++) {
if (inDegree[i] == 0) queue.add(i);
}
List<Integer> result = new ArrayList<>();
while (!queue.isEmpty()) {
int course = queue.poll();
result.add(course);
for (int neighbor : graph.getOrDefault(course, new ArrayList<>())) {
inDegree[neighbor]--;
if (inDegree[neighbor] == 0) queue.add(neighbor);
}
}
return result.size() == numCourses ? result : new ArrayList<>(); // return empty if there's a cycle
}
Q36. Write a Java program to implement a binary search tree (BST) and its operations.
Sample Answer: A binary search tree is a node-based data structure that has a left child less than the parent and a right child greater than the parent. For example:
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) { val = x; }
}
class BST {
private TreeNode root;
public void insert(int val) {
root = insertRec(root, val);
}
private TreeNode insertRec(TreeNode root, int val) {
if (root == null) {
root = new TreeNode(val);
return root;
}
if (val < root.val) root.left = insertRec(root.left, val);
else if (val > root.val) root.right = insertRec(root.right, val);
return root;
}
public boolean search(int val) {
return searchRec(root, val);
}
private boolean searchRec(TreeNode root, int val) {
if (root == null) return false;
if (root.val == val) return true;
return val < root.val ? searchRec(root.left, val) : searchRec(root.right, val);
}
public void inorder() {
inorderRec(root);
}
private void inorderRec(TreeNode root) {
if (root != null) {
inorderRec(root.left);
System.out.print(root.val + " ");
inorderRec(root.right);
}
}
}
// Main method
BST bst = new BST();
bst.insert(5);
bst.insert(3);
bst.insert(7);
bst.inorder(); // Output: 3 5 7
System.out.println(bst.search(5)); // Output: true
Q37. Write a Java program to implement the Producer-Consumer problem using BlockingQueue.
Sample Answer: The producer-consumer problem is a classic synchronization problem. In Java, the BlockingQueue interface makes it easier to implement this pattern. For example:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
// Producer class
class Producer implements Runnable {
private final BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
int i = 0;
try {
while (true) {
System.out.println("Produced: " + i);
queue.put(i++); // Adds item to the queue, blocks if full
Thread.sleep(500); // Simulate time delay
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
// Consumer class
class Consumer implements Runnable {
private final BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while (true) {
int item = queue.take(); // Retrieves and removes item, blocks if empty
System.out.println("Consumed: " + item);
Thread.sleep(1000); // Simulate time delay
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
// Main class to run the Producer-Consumer example
public class ProducerConsumerExample {
public static void main(String[] args) {
// Shared BlockingQueue with a capacity of 5
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);
// Start Producer and Consumer threads
Thread producerThread = new Thread(new Producer(queue));
Thread consumerThread = new Thread(new Consumer(queue));
producerThread.start();
consumerThread.start();
}
}
Q38. Write a Java program to implement a Merge Sort algorithm.
Sample Answer: Merge Sort is a divide-and-conquer algorithm that sorts an array by dividing it into halves, sorting each half, and then merging the sorted halves. Here is an example of how to do it:
public class MergeSort {
// Main function to sort an array using Merge Sort
public static void mergeSort(int[] array, int left, int right) {
if (left < right) {
int middle = (left + right) / 2;
// Recursively sort the first and second halves
mergeSort(array, left, middle);
mergeSort(array, middle + 1, right);
// Merge the two halves
merge(array, left, middle, right);
}
}
// Merge function to combine two sorted halves
private static void merge(int[] array, int left, int middle, int right) {
int n1 = middle - left + 1;
int n2 = right - middle;
// Temporary arrays to hold the split halves
int[] leftArray = new int[n1];
int[] rightArray = new int[n2];
// Copy data into temporary arrays
for (int i = 0; i < n1; i++) {
leftArray[i] = array[left + i];
}
for (int j = 0; j < n2; j++) {
rightArray[j] = array[middle + 1 + j];
}
// Merge the temp arrays back into the main array
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
array[k] = leftArray[i];
i++;
} else {
array[k] = rightArray[j];
j++;
}
k++;
}
// Copy any remaining elements from the left array
while (i < n1) {
array[k] = leftArray[i];
i++;
k++;
}
// Copy any remaining elements from the right array
while (j < n2) {
array[k] = rightArray[j];
j++;
k++;
}
}
public static void main(String[] args) {
int[] array = {38, 27, 43, 3, 9, 82, 10};
System.out.println("Original array:");
printArray(array);
mergeSort(array, 0, array.length - 1);
System.out.println("Sorted array:");
printArray(array);
}
// Helper function to print the array
private static void printArray(int[] array) {
for (int i : array) {
System.out.print(i + " ");
}
System.out.println();
}
}
Q39. Write a Java program to find the shortest path in a weighted graph using Dijkstra’s algorithm.
Sample Answer: Dijkstra’s algorithm is used to find the shortest path from a source node to all other nodes in a graph with non-negative weights. This can be implemented using a priority queue. Here is an example of how to do it:
import java.util.*;
public class Dijkstra {
// Edge class representing a directed edge with a weight
static class Edge {
int target;
int weight;
Edge(int target, int weight) {
this.target = target;
this.weight = weight;
}
}
// Method to find shortest paths from a source vertex
public static void dijkstra(List<List<Edge>> graph, int source) {
int vertices = graph.size();
int[] distances = new int[vertices];
Arrays.fill(distances, Integer.MAX_VALUE);
distances[source] = 0;
// Priority queue to select the vertex with the shortest known distance
PriorityQueue<Edge> pq = new PriorityQueue<>(Comparator.comparingInt(e -> e.weight));
pq.add(new Edge(source, 0));
while (!pq.isEmpty()) {
Edge current = pq.poll();
int u = current.target;
// For each neighbor of u, calculate the new distance
for (Edge edge : graph.get(u)) {
int v = edge.target;
int weight = edge.weight;
int newDist = distances[u] + weight;
// If new distance is shorter, update and add to the queue
if (newDist < distances[v]) {
distances[v] = newDist;
pq.add(new Edge(v, newDist));
}
}
}
// Print the shortest distances from the source
System.out.println("Vertex\tDistance from Source");
for (int i = 0; i < vertices; i++) {
System.out.println(i + "\t\t" + distances[i]);
}
}
public static void main(String[] args) {
int vertices = 5;
List<List<Edge>> graph = new ArrayList<>();
// Initialize graph
for (int i = 0; i < vertices; i++) {
graph.add(new ArrayList<>());
}
// Add edges: (source, target, weight)
graph.get(0).add(new Edge(1, 4));
graph.get(0).add(new Edge(2, 1));
graph.get(2).add(new Edge(1, 2));
graph.get(1).add(new Edge(3, 1));
graph.get(2).add(new Edge(3, 5));
graph.get(3).add(new Edge(4, 3));
// Find the shortest paths from vertex 0
dijkstra(graph, 0);
}
}
Q40. Write a Java program to implement a simple version of a HashMap.
Sample Answer: Here’s a simple Java implementation of a basic HashMap. In this Java Developer interview question, you have to demonstrate the core functionality of a HashMap, including the methods put, get, and remove. It uses an array of linked lists to handle hash collisions:
import java.util.LinkedList;
public class SimpleHashMap<K, V> {
// Default capacity for the hash table
private static final int DEFAULT_CAPACITY = 16;
private LinkedList<Entry<K, V>>[] table; // Array of LinkedLists for entries
// Constructor to initialize the hash table
public SimpleHashMap() {
table = new LinkedList[DEFAULT_CAPACITY];
}
// Entry class representing a key-value pair
private static class Entry<K, V> {
K key;
V value;
Entry(K key, V value) {
this.key = key;
this.value = value;
}
}
// Hash function to calculate index based on key
private int hash(K key) {
return Math.abs(key.hashCode() % table.length);
}
// Method to put a key-value pair in the HashMap
public void put(K key, V value) {
int index = hash(key);
if (table[index] == null) {
table[index] = new LinkedList<>();
}
for (Entry<K, V> entry : table[index]) {
if (entry.key.equals(key)) {
entry.value = value; // Update the existing key with a new value
return;
}
}
// If key doesn't exist, add a new entry
table[index].add(new Entry<>(key, value));
}
// Method to get a value by key
public V get(K key) {
int index = hash(key);
if (table[index] == null) return null;
for (Entry<K, V> entry : table[index]) {
if (entry.key.equals(key)) {
return entry.value;
}
}
return null; // Key not found
}
// Method to remove a key-value pair by key
public void remove(K key) {
int index = hash(key);
if (table[index] == null) return;
table[index].removeIf(entry -> entry.key.equals(key));
}
// Main method to test the SimpleHashMap
public static void main(String[] args) {
SimpleHashMap<String, Integer> map = new SimpleHashMap<>();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
System.out.println("apple: " + map.get("apple")); // Output: 10
System.out.println("banana: " + map.get("banana")); // Output: 20
map.remove("apple");
System.out.println("apple after removal: " + map.get("apple")); // Output: null
}
}
Q41. Write a Java program to count occurrences of each character in a string.
Sample Answer: A HashMap can be used to store and count the frequency of each character in the string. Here is an example:
public static void countCharOccurrences(String str) {
Map<Character, Integer> charCount = new HashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
System.out.println(charCount);
}
countCharOccurrences("hello world"); // Output: {d=1, e=1, h=1, l=3, o=2, r=1, w=1}
Q42. Write a Java program to perform a binary search on a sorted array.
Sample Answer: Binary search is an efficient algorithm for finding an item from a sorted list of items, reducing the search space by half each time. For example:
public static int binarySearch(int[] array, int target) {
int left = 0, right = array.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (array[mid] == target) {
return mid; // Target found
} else if (array[mid] < target) {
left = mid + 1; // Search in right half
} else {
right = mid - 1; // Search in left half
}
}
return -1; // Target not found
}
// Main method
int[] arr = {1, 2, 3, 4, 5};
System.out.println(binarySearch(arr, 3)); // Output: 2
Q43. Write a Java program to implement a lazy initialization holder class pattern for a singleton pattern.
Sample Answer: Here’s a Java program that demonstrates the lazy initialization holder class pattern for implementing a singleton. This pattern leverages the Java ClassLoader to ensure thread-safe lazy initialization without synchronization overhead. Here is an example of how to do it:
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() {}
// Static inner class responsible for holding the Singleton instance
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
// Public method to provide global access to the Singleton instance
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
Q44. Write a Java program to implement a basic version of a blocking queue.
Sample Answer: A blocking queue allows threads to wait for the queue to become non-empty when retrieving an element or for space to become available when adding an element. Here is an example of how to do it:
import java.util.LinkedList;
class BlockingQueue<T> {
private final LinkedList<T> queue = new LinkedList<>();
private final int limit;
public BlockingQueue(int limit) {
this.limit = limit;
}
public synchronized void enqueue(T item) throws InterruptedException {
while (queue.size() == limit) {
wait(); // Wait until space is available
}
queue.add(item);
notifyAll(); // Notify other threads that an item has been added
}
public synchronized T dequeue() throws InterruptedException {
while (queue.isEmpty()) {
wait(); // Wait until an item is available
}
T item = queue.removeFirst();
notifyAll(); // Notify other threads that an item has been removed
return item;
}
}
// Main method
BlockingQueue<Integer> queue = new BlockingQueue<>(5);
Q45. Write a Java program to find the maximum product of two integers in an array.
Sample Answer: To find the maximum product of two integers in an array, we can sort the array and calculate the product of the two largest numbers. For example:
public class MaxProduct {
public static int maxProduct(int[] arr) {
if (arr.length < 2) {
throw new IllegalArgumentException("Array must contain at least two integers.");
}
int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE;
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
// Traverse through the array
for (int num : arr) {
// Update max values
if (num > max1) {
max2 = max1;
max1 = num;
} else if (num > max2) {
max2 = num;
}
// Update min values
if (num < min1) {
min2 = min1;
min1 = num;
} else if (num < min2) {
min2 = num;
}
}
// Calculate max product of the two largest numbers and the two smallest numbers
return Math.max(max1 * max2, min1 * min2);
}
public static void main(String[] args) {
int[] arr = {5, -10, 15, 2, 9, -20};
System.out.println("Maximum product of two integers in the array: " + maxProduct(arr));
}
}
Conclusion
Securing a Java Developer role at Deloitte demands thorough preparation and a comprehensive understanding of Java, ranging from foundational principles to advanced frameworks. Deloitte’s interview process is designed to test your knowledge and ability to apply Java in real-world scenarios, irrespective of your professional level. By focusing on the key areas highlighted in this guide to Deloitte’s Java Developer interview questions, you can enhance your readiness and position yourself for success. Want to learn more about Deloitte interview questions? Read our blog for expert tips, common questions, and strategies to showcase your strengths and align with the company’s values.
FAQs
Answer: You can expect a mix of technical and behavioral questions during your interview. Technical questions will focus on your understanding of Java concepts, coding skills, and familiarity with frameworks and tools. Behavioral questions will assess your teamwork, problem-solving abilities, and how you’ve contributed to past projects.
Answer: To prepare for the coding challenges, practice solving a variety of algorithmic and data structure problems using Java. Familiarize yourself with common coding challenges, and consider using platforms like LeetCode or HackerRank. Additionally, review best practices for writing clean, efficient code, as well as any relevant frameworks or technologies mentioned in the job description.
Answer: Yes, focus on core Java concepts, object-oriented programming principles, Java frameworks (such as Spring and Hibernate), and design patterns. Additionally, understanding Agile methodologies and being able to discuss your experience working in teams will be beneficial. Familiarize yourself with coding optimization techniques and system design principles as well, especially for mid-level and experienced positions.