Java Coding Questions
Java Coding Questions
1. Write a program to find the sum of two numbers entered by the user.
import java.util.Scanner;
import java.util.Scanner;
import java.util.Scanner;
int first = 0;
int second = 1;
scanner.close();
}
}
import java.util.Arrays;
import java.util.Scanner;
1. Write a Java program to swap two numbers without using a temporary variable.
import java.util.Scanner;
import java.util.Arrays;
1. Write a program to sort an array of integers in ascending order using the Bubble
Sort algorithm.
import java.util.Arrays;
1. Write a Java program to find the GCD (Greatest Common Divisor) of two
numbers.
import java.util.Scanner;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Scanner;
import java.util.Scanner;
) {
String str = "12345";
boolean containsOnlyDigits = checkOnlyDigits(str);
System.out.println(str + " contains only digits: " + containsOnlyDigits);
}
1. Write a program to print the Pascal's triangle for a given number of rows.
import java.util.Scanner;
import java.util.HashSet;
import java.util.Set;
1. Write a Java program to find the nth term of the Fibonacci series using
recursion.
import java.util.Scanner;
return maxLength;
}
}
import java.util.*;
int i = 0;
return intersection;
}
}
1. Implement a stack that supports push, pop, and getMin operations in O(1) time.
import java.util.*;
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
}
1. Given a binary tree, write a Java function to find the diameter (longest path
between any two nodes).
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
1. Implement a queue using two stacks in Java with enqueue and dequeue
operations.
import java.util.Stack;
public QueueUsingStacks() {
stack1 = new Stack<>();
stack2 = new Stack<>();
1. Write a Java program to find the kth smallest element in a binary search tree.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class K
thSmallestElementInBST {
public int kthSmallest(TreeNode root, int k) {
int[] result = new int[2];
inorder(root, k, result);
return result[1];
}
inorder(node.left, k, result);
if (++result[0] == k) {
result[1] = node.val;
return;
}
inorder(node.right, k, result);
}
}
1. Given a matrix of 0s and 1s, find the largest square submatrix with all 1s.
int m = matrix.length;
int n = matrix[0].length;
int[][] dp = new int[m + 1][n + 1];
int maxSide = 0;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
public MinHeap() {
heap = new ArrayList<>();
}
if (minIdx != index) {
swap(index, minIdx);
index = minIdx;
} else {
break;
}
}
}
return maxProduct;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
import java.util.*;
class LRUCache {
private LinkedHashMap<Integer, Integer> cache;
private int capacity;
.capacity = capacity;
cache = new LinkedHashMap<>(capacity, 0.75f, true);
}
import java.util.*;
mergedIntervals.add(currentInterval);
return mergedIntervals.toArray(new int[mergedIntervals.size()][]);
}
}
1. Write a Java program to find the longest palindromic substring in a given string.
return prefix.toString();
}
}
1. Given a binary tree, write a Java function to find the path with the maximum
sum.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
import java.util.*;
1. Write a Java program to implement a stack with getMin operation in O(1) time.
import java.util.*;
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
}
1. Given a list of words, find the longest word that can be formed by other words in
the list.
import java.util.*;
return longestWord;
}
}
1. Implement a function to find the longest substring with at most two distinct
characters.
int maxLength = 0;
int left = 0;
{
charCount.remove(leftChar);
}
left++;
}
maxLength = Math.max(maxLength, right - left + 1);
right++;
}
return maxLength;
}
}
1. Given a 2D grid of characters, find all valid words from a dictionary using DFS or
Trie.
import java.util.*;
private void dfs(char[][] board, int x, int y, TrieNode node, Set<String> result)
{
if (newX >= 0 && newX < board.length && newY >= 0 && newY < board[0].lengt
h) {
dfs(board, newX, newY, node, result);
}
}
class TrieNode {
TrieNode[] children;
String word;
TrieNode() {
children = new TrieNode[26];
word = null;
}
}
class Trie {
private TrieNode root;
Trie() {
root = new TrieNode();
}
TrieNode getRoot() {
return root;
1. Write a Java program to find the number of islands in a 2D grid of '1's and '0's.
return count;
}
dfs(grid, x - 1, y);
dfs(grid, x + 1, y);
dfs(grid, x, y - 1);
dfs(grid, x, y + 1);
}
}
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
1. Given a binary tree, write a Java function to find the sum of all left leaves.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
These moderate-level coding questions cover a range of topics and challenges that
can help you prepare for Java interviews. Be sure to understand the solutions and
practice implementing them to enhance your problem-solving skills. Good luck with
your interviews!
1. Given a binary tree, write a Java function to check if it is a binary search tree
(BST).
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
1. Implement a stack using linked lists in Java with push, pop, and peek operations.
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
1. Write a Java program to find the kth smallest element in a binary search tree.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
1. Given an array of integers, find all pairs that sum up to a specific target.
import java.util.*;
return result;
}
}
1. Implement a queue using two stacks in Java with enqueue and dequeue
operations.
import java.util.Stack;
public QueueUsingStacks() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
return prev;
1. Given a 2D grid of 1s and 0s, find the size of the largest island (connected 1s).
return maxArea;
}
grid[x][y] = 0;
int area = 1;
return area;
}
}
1. Implement a Trie (prefix tree) in Java to support insert, search, and startsWith
operations.
class TrieNode {
boolean isEnd;
TrieNode[] children;
TrieNode() {
public Trie() {
root = new TrieNode();
}
.isEnd;
}
1. Write a Java program to find the longest common subsequence (LCS) of two
strings.
return lcs.toString();
}
}
1. Given a matrix of 0s and 1s, find the size of the largest square submatrix with all
1s.
int m = matrix.length;
int n = matrix[0].length;
int[][] dp = new int[m + 1][n + 1];
int maxSide = 0;
1. Implement a hash table (dictionary) in Java with put, get, and remove
operations.
public HashTable() {
table = new Entry[INITIAL_CAPACITY];
size = 0;
}
if (table[index] == null) {
table[index] = entry;
size++;
} else {
Entry<K, V> current = table[index];
while (current.next != null) {
if (current.key.equals(key)) {
current.value = value;
return;
}
current = current.next;
}
current.next = entry;
size++;
}
table = newTable;
}
}
import java.util.HashMap;
import java.util.Map;
1. Given a binary tree, write a Java function to find the maximum path sum
between any two nodes.
class TreeNode {
int val
;
TreeNode left;
TreeNode right;
TreeNode(int val) {
import java.util.ArrayList;
import java.util.List;
public MinHeap() {
heap = new ArrayList<>();
}
if (minIdx != index) {
swap(index, minIdx);
index = minIdx;
} else {
break;
}
}
}
1. Write a Java program to merge k sorted arrays into a single sorted array.
import java.util.PriorityQueue;
while (!pq.isEmpty()) {
ArrayElement element = pq.poll();
mergedArray[index++] = element.val;
return mergedArray;
}
class ArrayElement {
int val;
int arrayIndex;
int nextIndex;
1. Given an array of integers, find the length of the longest increasing subarray.
return maxLength;
}
}
1. Implement a graph in Java with BFS (Breadth-First Search) and DFS (Depth-
First Search) traversal algorithms.
import java.util.*;
class Graph {
private int V;
private List<Integer>[] adjList;
public Graph(int V) {
this.V = V;
adjList = new ArrayList[V];
for (int i = 0; i < V; i++) {
adjList[i] = new ArrayList<>();
}
}
while (!queue.isEmpty()) {
int node = queue.poll();
System.out.print(node + " ");
1. Write a Java program to find the median of two sorted arrays of different sizes.
if (m > n) {
return find
MedianSortedArrays(nums2, nums1);
}
int left = 0;
int right = m;
int total = (m + n + 1) / 2;
1. Given a 2D grid of characters, find all valid words from a dictionary using DFS or
Trie.
import java.util.*;
private void dfs(char[][] board, int x, int y, TrieNode node, Set<String> result)
{
char c = board[x][y];
if (c == '#' || node.children[c - 'a'] == null) {
return;
}
if (newX >= 0 && newX < board.length && newY >= 0 && newY < board[0].lengt
h) {
dfs(board, newX, newY, node, result);
}
}
class TrieNode {
TrieNode[] children;
String word;
TrieNode() {
children = new TrieNode[26];
word = null;
}
}
class Trie {
private TrieNode root;
Trie() {
root = new TrieNode();
}
TrieNode getRoot() {
return root;
}
}
1. Implement a circular linked list in Java with insert, delete, and traverse
operations.
class ListNode {
int val;
ListNode next;
ListNode(int val) {
public CircularLinkedList() {
head = null;
}
1. Write a Java program to find the maximum sum subarray using the Kadane's
algorithm.
return maxSum;
}
}
import java.util.*;
mergedIntervals.add(currentInterval);
return
mergedIntervals.toArray(new int[mergedIntervals.size()][]);
}
}
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
1. Write a Java function to serialize and deserialize a binary tree (convert to/from a
string representation).
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
1. Given a directed graph, check if it contains a cycle using DFS or BFS in Java.
import java.util.*;
return false;
}
if (visited[course] == -1) {
return false;
}
visited[course] = 1;
visited[course] = -1;
return false;
}
}
return maxLength;
}
}
return false;
}
private boolean dfs(char[][] board, int x, int y, String word, int index) {
if (index == word.length()) {
return true;
}
1. Write a Java program to find the kth largest element in an unsorted array.
import java.util.*;
return minHeap.peek();
}
}
return maxSum;
}
}
import java.util.*;
int left = 0;
int minLen = Integer.MAX_VALUE;
int minStart = 0;
int count = t.length();
while (count == 0) {
if (right - left + 1 < minLen) {
minLen = right - left + 1;
minStart = left;
}
left++;
}
}
int imin = 0;
int imax = m;
int halfLen = (m + n + 1) / 2;
if ((m + n) % 2 == 1) {
return maxOfLeft;
}
int minOfRight;
if (i == m) {
minOfRight = nums2[j];
} else if (j == n) {
minOfRight = nums1[i];
} else {
minOfRight = Math.min(nums1[i], nums2[j]);
}
return 0.0;
}
}
1. Given a 2D grid of 0s and 1s, find the largest rectangle containing only 1s.
return maxArea;
}
return maxArea;
}
}
1. Given a binary tree, write a Java function to find the largest BST subtree.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
class BSTInfo {
int min;
int max;
int size;
if (leftInfo.isBST && rightInfo.isBST && node.val > leftInfo.max && node.val <
rightInfo.min) {
int size = leftInfo.size + rightInfo.size + 1;
int min = Math.min(node.val, leftInfo.min);
int max = Math.max(node.val, rightInfo.max);
return new BSTInfo(min, max, size, true);
} else {
return new BSTInfo(0, 0, Math.max(leftInfo.size, rightInfo.size), false);
}
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
sb.append(node.val).append(DELIMITER);
serializeHelper(node.left, sb);
serializeHelper(node.right, sb);
}
1. Write a Java program to implement a binary search tree (BST) with insert,
delete, and search operations.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
return node;
}
if (val == node.val) {
return true;
} else if (val < node.val) {
return searchHelper(node.left, val);
} else {
return searchHelper(node.right, val);
}
}
node.val = findMinValue(node.right);
node.right = deleteHelper(node.right, node.val);
}
return node;
}
char[] t = preProcess(s);
int n = t.length;
int[] p = new int[n];
int center = 0;
int right = 0;
if (right > i) {
p[i] = Math.min(right - i, p[mirror]);
}
int maxLen = 0;
int centerIndex = 0;
int m = matrix.length;
int n = matrix[0].length;
int[][] cache = new int[m][n];
int maxPathLength = 0;
return maxPathLength;
}
int m = matrix.length;
int n = matrix[0].length;
int maxPath = 1;
cache[x][y] = maxPath;
return maxPath;
}
}
1. Implement an LRU (Least Recently Used) cache using a doubly-linked list and a
hashmap.
import java.util.*;
class Node {
int key;
int value;
Node prev;
Node next;
1. Given a list of non-negative integers, write a Java function to find the maximum
amount of water that can be trapped.
int maxLeft = 0;
for (int i = 0; i < n; i++) {
leftMax[i] = maxLeft;
maxLeft = Math.max(maxLeft, height[i]);
}
int maxRight = 0;
for (int i = n - 1; i >= 0; i--) {
rightMax[i] = maxRight;
maxRight = Math.max(maxRight, height[i]);
return totalWater;
}
}
1. Write a Java program to implement a trie (prefix tree) with insert, search, and
startsWith operations.
class TrieNode {
boolean isWord;
TrieNode[] children;
TrieNode() {
isWord = false;
children = new TrieNode[26];
}
}
public Trie() {
root = new TrieNode();
}
return prefix;
}
}
1. Given a non-empty binary tree, write a Java function to find the maximum
average value of a subtree.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
class SubtreeInfo {
int sum;
int count;
1. Write a Java program to find the maximum distance between two nodes in a
binary tree.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
1. Implement a function to find the number of possible paths in a 2D grid from the
top-left corner to the bottom-right corner.
1. Write a Java program to find the longest palindromic substring with a dynamic
programming approach.
return longestPalindrome;
}
}
1. Given a string s, write a Java program to find the length of the longest substring
without repeating characters.
import java.util.*;
return maxLength;
}
}
import java.util.*;
return result;
}
1. Write a Java program to find the longest increasing subsequence with a binary
search approach.
import java.util.*;
if (index < 0) {
index = -(index + 1);
}
if (index == lis.size()) {
lis.add(num);
} else {
lis.set(index, num);
return lis.size();
}
}
1. Given a list of words, write a Java program to find all word squares.
import java.util.*;
return result;
}
if (index == size) {
result.add(new ArrayList<>(wordSquare));
return;
}
if (!prefixMap.containsKey(prefix)) {
return;
}
import java.util.*;
return maxHeap.peek();
}
}
import java.util.*;
if (n <= 1) {
return n;
}
import java.util.*;
class Interval {
int start;
int end;
mergedIntervals.add(currentInterval);
return mergedIntervals;
}
}
return result;
}
}
return dp[m][n];
}
}
public FenwickTree(int n) {
BIT = new int[n + 1];
}
import java.util.*;
return closestElements;
}
}
import java.util.*;
1. Given a list of unique numbers, write a Java program to find all permutations of
the numbers.
import java.util.*;
1. Write a Java program to implement a stack with the ability to get the minimum
element in constant time.
import java.util.*;
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
}
1. Implement a function to find the maximum sum subarray of a given array using
Kadane's algorithm.
return maxSum;
}
}
1. Write a Java program to implement a trie (prefix tree) with insert, search, and
delete operations.
class TrieNode {
boolean isWord;
TrieNode[] children;
TrieNode() {
isWord = false;
children = new TrieNode[26];
}
}
public Trie() {
root = new TrieNode();
}
if (depth == word.length()) {
if (!node.isWord) {
return false;
}
node.isWord = false;
return allChildrenNull(node);
}
return false;
}
import java.util.*;
mergedIntervals.add(newInterval);
1. Write a Java program to find the maximum profit by buying and selling stocks
(multiple transactions allowed).
return maxProfit;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
sb.append(node.val).append(",");
serializeHelper(node.left, sb);
serializeHelper(node.right, sb);
}
return maxSum;
}
}
import java.util.*;
public MinHeapPriorityQueue() {
heap = new int[DEFAULT_CAPACITY];
size = 0;
}
size++;
int index = size;
heap[index] = val;
int index = 1;
while (true) {
int smallest = index;
int leftChild = index * 2;
int rightChild = index * 2 + 1;
if (smallest == index) {
break;
}
swap(index, smallest);
index = smallest;
}
return min;
}
return heap[1];
}
return prefix;
}
}
import java.util.*;
class Interval {
int start;
int end;
int count = 0;
int end = intervals[0].end;
return count;
1. Write a Java program to find the longest palindromic substring in a given string.
indromicSubstring {
public String longestPalindrome(String s) {
int n = s.length();
boolean[][] dp = new boolean[n][n];
String longestPalindrome = "";
return longestPalindrome;
}
}
1. Given a list of words, write a Java program to find all valid word squares.
import java.util.*;
if (index == size) {
result.add(new ArrayList<>(wordSquare));
return;
}
if (!prefixMap.containsKey(prefix)) {
return;
}
import java.util.*;
return maxLength;
}
}
1. Given a list of strings, write a Java program to find the longest word made of
other words in the list.
import java.util.*;
return "";
}