Java Coding Questions
Basic Coding Questions
1. Write a Java program to print "Hello, World!" to the console.
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
1. Write a program to find the sum of two numbers entered by the user.
import [Link];
public class SumOfTwoNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the first number: ");
int num1 = [Link]();
[Link]("Enter the second number: ");
int num2 = [Link]();
int sum = num1 + num2;
[Link]("Sum: " + sum);
[Link]();
}
}
1. Write a Java program to check if a number is even or odd.
import [Link];
public class EvenOrOdd {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
String result = (num % 2 == 0) ? "even" : "odd";
[Link](num + " is " + result);
[Link]();
}
}
1. Write a function to find the factorial of a given number using recursion.
Java Coding Questions 1
public class Factorial {
public static void main(String[] args) {
int number = 5;
int factorial = findFactorial(number);
[Link]("Factorial of " + number + " is: " + factorial);
}
public static int findFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * findFactorial(n - 1);
}
}
1. Implement a function to check if a string is a palindrome.
public class Palindrome {
public static void main(String[] args) {
String str = "radar";
boolean isPalindrome = checkPalindrome(str);
[Link](str + " is a palindrome: " + isPalindrome);
}
public static boolean checkPalindrome(String str) {
int left = 0;
int right = [Link]() - 1;
while (left < right) {
if ([Link](left) != [Link](right)) {
return false;
}
left++;
right--;
}
return true;
}
}
1. Write a program to print the Fibonacci series up to a given number.
import [Link];
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of terms: ");
int n = [Link]();
int first = 0;
int second = 1;
Java Coding Questions 2
[Link]("Fibonacci Series: " + first + " " + second + " ");
for (int i = 2; i < n; i++) {
int next = first + second;
[Link](next + " ");
first = second;
second = next;
}
[Link]();
}
}
1. Write a Java function to reverse an array of integers in-place.
public class ReverseArray {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
reverseArray(arr);
[Link]("Reversed Array: ");
for (int num : arr) {
[Link](num + " ");
}
}
public static void reverseArray(int[] arr) {
int left = 0;
int right = [Link] - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
}
1. Implement a function to find the maximum element in an array.
public class MaxElementInArray {
public static void main(String[] args) {
int[] arr = { 10, 25, 7, 42, 32 };
int max = findMaxElement(arr);
[Link]("Maximum element in the array: " + max);
}
public static int findMaxElement(int[] arr) {
int max = arr[0];
for (int i = 1; i < [Link]; i++) {
Java Coding Questions 3
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
}
1. Write a program to remove duplicates from an array in Java.
import [Link];
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 3, 4, 5, 5, 6 };
int[] uniqueArray = removeDuplicates(arr);
[Link]("Array with duplicates removed: ");
for (int num : uniqueArray) {
[Link](num + " ");
}
}
public static int[] removeDuplicates(int[] arr) {
int[] uniqueArray = new int[[Link]];
int j = 0;
for (int i = 0; i < [Link] - 1; i++) {
if (arr[i] != arr[i + 1]) {
uniqueArray[j++] = arr[i];
}
}
uniqueArray[j++] = arr[[Link] - 1];
return [Link](uniqueArray, j);
}
}
1. Implement a function to check if a number is prime.
import [Link];
public class PrimeNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
boolean isPrime = checkPrime(num);
[Link](num + " is a prime number: " + isPrime);
[Link]();
}
Java Coding Questions 4
public static boolean checkPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
1. Write a Java program to swap two numbers without using a temporary variable.
public class SwapWithoutTempVariable {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
[Link]("Before swapping: num1 = " + num1 + ", num2 = " + num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
[Link]("After swapping: num1 = " + num1 + ", num2 = " + num2);
}
}
1. Implement a function to count
the occurrences of a specific element in an array.
public class CountOccurrences {
public static void main(String[] args) {
int[] arr = { 2, 3, 4, 2, 2, 5, 6, 2 };
int element = 2;
int count = countOccurrences(arr, element);
[Link]("Occurrences of " + element + " in the array: " + count);
}
public static int countOccurrences(int[] arr, int element) {
int count = 0;
for (int num : arr) {
if (num == element) {
count++;
}
}
return count;
}
}
Java Coding Questions 5
1. Write a Java function to calculate the area of a circle given its radius.
import [Link];
public class CircleArea {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the radius of the circle: ");
double radius = [Link]();
double area = calculateArea(radius);
[Link]("Area of the circle: " + area);
[Link]();
}
public static double calculateArea(double radius) {
return [Link] * radius * radius;
}
}
1. Implement a function to find the second largest element in an array.
import [Link];
public class SecondLargestElement {
public static void main(String[] args) {
int[] arr = { 10, 25, 7, 42, 32 };
int secondLargest = findSecondLargest(arr);
[Link]("Second largest element in the array: " + secondLargest);
}
public static int findSecondLargest(int[] arr) {
[Link](arr);
return arr[[Link] - 2];
}
}
1. Write a program to sort an array of integers in ascending order using the Bubble
Sort algorithm.
import [Link];
public class BubbleSort {
public static void main(String[] args) {
int[] arr = { 64, 34, 25, 12, 22, 11, 90 };
bubbleSort(arr);
[Link]("Sorted array: " + [Link](arr));
}
Java Coding Questions 6
public static void bubbleSort(int[] arr) {
int n = [Link];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
1. Implement a function to reverse a string in Java.
public class ReverseString {
public static void main(String[] args) {
String str = "Hello, World!";
String reversed = reverseString(str);
[Link]("Reversed string: " + reversed);
}
public static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return [Link]().toString();
}
}
1. Write a Java program to find the GCD (Greatest Common Divisor) of two
numbers.
import [Link];
public class GCD {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the first number: ");
int num1 = [Link]();
[Link]("Enter the second number: ");
int num2 = [Link]();
int gcd = findGCD(num1, num2);
[Link]("GCD of " + num1 + " and " + num2 + " is: " + gcd);
[Link]();
}
public static int findGCD(int a, int b) {
if (b == 0) {
return a;
}
return findGCD(b, a % b);
Java Coding Questions 7
}
}
1. Implement a function to check if two strings are anagrams.
import [Link];
public class Anagrams {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
boolean areAnagrams = checkAnagrams(str1, str2);
[Link](str1 + " and " + str2 + " are anagrams: " + areAnagrams);
}
public static boolean checkAnagrams(String str1, String str2) {
if ([Link]() != [Link]()) {
return false;
}
char[] chars1 = [Link]();
char[] chars2 = [Link]();
[Link](chars1);
[Link](chars2);
return [Link](chars1, chars2);
}
}
1. Write a Java program to find the factorial of a number using an iterative
approach.
import [Link];
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
int factorial = findFactorial(number);
[Link]("Factorial of " + number + " is: " + factorial);
[Link]();
}
public static int findFactorial(int n) {
int factorial = 1;
for (int i = 2; i <= n; i++) {
factorial *= i;
}
return factorial;
}
}
Java Coding Questions 8
1. Implement a function to find the sum of digits of a given number.
import [Link];
public class SumOfDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
int sum = sumOfDigits(number);
[Link]("Sum of digits of " + number + " is: " + sum);
[Link]();
}
public static int sumOfDigits(int num) {
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
}
1. Write a Java program to find the prime factors of a given number.
import [Link];
public class PrimeFactors {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
[Link]("Prime factors of " + number + ": ");
findPrimeFactors(number);
[Link]();
}
public static void findPrimeFactors(int num) {
for (int i = 2; i <= num; i++) {
while (num % i == 0) {
[Link](i + " ");
num /= i;
}
}
}
}
1. Implement a function to check if a string contains only digits.
Java Coding Questions 9
public class OnlyDigits {
public static void main(String[] args
) {
String str = "12345";
boolean containsOnlyDigits = checkOnlyDigits(str);
[Link](str + " contains only digits: " + containsOnlyDigits);
}
public static boolean checkOnlyDigits(String str) {
return [Link]("\\\\d+");
}
}
1. Write a program to print the Pascal's triangle for a given number of rows.
import [Link];
public class PascalsTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of rows: ");
int numRows = [Link]();
printPascalsTriangle(numRows);
[Link]();
}
public static void printPascalsTriangle(int numRows) {
for (int i = 0; i < numRows; i++) {
int num = 1;
for (int j = 0; j <= i; j++) {
[Link](num + " ");
num = num * (i - j) / (j + 1);
}
[Link]();
}
}
}
1. Implement a function to find the intersection of two arrays.
import [Link];
import [Link];
public class ArrayIntersection {
public static void main(String[] args) {
int[] arr1 = { 1, 2, 3, 4, 5 };
int[] arr2 = { 3, 4, 5, 6, 7 };
int[] intersection = findIntersection(arr1, arr2);
[Link]("Intersection of the arrays: ");
Java Coding Questions 10
for (int num : intersection) {
[Link](num + " ");
}
}
public static int[] findIntersection(int[] arr1, int[] arr2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> intersect = new HashSet<>();
for (int num : arr1) {
[Link](num);
}
for (int num : arr2) {
if ([Link](num)) {
[Link](num);
}
}
int[] result = new int[[Link]()];
int index = 0;
for (int num : intersect) {
result[index++] = num;
}
return result;
}
}
1. Write a Java program to find the nth term of the Fibonacci series using
recursion.
import [Link];
public class FibonacciRecursion {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the value of n: ");
int n = [Link]();
int nthTerm = fibonacci(n);
[Link]("The " + n + "th term of the Fibonacci series is: " + nthTe
rm);
[Link]();
}
public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
Moderate Java Coding Questions
1. Write a Java function to reverse a string in place.
Java Coding Questions 11
public class ReverseString {
public String reverseString(String s) {
char[] chars = [Link]();
int left = 0;
int right = [Link]() - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}
}
1. Given an array of integers, find the longest increasing subsequence.
public class LongestIncreasingSubsequence {
public int lengthOfLIS(int[] nums) {
int n = [Link];
int[] dp = new int[n];
int maxLength = 0;
for (int i = 0; i < n; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = [Link](dp[i], dp[j] + 1);
}
}
maxLength = [Link](maxLength, dp[i]);
}
return maxLength;
}
}
1. Write a Java program to find the intersection of two arrays.
import [Link].*;
public class IntersectionOfArrays {
public int[] intersect(int[] nums1, int[] nums2) {
[Link](nums1);
[Link](nums2);
List<Integer> result = new ArrayList<>();
int i = 0;
Java Coding Questions 12
int j = 0;
while (i < [Link] && j < [Link]) {
if (nums1[i] == nums2[j]) {
[Link](nums1[i]);
i++;
j++;
} else if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
int[] intersection = new int[[Link]()];
for (int k = 0; k < [Link](); k++) {
intersection[k] = [Link](k);
}
return intersection;
}
}
1. Implement a stack that supports push, pop, and getMin operations in O(1) time.
import [Link].*;
public class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int val) {
[Link](val);
if ([Link]() || val <= [Link]()) {
[Link](val);
}
}
public void pop() {
int val = [Link]();
if (val == [Link]()) {
[Link]();
}
}
public int top() {
return [Link]();
}
public int getMin() {
Java Coding Questions 13
return [Link]();
}
}
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) {
[Link] = val;
}
}
public class DiameterOfBinaryTree {
private int diameter;
public int diameterOfBinaryTree(TreeNode root) {
diameter = 0;
depth(root);
return diameter;
}
private int depth(TreeNode node) {
if (node == null) {
return 0;
}
int leftDepth = depth([Link]);
int rightDepth = depth([Link]);
diameter = [Link](diameter, leftDepth + rightDepth);
return 1 + [Link](leftDepth, rightDepth);
}
}
1. Implement a queue using two stacks in Java with enqueue and dequeue
operations.
import [Link];
public class QueueUsingStacks {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public QueueUsingStacks() {
stack1 = new Stack<>();
stack2 = new Stack<>();
Java Coding Questions 14
}
public void enqueue(int val) {
[Link](val);
}
public int dequeue() {
if (isEmpty()) {
throw new RuntimeException("Queue is empty");
}
if ([Link]()) {
while (![Link]()) {
[Link]([Link]());
}
}
return [Link]();
}
public int peek() {
if (isEmpty()) {
throw new RuntimeException("Queue is empty");
}
if ([Link]()) {
while (![Link]()) {
[Link]([Link]());
}
}
return [Link]();
}
public boolean isEmpty() {
return [Link]() && [Link]();
}
}
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) {
[Link] = val;
}
}
public class K
thSmallestElementInBST {
public int kthSmallest(TreeNode root, int k) {
int[] result = new int[2];
inorder(root, k, result);
return result[1];
}
Java Coding Questions 15
private void inorder(TreeNode node, int k, int[] result) {
if (node == null) {
return;
}
inorder([Link], k, result);
if (++result[0] == k) {
result[1] = [Link];
return;
}
inorder([Link], k, result);
}
}
1. Given a matrix of 0s and 1s, find the largest square submatrix with all 1s.
public class MaxSquareSubmatrix {
public int maximalSquare(char[][] matrix) {
if (matrix == null || [Link] == 0 || matrix[0].length == 0) {
return 0;
}
int m = [Link];
int n = matrix[0].length;
int[][] dp = new int[m + 1][n + 1];
int maxSide = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (matrix[i - 1][j - 1] == '1') {
dp[i][j] = [Link]([Link](dp[i - 1][j], dp[i][j - 1]), dp[i -
1][j - 1]) + 1;
maxSide = [Link](maxSide, dp[i][j]);
}
}
}
return maxSide * maxSide;
}
}
1. Write a Java program to find all valid IP addresses in a given string.
import [Link].*;
public class ValidIPAddresses {
public List<String> restoreIpAddresses(String s) {
List<String> result = new ArrayList<>();
if ([Link]() < 4 || [Link]() > 12) {
Java Coding Questions 16
return result;
}
backtrack(s, 0, new ArrayList<>(), result);
return result;
}
private void backtrack(String s, int start, List<String> temp, List<String> resul
t) {
if ([Link]() == 4 && start == [Link]()) {
[Link]([Link](".", temp));
return;
}
for (int i = 1; i <= 3; i++) {
if (start + i > [Link]()) {
break;
}
String part = [Link](start, start + i);
if (isValidPart(part)) {
[Link](part);
backtrack(s, start + i, temp, result);
[Link]([Link]() - 1);
}
}
}
private boolean isValidPart(String part) {
if ([Link]() > 1 && [Link]("0")) {
return false;
}
int num = [Link](part);
return num >= 0 && num <= 255;
}
}
1. Implement a priority queue (min-heap) in Java with insert and extractMin
operations.
import [Link];
import [Link];
public class MinHeap {
private List<Integer> heap;
public MinHeap() {
heap = new ArrayList<>();
}
public void insert(int val) {
[Link](val);
siftUp([Link]() - 1);
}
public int extractMin() {
Java Coding Questions 17
if (isEmpty()) {
throw new RuntimeException("Heap is empty");
}
int min = [Link](0);
int lastIdx = [Link]() - 1;
[Link](0, [Link](lastIdx));
[Link](lastIdx);
siftDown(0);
return min;
}
public boolean isEmpty() {
return [Link]();
}
private void siftUp(int index) {
while (index > 0) {
int parentIdx = (index - 1) / 2;
if ([Link](parentIdx) > [Link](index)) {
swap(parentIdx, index);
index = parentIdx;
} else {
break;
}
}
}
private void siftDown(int index) {
int size = [Link]();
while (index < size) {
int leftChildIdx = 2 * index + 1;
int rightChildIdx = 2 * index + 2;
int minIdx = index;
if (leftChildIdx < size && [Link](leftChildIdx) < [Link](minIdx)) {
minIdx = leftChildIdx;
}
if (rightChildIdx < size && [Link](rightChildIdx) < [Link](minIdx)) {
minIdx = rightChildIdx;
}
if (minIdx != index) {
swap(index, minIdx);
index = minIdx;
} else {
break;
}
}
}
private void swap(int i, int j) {
int temp = [Link](i);
[Link](i, [Link](j));
[Link](j, temp);
}
}
Java Coding Questions 18
1. Given an array of integers, find the maximum product subarray.
public class MaximumProductSubarray {
public int maxProduct(int[] nums) {
int n = [Link];
if (n == 0) {
return 0;
}
int maxProduct = nums[0];
int maxEndingHere = nums[0];
int minEndingHere = nums[0];
for (int i = 1; i < n; i++) {
int temp = maxEndingHere;
maxEndingHere = [Link](nums[i], [Link](nums[i] * maxEndingHere, nums
[i] * minEndingHere));
minEndingHere = [Link](nums[i], [Link](nums[i] * temp, nums[i] * minEn
dingHere));
maxProduct = [Link](maxProduct, maxEndingHere);
}
return maxProduct;
}
}
1. Implement a function to check if a binary tree is balanced in Java.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
[Link] = val;
}
}
public class BalancedBinaryTree {
public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}
private int height(TreeNode node) {
if (node == null) {
return 0;
}
int leftHeight = height([Link]);
if (leftHeight == -1) {
return -1;
}
Java Coding Questions 19
int rightHeight = height([Link]);
if (rightHeight == -1) {
return -1;
}
if ([Link](leftHeight - rightHeight) > 1) {
return -1;
}
return [Link](leftHeight, rightHeight) + 1;
}
}
1. Write a Java program to implement a least recently used (LRU) cache.
import [Link].*;
class LRUCache {
private LinkedHashMap<Integer, Integer> cache;
private int capacity;
public LRUCache(int capacity) {
this
.capacity = capacity;
cache = new LinkedHashMap<>(capacity, 0.75f, true);
}
public int get(int key) {
return [Link](key, -1);
}
public void put(int key, int value) {
[Link](key, value);
if ([Link]() > capacity) {
int oldestKey = [Link]().iterator().next().getKey();
[Link](oldestKey);
}
}
}
1. Given a list of intervals, merge overlapping intervals in Java.
import [Link].*;
public class MergeIntervals {
public int[][] merge(int[][] intervals) {
if (intervals == null || [Link] == 0) {
return new int[0][0];
}
[Link](intervals, [Link](a -> a[0]));
Java Coding Questions 20
List<int[]> mergedIntervals = new ArrayList<>();
int[] currentInterval = intervals[0];
for (int i = 1; i < [Link]; i++) {
if (currentInterval[1] >= intervals[i][0]) {
currentInterval[1] = [Link](currentInterval[1], intervals[i][1]);
} else {
[Link](currentInterval);
currentInterval = intervals[i];
}
}
[Link](currentInterval);
return [Link](new int[[Link]()][]);
}
}
1. Write a Java program to find the longest palindromic substring in a given string.
public class LongestPalindromicSubstring {
public String longestPalindrome(String s) {
int n = [Link]();
if (n == 0) {
return "";
}
boolean[][] dp = new boolean[n][n];
int start = 0;
int maxLength = 1;
for (int i = 0; i < n; i++) {
dp[i][i] = true;
}
for (int i = n - 1; i >= 0; i--) {
for (int j = i + 1; j < n; j++) {
if ([Link](i) == [Link](j)) {
if (j - i == 1 || dp[i + 1][j - 1]) {
dp[i][j] = true;
if (j - i + 1 > maxLength) {
maxLength = j - i + 1;
start = i;
}
}
}
}
}
return [Link](start, start + maxLength);
}
}
Java Coding Questions 21
1. Implement a function to find the longest common prefix of an array of strings.
public class LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if (strs == null || [Link] == 0) {
return "";
}
StringBuilder prefix = new StringBuilder(strs[0]);
for (int i = 1; i < [Link]; i++) {
int j = 0;
while (j < [Link]() && j < strs[i].length() && [Link](j) ==
strs[i].charAt(j)) {
j++;
}
[Link](j);
}
return [Link]();
}
}
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) {
[Link] = val;
}
}
public class MaximumPathSum {
private int maxSum;
public int maxPathSum(TreeNode root) {
maxSum = Integer.MIN_VALUE;
findMaxPathSum(root);
return maxSum;
}
private int findMaxPathSum(TreeNode node) {
if (node == null) {
return 0;
}
int leftSum = [Link](findMaxPathSum([Link]), 0);
int rightSum = [Link](findMaxPathSum([Link]), 0);
Java Coding Questions 22
int pathSum = [Link] + leftSum + rightSum;
maxSum = [Link](maxSum, pathSum);
return [Link] + [Link](leftSum, rightSum);
}
}
1. Implement a function to find the first non-repeated character in a string.
import [Link].*;
public class FirstNonRepeatedCharacter {
public char findFirstNonRepeatedCharacter(String s) {
Map<Character, Integer> charCount = new LinkedHashMap<>();
for (char c : [Link]()) {
[Link](c, [Link](c, 0) + 1);
}
for ([Link]<Character, Integer> entry : [Link]()) {
if ([Link]() == 1) {
return [Link]();
}
}
return '\\0'; // If no non-repeated character found
}
}
1. Write a Java program to implement a stack with getMin operation in O(1) time.
import [Link].*;
public class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int val) {
[Link](val);
if ([Link]() || val <= [Link]()) {
[Link](val);
}
}
public void pop() {
int val = [Link]();
if (val == [Link]()) {
Java Coding Questions 23
[Link]();
}
}
public int top() {
return [Link]();
}
public int getMin() {
return [Link]();
}
}
1. Given a list of words, find the longest word that can be formed by other words in
the list.
import [Link].*;
public class LongestWordInDictionary {
public String longestWord(String[] words) {
[Link](words);
Set<String> wordSet = new HashSet<>();
String longestWord = "";
for (String word : words) {
if ([Link]() == 1 || [Link]([Link](0, [Link]()
- 1))) {
[Link](word);
if ([Link]() > [Link]()) {
longestWord = word;
}
}
}
return longestWord;
}
}
1. Implement a function to find the longest substring with at most two distinct
characters.
public class LongestSubstringWithTwoDistinct {
public int lengthOfLongestSubstringTwoDistinct(String s) {
int n = [Link]();
if (n == 0) {
return 0;
}
int maxLength = 0;
int left = 0;
Java Coding Questions 24
int right = 0;
Map<Character, Integer> charCount = new HashMap<>();
while (right < n) {
char c = [Link](right);
[Link](c, [Link](c, 0) + 1);
while ([Link]() > 2) {
char leftChar = [Link](left);
[Link](leftChar, [Link](leftChar) - 1);
if ([Link](leftChar) == 0)
{
[Link](leftChar);
}
left++;
}
maxLength = [Link](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 [Link].*;
public class WordSearchII {
private static final int[] dx = { -1, 1, 0, 0 };
private static final int[] dy = { 0, 0, -1, 1 };
public List<String> findWords(char[][] board, String[] words) {
Trie trie = new Trie();
for (String word : words) {
[Link](word);
}
Set<String> result = new HashSet<>();
int m = [Link];
int n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dfs(board, i, j, [Link](), result);
}
}
return new ArrayList<>(result);
}
private void dfs(char[][] board, int x, int y, TrieNode node, Set<String> result)
{
Java Coding Questions 25
char c = board[x][y];
if (c == '#' || [Link][c - 'a'] == null) {
return;
}
node = [Link][c - 'a'];
if ([Link] != null) {
[Link]([Link]);
[Link] = null; // Avoid duplicates
}
board[x][y] = '#'; // Mark as visited
for (int i = 0; i < 4; i++) {
int newX = x + dx[i];
int newY = y + dy[i];
if (newX >= 0 && newX < [Link] && newY >= 0 && newY < board[0].lengt
h) {
dfs(board, newX, newY, node, result);
}
}
board[x][y] = c; // Restore the cell
}
}
class TrieNode {
TrieNode[] children;
String word;
TrieNode() {
children = new TrieNode[26];
word = null;
}
}
class Trie {
private TrieNode root;
Trie() {
root = new TrieNode();
}
void insert(String word) {
TrieNode node = root;
for (char c : [Link]()) {
int index = c - 'a';
if ([Link][index] == null) {
[Link][index] = new TrieNode();
}
node = [Link][index];
}
[Link] = word;
}
TrieNode getRoot() {
return root;
Java Coding Questions 26
}
}
1. Write a Java program to find the number of islands in a 2D grid of '1's and '0's.
public class NumberOfIslands {
public int numIslands(char[][] grid) {
int m = [Link];
int n = grid[0].length;
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
count++;
}
}
}
return count;
}
private void dfs(char[][] grid, int x, int y) {
int m = [Link];
int n = grid[0].length;
if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] != '1') {
return;
}
grid[x][y] = '0'; // Mark as visited
dfs(grid, x - 1, y);
dfs(grid, x + 1, y);
dfs(grid, x, y - 1);
dfs(grid, x, y + 1);
}
}
1. Implement an iterator for a binary search tree (BST) in Java.
import [Link].*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
[Link] = val;
}
Java Coding Questions 27
}
public class BSTIterator {
private Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<>();
pushAllLeft(root);
}
public int next() {
TreeNode node = [Link]();
pushAllLeft([Link]);
return [Link];
}
public boolean hasNext() {
return ![Link]();
}
private void pushAllLeft(TreeNode node) {
while (node != null) {
[Link](node);
node = [Link];
}
}
}
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) {
[Link] = val;
}
}
public class SumOfLeftLeaves {
public int sumOfLeftLeaves(TreeNode root) {
return sumOfLeftLeavesHelper(root, false);
}
private int sumOfLeftLeavesHelper(TreeNode node, boolean isLeft) {
if (node == null) {
return 0;
}
if ([Link] == null && [Link] == null && isLeft) {
return [Link];
}
int leftSum = sumOfLeftLeavesHelper([Link], true);
Java Coding Questions 28
int rightSum = sumOfLeftLeavesHelper([Link], false);
return leftSum + rightSum;
}
}
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) {
[Link] = val;
}
}
public class ValidateBST {
public boolean isValidBST(TreeNode root) {
return isValidBSTHelper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean isValidBSTHelper(TreeNode node, long min, long max) {
if (node == null) {
return true;
}
if ([Link] <= min || [Link] >= max) {
return false;
}
return isValidBSTHelper([Link], min, [Link]) && isValidBSTHelper([Link]
ht, [Link], max);
}
}
1. Implement a stack using linked lists in Java with push, pop, and peek operations.
class ListNode {
int val;
ListNode next;
ListNode(int val) {
[Link] = val;
}
Java Coding Questions 29
}
public class LinkedStack {
private ListNode top;
public void push(int val) {
ListNode newNode = new ListNode(val);
[Link] = top;
top = newNode;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
int popped = [Link];
top = [Link];
return popped;
}
public int peek() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return [Link];
}
public boolean isEmpty() {
return top == null;
}
}
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) {
[Link] = val;
}
}
public class KthSmallestInBST {
private int k;
private int result;
public int kthSmallest(TreeNode root, int k) {
this.k = k;
inorderTraversal(root);
return result;
}
private void inorderTraversal(TreeNode node) {
Java Coding Questions 30
if (node == null) {
return;
}
inorderTraversal([Link]);
k--;
if (k == 0) {
result = [Link];
return;
}
inorderTraversal([Link]);
}
}
1. Given an array of integers, find all pairs that sum up to a specific target.
import [Link].*;
public class TwoSum {
public List<List<Integer>> twoSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < [Link]; i++) {
int complement = target - nums[i];
if ([Link](complement)) {
[Link]([Link](nums[i], complement));
}
[Link](nums[i], i);
}
return result;
}
}
1. Implement a queue using two stacks in Java with enqueue and dequeue
operations.
import [Link];
public class QueueUsingStacks {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public QueueUsingStacks() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void enqueue(int val) {
[Link](val);
}
Java Coding Questions 31
public int dequeue() {
if (isEmpty()) {
throw new RuntimeException("Queue is empty");
}
if ([Link]()) {
while (![Link]()) {
[Link]([Link]());
}
}
return [Link]();
}
public int peek() {
if (isEmpty()) {
throw new RuntimeException("Queue is empty");
}
if ([Link]()) {
while (![Link]()) {
[Link]([Link]());
}
}
return [Link]();
}
public boolean isEmpty() {
return [Link]() && [Link]();
}
}
1. Write a Java function to reverse a linked list.
class ListNode {
int val;
ListNode next;
ListNode(int val) {
[Link] = val;
}
}
public class ReverseLinkedList {
public ListNode reverse(ListNode head) {
ListNode prev = null;
ListNode current = head;
ListNode next;
while (current != null) {
next = [Link];
[Link] = prev;
prev = current;
current = next;
}
return prev;
Java Coding Questions 32
}
}
1. Given a 2D grid of 1s and 0s, find the size of the largest island (connected 1s).
public class LargestIsland {
private static final int[] dx = { -1, 1, 0, 0 };
private static final int[] dy = { 0, 0, -1, 1 };
public int largestIsland(int[][] grid) {
int maxArea = 0;
int rows = [Link];
int cols = grid[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == 1) {
maxArea = [Link](maxArea, dfs(grid, i, j));
}
}
}
return maxArea;
}
private int dfs(int[][] grid, int x, int y) {
if (x < 0 || x >= [Link] || y < 0 || y >= grid[0].length || grid[x][y] ==
0) {
return 0;
}
grid[x][y] = 0;
int area = 1;
for (int i = 0; i < 4; i++) {
int newX = x + dx[i];
int newY = y + dy[i];
area += dfs(grid, newX, newY);
}
return area;
}
}
1. Implement a Trie (prefix tree) in Java to support insert, search, and startsWith
operations.
class TrieNode {
boolean isEnd;
TrieNode[] children;
TrieNode() {
Java Coding Questions 33
isEnd = false;
children = new TrieNode[26];
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for (char c : [Link]()) {
int index = c - 'a';
if ([Link][index] == null) {
[Link][index] = new TrieNode();
}
node = [Link][index];
}
[Link] = true;
}
public boolean search(String word) {
TrieNode node = findNode(word);
return node != null && node
.isEnd;
}
public boolean startsWith(String prefix) {
return findNode(prefix) != null;
}
private TrieNode findNode(String word) {
TrieNode node = root;
for (char c : [Link]()) {
int index = c - 'a';
if ([Link][index] == null) {
return null;
}
node = [Link][index];
}
return node;
}
}
1. Write a Java program to find the longest common subsequence (LCS) of two
strings.
public class LongestCommonSubsequence {
public String longestCommonSubsequence(String text1, String text2) {
int m = [Link]();
Java Coding Questions 34
int n = [Link]();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if ([Link](i - 1) == [Link](j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = [Link](dp[i - 1][j], dp[i][j - 1]);
}
}
}
StringBuilder lcs = new StringBuilder();
int i = m, j = n;
while (i > 0 && j > 0) {
if ([Link](i - 1) == [Link](j - 1)) {
[Link](0, [Link](i - 1));
i--;
j--;
} else if (dp[i - 1][j] > dp[i][j - 1]) {
i--;
} else {
j--;
}
}
return [Link]();
}
}
1. Given a matrix of 0s and 1s, find the size of the largest square submatrix with all
1s.
public class MaxSquareSubmatrix {
public int maximalSquare(char[][] matrix) {
if (matrix == null || [Link] == 0 || matrix[0].length == 0) {
return 0;
}
int m = [Link];
int n = matrix[0].length;
int[][] dp = new int[m + 1][n + 1];
int maxSide = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (matrix[i - 1][j - 1] == '1') {
dp[i][j] = [Link]([Link](dp[i - 1][j], dp[i][j - 1]), dp[i -
1][j - 1]) + 1;
maxSide = [Link](maxSide, dp[i][j]);
}
}
Java Coding Questions 35
}
return maxSide * maxSide;
}
}
1. Implement a hash table (dictionary) in Java with put, get, and remove
operations.
class Entry<K, V> {
K key;
V value;
Entry<K, V> next;
Entry(K key, V value) {
[Link] = key;
[Link] = value;
}
}
public class HashTable<K, V> {
private static final int INITIAL_CAPACITY = 16;
private Entry<K, V>[] table;
private int size;
public HashTable() {
table = new Entry[INITIAL_CAPACITY];
size = 0;
}
public void put(K key, V value) {
int index = getIndex(key);
Entry<K, V> entry = new Entry<>(key, value);
if (table[index] == null) {
table[index] = entry;
size++;
} else {
Entry<K, V> current = table[index];
while ([Link] != null) {
if ([Link](key)) {
[Link] = value;
return;
}
current = [Link];
}
[Link] = entry;
size++;
}
if (size >= [Link] * 0.75) {
resize();
}
}
Java Coding Questions 36
public V get(K key) {
int index = getIndex(key);
Entry<K, V> current = table[index];
while (current != null) {
if ([Link](key)) {
return [Link];
}
current = [Link];
}
return null;
}
public void remove(K key) {
int index = getIndex(key);
Entry<K, V> prev = null;
Entry<K, V> current = table[index];
while (current != null) {
if ([Link](key)) {
if (prev == null) {
table[index] = [Link];
} else {
[Link] = [Link];
}
size--;
return;
}
prev = current;
current = [Link];
}
}
public boolean containsKey(K key) {
int index = getIndex(key);
Entry<K, V> current = table[index];
while (current != null) {
if ([Link](key)) {
return true;
}
current = [Link];
}
return false;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
private int getIndex(K key) {
int hashCode = [Link]();
return hashCode % [Link];
}
Java Coding Questions 37
private void resize() {
int newCapacity = [Link] * 2;
Entry<K, V>[] newTable = new Entry[newCapacity];
for (Entry<K, V> entry : table) {
while (entry != null) {
int newIndex = [Link]() % newCapacity;
Entry<K, V> newEntry = new Entry<>([Link], [Link]);
[Link] = newTable[newIndex];
newTable[newIndex] = newEntry;
entry = [Link];
}
}
table = newTable;
}
}
1. Write a Java function to find the first non-repeated character in a string.
import [Link];
import [Link];
public class FirstNonRepeatedCharacter {
public char findFirstNonRepeatedCharacter(String str) {
Map<Character, Integer> charCountMap = new HashMap<>();
for (char c : [Link]()) {
[Link](c, [Link](c, 0) + 1);
}
for (char c : [Link]()) {
if ([Link](c) == 1) {
return c;
}
}
return '\\0'; // Return null character if no non-repeated character found
}
}
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) {
Java Coding Questions 38
[Link] = val;
}
}
public class MaxPathSum {
private int maxSum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
findMaxPathSum(root);
return maxSum;
}
private int findMaxPathSum(TreeNode node) {
if (node == null) {
return 0;
}
int leftSum = [Link](findMaxPathSum([Link]), 0);
int rightSum = [Link](findMaxPathSum([Link]), 0);
int pathSum = [Link] + leftSum + rightSum;
maxSum = [Link](maxSum, pathSum);
return [Link] + [Link](leftSum, rightSum);
}
}
1. Implement a priority queue (min-heap) in Java with insert and extractMin
operations.
import [Link];
import [Link];
public class MinHeap {
private List<Integer> heap;
public MinHeap() {
heap = new ArrayList<>();
}
public void insert(int val) {
[Link](val);
siftUp([Link]() - 1);
}
public int extractMin() {
if (isEmpty()) {
throw new RuntimeException("Heap is empty");
}
int min = [Link](0);
int lastIdx = [Link]() - 1;
[Link](0, [Link](lastIdx));
[Link](lastIdx);
siftDown(0);
Java Coding Questions 39
return min;
}
public boolean isEmpty() {
return [Link]();
}
private void siftUp(int index) {
while (index > 0) {
int parentIdx = (index - 1) / 2;
if ([Link](parentIdx) > [Link](index)) {
swap(parentIdx, index);
index = parentIdx;
} else {
break;
}
}
}
private void siftDown(int index) {
int size = [Link]();
while (index < size) {
int leftChildIdx = 2 * index + 1;
int rightChildIdx = 2 * index + 2;
int minIdx = index;
if (leftChildIdx < size && [Link](leftChildIdx) < [Link](minIdx)) {
minIdx = leftChildIdx;
}
if (rightChildIdx < size && [Link](rightChildIdx) < [Link](minIdx)) {
minIdx = rightChildIdx;
}
if (minIdx != index) {
swap(index, minIdx);
index = minIdx;
} else {
break;
}
}
}
private void swap(int i, int j) {
int temp = [Link](i);
[Link](i, [Link](j));
[Link](j, temp);
}
}
1. Write a Java program to merge k sorted arrays into a single sorted array.
import [Link];
public class MergeKSortedArrays {
public int[] mergeKSortedArrays(int[][] arrays) {
Java Coding Questions 40
if (arrays == null || [Link] == 0) {
return new int[0];
}
PriorityQueue<ArrayElement> pq = new PriorityQueue<>((a, b) -> [Link] - [Link]);
int totalSize = 0;
for (int i = 0; i < [Link]; i++) {
if (arrays[i].length > 0) {
[Link](new ArrayElement(arrays[i][0], i, 0));
totalSize += arrays[i].length;
}
}
int[] mergedArray = new int[totalSize];
int index = 0;
while (![Link]()) {
ArrayElement element = [Link]();
mergedArray[index++] = [Link];
int arrayIndex = [Link];
int nextIndex = [Link] + 1;
if (nextIndex < arrays[arrayIndex].length) {
[Link](new ArrayElement(arrays[arrayIndex][nextIndex], arrayIndex, n
extIndex));
}
}
return mergedArray;
}
class ArrayElement {
int val;
int arrayIndex;
int nextIndex;
ArrayElement(int val, int arrayIndex, int nextIndex) {
[Link] = val;
[Link] = arrayIndex;
[Link] = nextIndex;
}
}
}
1. Given an array of integers, find the length of the longest increasing subarray.
public class LongestIncreasingSubarray {
public int findLengthOfLIS(int[] nums) {
int n = [Link];
int[] dp = new int[n];
dp[0] = 1;
int maxLength = 1;
for (int i = 1; i < n; i++) {
Java Coding Questions 41
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = [Link](dp[i], dp[j] + 1);
}
}
maxLength = [Link](maxLength, dp[i]);
}
return maxLength;
}
}
1. Implement a graph in Java with BFS (Breadth-First Search) and DFS (Depth-
First Search) traversal algorithms.
import [Link].*;
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<>();
}
}
public void addEdge(int u, int v) {
adjList[u].add(v);
adjList[v].add(u); // For undirected graph
}
public void bfsTraversal(int start) {
boolean[] visited = new boolean[V];
Queue<Integer> queue = new LinkedList<>();
[Link](start);
visited[start] = true;
while (![Link]()) {
int node = [Link]();
[Link](node + " ");
for (int neighbor : adjList[node]) {
if (!visited[neighbor]) {
[Link](neighbor);
visited[neighbor] = true;
}
}
}
}
Java Coding Questions 42
public void dfsTraversal(int start) {
boolean[] visited = new boolean[V];
dfsHelper(start, visited);
}
private void dfsHelper(int node, boolean[] visited) {
visited[node] = true;
[Link](node + " ");
for (int neighbor : adjList[node]) {
if (!visited[neighbor]) {
dfsHelper(neighbor, visited);
}
}
}
}
1. Write a Java program to find the median of two sorted arrays of different sizes.
public class MedianOfTwoSortedArrays {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = [Link];
int n = [Link];
if (m > n) {
return find
MedianSortedArrays(nums2, nums1);
}
int left = 0;
int right = m;
int total = (m + n + 1) / 2;
while (left < right) {
int partition1 = left + (right - left) / 2;
int partition2 = total - partition1;
int maxLeft1 = (partition1 == 0) ? Integer.MIN_VALUE : nums1[partition1 -
1];
int minRight1 = (partition1 == m) ? Integer.MAX_VALUE : nums1[partition1];
int maxLeft2 = (partition2 == 0) ? Integer.MIN_VALUE : nums2[partition2 -
1];
int minRight2 = (partition2 == n) ? Integer.MAX_VALUE : nums2[partition2];
if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {
if ((m + n) % 2 == 0) {
return ([Link](maxLeft1, maxLeft2) + [Link](minRight1, minRigh
t2)) / 2.0;
} else {
return [Link](maxLeft1, maxLeft2);
}
} else if (maxLeft1 > minRight2) {
right = partition1 - 1;
Java Coding Questions 43
} else {
left = partition1 + 1;
}
}
throw new IllegalArgumentException("Input arrays are not sorted.");
}
}
1. Given a 2D grid of characters, find all valid words from a dictionary using DFS or
Trie.
import [Link].*;
public class WordSearchII {
private static final int[] dx = { -1, 1, 0, 0 };
private static final int[] dy = { 0, 0, -1, 1 };
public List<String> findWords(char[][] board, String[] words) {
Trie trie = new Trie();
for (String word : words) {
[Link](word);
}
Set<String> result = new HashSet<>();
int m = [Link];
int n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dfs(board, i, j, [Link](), result);
}
}
return new ArrayList<>(result);
}
private void dfs(char[][] board, int x, int y, TrieNode node, Set<String> result)
{
char c = board[x][y];
if (c == '#' || [Link][c - 'a'] == null) {
return;
}
node = [Link][c - 'a'];
if ([Link] != null) {
[Link]([Link]);
[Link] = null; // Avoid duplicates
}
board[x][y] = '#'; // Mark as visited
for (int i = 0; i < 4; i++) {
int newX = x + dx[i];
Java Coding Questions 44
int newY = y + dy[i];
if (newX >= 0 && newX < [Link] && newY >= 0 && newY < board[0].lengt
h) {
dfs(board, newX, newY, node, result);
}
}
board[x][y] = c; // Restore the cell
}
}
class TrieNode {
TrieNode[] children;
String word;
TrieNode() {
children = new TrieNode[26];
word = null;
}
}
class Trie {
private TrieNode root;
Trie() {
root = new TrieNode();
}
void insert(String word) {
TrieNode node = root;
for (char c : [Link]()) {
int index = c - 'a';
if ([Link][index] == null) {
[Link][index] = new TrieNode();
}
node = [Link][index];
}
[Link] = word;
}
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) {
Java Coding Questions 45
[Link] = val;
[Link] = null;
}
}
public class CircularLinkedList {
private ListNode head;
public CircularLinkedList() {
head = null;
}
public void insert(int val) {
ListNode newNode = new ListNode(val);
if (head == null) {
head = newNode;
[Link] = head;
} else {
ListNode tail = head;
while ([Link] != head) {
tail = [Link];
}
[Link] = newNode;
[Link] = head;
}
}
public void delete(int val) {
if (head == null) {
return;
}
ListNode curr = head;
ListNode prev = null;
while ([Link] != head) {
if ([Link] == val) {
if (prev != null) {
[Link] = [Link];
} else {
ListNode tail = head;
while ([Link] != head) {
tail = [Link];
}
head = [Link];
[Link] = head;
}
return;
}
prev = curr;
curr = [Link];
}
if ([Link] == val) {
if (prev != null) {
[Link] = head;
} else {
head = null;
}
}
}
Java Coding Questions 46
public void traverse() {
if (head == null) {
return;
}
ListNode curr = head;
do {
[Link]([Link] + " ");
curr = [Link];
} while (curr != head);
}
}
1. Write a Java program to find the maximum sum subarray using the Kadane's
algorithm.
public class MaximumSubarraySum {
public int maxSubArray(int[] nums) {
int maxSum = nums[0];
int currentSum = nums[0];
for (int i = 1; i < [Link]; i++) {
currentSum = [Link](nums[i], currentSum + nums[i]);
maxSum = [Link](maxSum, currentSum);
}
return maxSum;
}
}
1. Given a list of intervals, merge overlapping intervals in Java.
import [Link].*;
public class MergeIntervals {
public int[][] merge(int[][] intervals) {
if (intervals == null || [Link] == 0) {
return new int[0][0];
}
[Link](intervals, [Link](a -> a[0]));
List<int[]> mergedIntervals = new ArrayList<>();
int[] currentInterval = intervals[0];
for (int i = 1; i < [Link]; i++) {
if (currentInterval[1] >= intervals[i][0]) {
currentInterval[1] = [Link](currentInterval[1], intervals[i][1]);
} else {
[Link](currentInterval);
currentInterval = intervals[i];
}
Java Coding Questions 47
}
[Link](currentInterval);
return
[Link](new int[[Link]()][]);
}
}
1. Implement a binary search in Java to find the index of a given element in a
sorted array.
public class BinarySearch {
public int search(int[] nums, int target) {
int left = 0;
int right = [Link] - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
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) {
[Link] = val;
}
}
public class SerializeDeserializeBinaryTree {
private static final String NULL_NODE = "null";
private static final String DELIMITER = ",";
// Serialize a binary tree to a string
Java Coding Questions 48
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
buildString(root, sb);
return [Link]();
}
private void buildString(TreeNode node, StringBuilder sb) {
if (node == null) {
[Link](NULL_NODE).append(DELIMITER);
} else {
[Link]([Link]).append(DELIMITER);
buildString([Link], sb);
buildString([Link], sb);
}
}
// Deserialize a string to a binary tree
public TreeNode deserialize(String data) {
Queue<String> queue = new LinkedList<>([Link]([Link](DELIMITER)));
return buildTree(queue);
}
private TreeNode buildTree(Queue<String> queue) {
String val = [Link]();
if ([Link](NULL_NODE)) {
return null;
} else {
TreeNode node = new TreeNode([Link](val));
[Link] = buildTree(queue);
[Link] = buildTree(queue);
return node;
}
}
}
1. Given a directed graph, check if it contains a cycle using DFS or BFS in Java.
import [Link].*;
public class CycleInDirectedGraph {
public boolean hasCycle(int numCourses, int[][] prerequisites) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < numCourses; i++) {
[Link](new ArrayList<>());
}
for (int[] prerequisite : prerequisites) {
[Link](prerequisite[0]).add(prerequisite[1]);
}
int[] visited = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
if (hasCycleDFS(i, graph, visited)) {
return true;
Java Coding Questions 49
}
}
return false;
}
private boolean hasCycleDFS(int course, List<List<Integer>> graph, int[] visited)
{
if (visited[course] == 1) {
return true;
}
if (visited[course] == -1) {
return false;
}
visited[course] = 1;
for (int prerequisite : [Link](course)) {
if (hasCycleDFS(prerequisite, graph, visited)) {
return true;
}
}
visited[course] = -1;
return false;
}
}
Hard Level Coding Questions
1. Implement a function to find the longest increasing subsequence in a given
array.
public class LongestIncreasingSubsequence {
public int lengthOfLIS(int[] nums) {
int n = [Link];
int[] dp = new int[n];
int maxLength = 0;
for (int i = 0; i < n; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = [Link](dp[i], dp[j] + 1);
}
}
maxLength = [Link](maxLength, dp[i]);
}
return maxLength;
}
}
Java Coding Questions 50
1. Given a 2D grid of characters and a word, check if the word exists in the grid.
public class WordSearch {
public boolean exist(char[][] board, String word) {
int m = [Link];
int n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (dfs(board, i, j, word, 0)) {
return true;
}
}
}
return false;
}
private boolean dfs(char[][] board, int x, int y, String word, int index) {
if (index == [Link]()) {
return true;
}
if (x < 0 || x >= [Link] || y < 0 || y >= board[0].length || board[x][y]
!= [Link](index)) {
return false;
}
char temp = board[x][y];
board[x][y] = '#'; // Mark as visited
boolean found = dfs(board, x - 1, y, word, index + 1) ||
dfs(board, x + 1, y, word, index + 1) ||
dfs(board, x, y - 1, word, index + 1) ||
dfs(board, x, y + 1, word, index + 1);
board[x][y] = temp; // Restore the cell
return found;
}
}
1. Write a Java program to find the kth largest element in an unsorted array.
import [Link].*;
public class KthLargestElement {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int num : nums) {
[Link](num);
if ([Link]() > k) {
Java Coding Questions 51
[Link]();
}
}
return [Link]();
}
}
1. Given an array of integers, find the maximum subarray sum (Kadane's
algorithm).
public class MaximumSubarraySum {
public int maxSubArray(int[] nums) {
int maxSum = Integer.MIN_VALUE;
int currentSum = 0;
for (int num : nums) {
currentSum = [Link](num, currentSum + num);
maxSum = [Link](maxSum, currentSum);
}
return maxSum;
}
}
1. Implement a function to find the minimum window substring in a given string.
import [Link].*;
public class MinimumWindowSubstring {
public String minWindow(String s, String t) {
if ([Link]() == 0 || [Link]() == 0) {
return "";
}
Map<Character, Integer> targetCount = new HashMap<>();
for (char c : [Link]()) {
[Link](c, [Link](c, 0) + 1);
}
int left = 0;
int minLen = Integer.MAX_VALUE;
int minStart = 0;
int count = [Link]();
for (int right = 0; right < [Link](); right++) {
char rightChar = [Link](right);
if ([Link](rightChar)) {
[Link](rightChar, [Link](rightChar) - 1);
if ([Link](rightChar) >= 0) {
count--;
}
Java Coding Questions 52
}
while (count == 0) {
if (right - left + 1 < minLen) {
minLen = right - left + 1;
minStart = left;
}
char leftChar = [Link](left);
if ([Link](leftChar)) {
[Link](leftChar, [Link](leftChar) + 1);
if ([Link](leftChar) > 0) {
count++;
}
}
left++;
}
}
return minLen == Integer.MAX_VALUE ? "" : [Link](minStart, minStart + min
Len);
}
}
1. Write a Java program to implement a regular expression matcher.
public class RegularExpressionMatcher {
public boolean isMatch(String s, String p) {
if ([Link]()) {
return [Link]();
}
boolean firstMatch = ![Link]() && ([Link](0) == [Link](0) || [Link]
(0) == '.');
if ([Link]() >= 2 && [Link](1) == '*') {
return (isMatch(s, [Link](2)) || (firstMatch && isMatch([Link]
(1), p)));
} else {
return firstMatch && isMatch([Link](1), [Link](1));
}
}
}
1. Implement a function to find the median of two sorted arrays in Java.
public class MedianOfTwoSortedArrays {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = [Link];
int n = [Link];
if (m > n) {
Java Coding Questions 53
return findMedianSortedArrays(nums2, nums1);
}
int imin = 0;
int imax = m;
int halfLen = (m + n + 1) / 2;
while (imin <= imax) {
int i = (imin + imax) / 2;
int j = halfLen - i;
if (i < m && nums2[j - 1] > nums1[i]) {
imin = i + 1;
} else if (i > 0 && nums1[i - 1] > nums2[j]) {
imax = i - 1;
} else {
int maxOfLeft;
if (i == 0) {
maxOfLeft = nums2[j - 1];
} else if (j == 0) {
maxOfLeft = nums1[i - 1];
} else {
maxOfLeft = [Link](nums1[i - 1], nums2[j - 1]);
}
if ((m + n) % 2 == 1) {
return maxOfLeft;
}
int minOfRight;
if (i == m) {
minOfRight = nums2[j];
} else if (j == n) {
minOfRight = nums1[i];
} else {
minOfRight = [Link](nums1[i], nums2[j]);
}
return (maxOfLeft + minOfRight) / 2.0;
}
}
return 0.0;
}
}
1. Given a 2D grid of 0s and 1s, find the largest rectangle containing only 1s.
public class MaximalRectangle {
public int maximalRectangle(char[][] matrix) {
if (matrix == null || [Link] == 0 || matrix[0].length == 0) {
return 0;
}
Java Coding Questions 54
int m = [Link];
int n = matrix[0].length;
int[] heights = new int[n];
int maxArea = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
heights[j]++;
} else {
heights[j] = 0;
}
}
maxArea = [Link](maxArea, largestRectangleArea(heights));
}
return maxArea;
}
private int largestRectangleArea(int[] heights) {
int n = [Link];
int maxArea = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i <= n; i++) {
int h = (i == n) ? 0 : heights[i];
while (![Link]() && h < heights[[Link]()]) {
int height = heights[[Link]()];
int width = [Link]() ? i : i - [Link]() - 1;
maxArea = [Link](maxArea, height * width);
}
[Link](i);
}
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) {
[Link] = val;
}
}
class BSTInfo {
int min;
int max;
int size;
Java Coding Questions 55
boolean isBST;
BSTInfo(int min, int max, int size, boolean isBST) {
[Link] = min;
[Link] = max;
[Link] = size;
[Link] = isBST;
}
}
public class LargestBSTSubtree {
public int largestBSTSubtree(TreeNode root) {
return largestBSTSubtreeHelper(root).size;
}
private BSTInfo largestBSTSubtreeHelper(TreeNode node) {
if (node == null) {
return new BSTInfo(Integer.MAX_VALUE, Integer.MIN_VALUE, 0, true);
}
BSTInfo leftInfo = largestBSTSubtreeHelper([Link]);
BSTInfo rightInfo = largestBSTSubtreeHelper([Link]);
if ([Link] && [Link] && [Link] > [Link] && [Link] <
[Link]) {
int size = [Link] + [Link] + 1;
int min = [Link]([Link], [Link]);
int max = [Link]([Link], [Link]);
return new BSTInfo(min, max, size, true);
} else {
return new BSTInfo(0, 0, [Link]([Link], [Link]), false);
}
}
}
1. Implement a function to serialize and deserialize a binary tree in Java.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
[Link] = val;
}
}
public class SerializeDeserializeBinaryTree {
private static final String NULL_NODE = "null";
private static final String DELIMITER = ",";
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serializeHelper(root, sb);
Java Coding Questions 56
return [Link]();
}
private void serializeHelper(TreeNode node, StringBuilder sb) {
if (node == null) {
[Link](NULL_NODE).append(DELIMITER);
return;
}
[Link]([Link]).append(DELIMITER);
serializeHelper([Link], sb);
serializeHelper([Link], sb);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
Queue<String> nodes = new LinkedList<>([Link]([Link](DELIMITER)));
return deserializeHelper(nodes);
}
private TreeNode deserializeHelper(Queue<String> nodes) {
String val = [Link]();
if ([Link](NULL_NODE)) {
return null;
}
TreeNode node = new TreeNode([Link](val));
[Link] = deserializeHelper(nodes);
[Link] = deserializeHelper(nodes);
return node;
}
}
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) {
[Link] = val;
}
}
public class BinarySearchTree {
private TreeNode root;
public void insert(int val) {
root = insertHelper(root, val);
}
private TreeNode insertHelper(TreeNode node, int val) {
Java Coding Questions 57
if (node == null) {
return new TreeNode(val);
}
if (val < [Link]) {
[Link] = insertHelper([Link], val);
} else if (val > [Link]) {
[Link] = insertHelper([Link], val);
}
return node;
}
public boolean search(int val) {
return searchHelper(root, val);
}
private boolean searchHelper(TreeNode node, int val) {
if (node == null) {
return false;
}
if (val == [Link]) {
return true;
} else if (val < [Link]) {
return searchHelper([Link], val);
} else {
return searchHelper([Link], val);
}
}
public void delete(int val) {
root = deleteHelper(root, val);
}
private TreeNode deleteHelper(TreeNode node, int val) {
if (node == null) {
return null;
}
if (val < [Link]) {
[Link] = deleteHelper([Link], val);
} else if (val > [Link]) {
[Link] = deleteHelper([Link], val);
} else {
if ([Link] == null) {
return [Link];
} else if ([Link] == null) {
return [Link];
}
[Link] = findMinValue([Link]);
[Link] = deleteHelper([Link], [Link]);
}
return node;
}
Java Coding Questions 58
private int findMinValue(TreeNode node) {
while ([Link] != null) {
node = [Link];
}
return [Link];
}
}
1. Implement a function to find the longest palindromic substring in a given string
(Manacher's algorithm).
public class LongestPalindromicSubstring {
public String longestPalindrome(String s) {
if (s == null || [Link]() == 0) {
return "";
}
char[] t = preProcess(s);
int n = [Link];
int[] p = new int[n];
int center = 0;
int right = 0;
for (int i = 1; i < n - 1; i++) {
int mirror = 2 * center - i;
if (right > i) {
p[i] = [Link](right - i, p[mirror]);
}
while (t[i + p[i] + 1] == t[i - p[i] - 1]) {
p[i]++;
}
if (i + p[i] > right) {
center = i;
right = i + p[i];
}
}
int maxLen = 0;
int centerIndex = 0;
for (int i = 1; i < n - 1; i++) {
if (p[i] > maxLen) {
maxLen = p[i];
centerIndex = i;
}
}
int start = (centerIndex - maxLen) / 2;
return [Link](start, start + maxLen);
Java Coding Questions 59
}
private char[] preProcess(String s) {
int n = [Link]();
char[] t = new char[2 * n + 3];
t[0] = '^';
for (int i = 0; i < n; i++) {
t[2 * i + 1] = '#';
t[2 * i + 2] = [Link](i);
}
t[2 * n + 1] = '#';
t[2 * n + 2] = '$';
return t;
}
}
1. Given a matrix of m x n elements (m rows, n columns), write a Java function to
find the longest increasing path.
public class LongestIncreasingPathInMatrix {
private static final int[] dx = { -1, 1, 0, 0 };
private static final int[] dy = { 0, 0, -1, 1 };
public int longestIncreasingPath(int[][] matrix) {
if (matrix == null || [Link] == 0 || matrix[0].length == 0) {
return 0;
}
int m = [Link];
int n = matrix[0].length;
int[][] cache = new int[m][n];
int maxPathLength = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
maxPathLength = [Link](maxPathLength, dfs(matrix, i, j, cache));
}
}
return maxPathLength;
}
private int dfs(int[][] matrix, int x, int y, int[][] cache) {
if (cache[x][y] != 0) {
return cache[x][y];
}
int m = [Link];
int n = matrix[0].length;
int maxPath = 1;
for (int i = 0; i < 4; i++) {
int newX = x + dx[i];
int newY = y + dy[i];
Java Coding Questions 60
if (newX >= 0 && newX < m && newY >= 0 && newY < n && matrix[newX][newY] >
matrix[x][y]) {
maxPath = [Link](maxPath, 1 + dfs(matrix, newX, newY, cache));
}
}
cache[x][y] = maxPath;
return maxPath;
}
}
1. Implement an LRU (Least Recently Used) cache using a doubly-linked list and a
hashmap.
import [Link].*;
class Node {
int key;
int value;
Node prev;
Node next;
Node(int key, int value) {
[Link] = key;
[Link] = value;
}
}
public class LRUCache {
private final int capacity;
private final Map<Integer, Node> cache;
private Node head;
private Node tail;
public LRUCache(int capacity) {
[Link] = capacity;
[Link] = new HashMap<>();
[Link] = new Node(0, 0);
[Link] = new Node(0, 0);
[Link] = tail;
[Link] = head;
}
private void addToFront(Node node) {
[Link] = head;
[Link] = [Link];
[Link] = node;
[Link] = node;
}
private void removeNode(Node node) {
[Link] = [Link];
[Link] = [Link];
Java Coding Questions 61
}
private void moveToHead(Node node) {
removeNode(node);
addToFront(node);
}
public int get(int key) {
if ([Link](key)) {
Node node = [Link](key);
moveToHead(node);
return [Link];
}
return -1;
}
public void put(int key, int value) {
if ([Link](key)) {
Node node = [Link](key);
[Link] = value;
moveToHead(node);
} else {
if ([Link]() >= capacity) {
Node evictNode = [Link];
removeNode(evictNode);
[Link]([Link]);
}
Node newNode = new Node(key, value);
addToFront(newNode);
[Link](key, newNode);
}
}
}
1. Given a list of non-negative integers, write a Java function to find the maximum
amount of water that can be trapped.
public class TrappingRainWater {
public int trap(int[] height) {
int n = [Link];
int[] leftMax = new int[n];
int[] rightMax = new int[n];
int totalWater = 0;
int maxLeft = 0;
for (int i = 0; i < n; i++) {
leftMax[i] = maxLeft;
maxLeft = [Link](maxLeft, height[i]);
}
int maxRight = 0;
for (int i = n - 1; i >= 0; i--) {
rightMax[i] = maxRight;
maxRight = [Link](maxRight, height[i]);
Java Coding Questions 62
int minHeight = [Link](leftMax[i], rightMax[i]);
if (minHeight > height[i]) {
totalWater += minHeight - 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 class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for (char c : [Link]()) {
int index = c - 'a';
if ([Link][index] == null) {
[Link][index] = new TrieNode();
}
node = [Link][index];
}
[Link] = true;
}
public boolean search(String word) {
TrieNode node = findNode(word);
return node != null && [Link];
}
public boolean startsWith(String prefix) {
TrieNode node = findNode(prefix);
return node != null;
}
Java Coding Questions 63
private TrieNode findNode(String word) {
TrieNode node = root;
for (char c : [Link]()) {
int index = c - 'a';
if ([Link][index] == null) {
return null;
}
node = [Link][index];
}
return node;
}
}
1. Implement a function to find the longest common prefix in an array of strings.
public class LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if (strs == null || [Link] == 0) {
return "";
}
String prefix = strs[0];
for (int i = 1; i < [Link]; i++) {
while (!strs[i].startsWith(prefix)) {
prefix = [Link](0, [Link]() - 1);
}
}
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) {
[Link] = val;
}
}
class SubtreeInfo {
int sum;
int count;
SubtreeInfo(int sum, int count) {
[Link] = sum;
Java Coding Questions 64
[Link] = count;
}
}
public class MaximumAverageSubtree {
private double maxAverage;
public double maximumAverageSubtree(TreeNode root) {
maxAverage = 0;
findMaxAverage(root);
return maxAverage;
}
private SubtreeInfo findMaxAverage(TreeNode node) {
if (node == null) {
return new SubtreeInfo(0, 0);
}
SubtreeInfo leftInfo = findMaxAverage([Link]);
SubtreeInfo rightInfo = findMaxAverage([Link]);
int sum = [Link] + [Link] + [Link];
int count = [Link] + [Link] + 1;
double average = (double) sum / count;
maxAverage = [Link](maxAverage, average);
return new SubtreeInfo(sum, 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) {
[Link] = val;
}
}
public class MaximumDistanceBetweenNodes {
private int maxDistance;
public int maxDistance(TreeNode root) {
maxDistance = 0;
findMaxDistance(root);
return maxDistance;
}
private int[] findMaxDistance(TreeNode node) {
Java Coding Questions 65
if (node == null) {
return new int[] { -1, -1 };
}
int[] left = findMaxDistance([Link]);
int[] right = findMaxDistance([Link]);
int heightLeft = left[0] + 1;
int heightRight = right[0] + 1;
int distanceLeft = left[1];
int distanceRight = right[1];
maxDistance = [Link](maxDistance, distanceLeft);
maxDistance = [Link](maxDistance, distanceRight);
maxDistance = [Link](maxDistance, heightLeft + heightRight);
return new int[] { [Link](heightLeft, heightRight), [Link](heightLeft + he
ightRight, [Link](distanceLeft, distanceRight)) };
}
}
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.
public class UniquePathsInGrid {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++) {
dp[i][0] = 1;
}
for (int i = 0; i < n; i++) {
dp[0][i] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
}
1. Write a Java program to find the longest palindromic substring with a dynamic
programming approach.
public class LongestPalindromicSubstringDP {
public String longestPalindrome(String s) {
Java Coding Questions 66
int n = [Link]();
boolean[][] dp = new boolean[n][n];
String longestPalindrome = "";
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
dp[i][j] = ([Link](i) == [Link](j) && (j - i < 3 || dp[i + 1][j -
1]));
if (dp[i][j] && ([Link]() || j - i + 1 > longestPal
[Link]())) {
longestPalindrome = [Link](i, j + 1);
}
}
}
return longestPalindrome;
}
}
1. Given a string s, write a Java program to find the length of the longest substring
without repeating characters.
import [Link].*;
public class LongestSubstringWithoutRepeatingCharacters {
public int lengthOfLongestSubstring(String s) {
int n = [Link]();
Map<Character, Integer> charIndexMap = new HashMap<>();
int maxLength = 0;
int left = 0;
for (int right = 0; right < n; right++) {
char rightChar = [Link](right);
if ([Link](rightChar)) {
left = [Link](left, [Link](rightChar) + 1);
}
[Link](rightChar, right);
maxLength = [Link](maxLength, right - left + 1);
}
return maxLength;
}
}
1. Given a string containing only digits, write a Java program to restore it by
returning all possible valid IP address combinations.
import [Link].*;
public class RestoreIPAddresses {
Java Coding Questions 67
public List<String> restoreIpAddresses(String s) {
List<String> result = new ArrayList<>();
int n = [Link]();
for (int i = 1; i <= 3 && i <= n - 3; i++) {
for (int j = i + 1; j <= i + 3 && j <= n - 2; j++) {
for (int k = j + 1; k <= j +
3 && k <= n - 1; k++) {
String part1 = [Link](0, i);
String part2 = [Link](i, j);
String part3 = [Link](j, k);
String part4 = [Link](k);
if (isValid(part1) && isValid(part2) && isValid(part3) && isValid
(part4)) {
[Link](part1 + "." + part2 + "." + part3 + "." + part4);
}
}
}
}
return result;
}
private boolean isValid(String part) {
if ([Link]() > 1 && [Link]("0")) {
return false;
}
int num = [Link](part);
return num >= 0 && num <= 255;
}
}
1. Write a Java program to find the longest increasing subsequence with a binary
search approach.
import [Link].*;
public class LongestIncreasingSubsequenceBinarySearch {
public int lengthOfLIS(int[] nums) {
List<Integer> lis = new ArrayList<>();
for (int num : nums) {
int index = [Link](lis, num);
if (index < 0) {
index = -(index + 1);
}
if (index == [Link]()) {
[Link](num);
} else {
[Link](index, num);
Java Coding Questions 68
}
}
return [Link]();
}
}
1. Given a list of words, write a Java program to find all word squares.
import [Link].*;
public class WordSquares {
public List<List<String>> wordSquares(String[] words) {
List<List<String>> result = new ArrayList<>();
Map<String, List<String>> prefixMap = new HashMap<>();
for (String word : words) {
for (int i = 1; i <= [Link](); i++) {
String prefix = [Link](0, i);
[Link](prefix, new ArrayList<>());
[Link](prefix).add(word);
}
}
for (String word : words) {
List<String> wordSquare = new ArrayList<>();
[Link](word);
findWordSquares(prefixMap, wordSquare, result);
}
return result;
}
private void findWordSquares(Map<String, List<String>> prefixMap, List<String> wor
dSquare, List<List<String>> result) {
int size = [Link](0).length();
int index = [Link]();
if (index == size) {
[Link](new ArrayList<>(wordSquare));
return;
}
StringBuilder prefixBuilder = new StringBuilder();
for (String word : wordSquare) {
[Link]([Link](index));
}
String prefix = [Link]();
if () {
return;
}
Java Coding Questions 69
for (String nextWord : [Link](prefix)) {
[Link](nextWord);
findWordSquares(prefixMap, wordSquare, result);
[Link]([Link]() - 1);
}
}
}
1. Given an array of integers, find the kth smallest element in it.
import [Link].*;
public class KthSmallestElement {
public int kthSmallest(int[] nums, int k) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>([Link]
());
for (int num : nums) {
[Link](num);
if ([Link]() > k) {
[Link]();
}
}
return [Link]();
}
}
1. Implement a function to calculate the n-th Fibonacci number efficiently using
memoization.
import [Link].*;
public class FibonacciMemoization {
public int fib(int n) {
Map<Integer, Integer> memo = new HashMap<>();
return fibHelper(n, memo);
}
private int fibHelper(int n, Map<Integer, Integer> memo) {
if ([Link](n)) {
return [Link](n);
}
if (n <= 1) {
return n;
}
int fibN = fibHelper(n - 1, memo) + fibHelper(n - 2, memo);
[Link](n, fibN);
return fibN;
Java Coding Questions 70
}
}
1. Given a list of meeting intervals, merge overlapping intervals.
import [Link].*;
class Interval {
int start;
int end;
Interval(int start, int end) {
[Link] = start;
[Link] = end;
}
}
public class MergeIntervals {
public List<Interval> merge(List<Interval> intervals) {
if (intervals == null || [Link]() <= 1) {
return intervals;
}
[Link](intervals, (a, b) -> [Link] - [Link]);
List<Interval> mergedIntervals = new ArrayList<>();
Interval currentInterval = [Link](0);
for (int i = 1; i < [Link](); i++) {
Interval nextInterval = [Link](i);
if ([Link] >= [Link]) {
[Link] = [Link]([Link], [Link]);
} else {
[Link](currentInterval);
currentInterval = nextInterval;
}
}
[Link](currentInterval);
return mergedIntervals;
}
}
1. Write a Java program to perform matrix multiplication efficiently.
public class MatrixMultiplication {
public int[][] multiply(int[][] A, int[][] B) {
int m = [Link];
int n = A[0].length;
int p = B[0].length;
int[][] result = new int[m][p];
Java Coding Questions 71
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < n; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
return result;
}
}
1. Implement a function to find the longest common subsequence of two strings.
public class LongestCommonSubsequence {
public int longestCommonSubsequence(String text1, String text2) {
int m = [Link]();
int n = [Link]();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if ([Link](i - 1) == [Link](j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = [Link](dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
}
1. Write a Java program to implement a binary indexed tree (Fenwick tree).
public class FenwickTree {
private int[] BIT;
public FenwickTree(int n) {
BIT = new int[n + 1];
}
public void update(int index, int value) {
while (index < [Link]) {
BIT[index] += value;
index += index & -index;
}
}
public int query(int index) {
Java Coding Questions 72
int sum = 0;
while (index > 0) {
sum += BIT[index];
index -= index & -index;
}
return sum;
}
public int rangeSum(int left, int right) {
return query(right) - query(left - 1);
}
}
1. Given a sorted array of integers, write a Java program to find
the closest elements to a target value.
import [Link].*;
public class ClosestElements {
public List<Integer> findClosestElements(int[] arr, int k, int target) {
int left = 0;
int right = [Link] - k;
while (left < right) {
int mid = left + (right - left) / 2;
if (target - arr[mid] > arr[mid + k] - target) {
left = mid + 1;
} else {
right = mid;
}
}
List<Integer> closestElements = new ArrayList<>();
for (int i = left; i < left + k; i++) {
[Link](arr[i]);
}
return closestElements;
}
}
1. Implement a function to find the minimum number of coins needed to make a
given amount using dynamic programming.
import [Link].*;
public class CoinChange {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
[Link](dp, amount + 1);
dp[0] = 0;
Java Coding Questions 73
for (int coin : coins) {
for (int i = coin; i <= amount; i++) {
dp[i] = [Link](dp[i], dp[i - coin] + 1);
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
}
1. Given a list of unique numbers, write a Java program to find all permutations of
the numbers.
import [Link].*;
public class Permutations {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
boolean[] used = new boolean[[Link]];
List<Integer> current = new ArrayList<>();
permuteHelper(nums, used, current, result);
return result;
}
private void permuteHelper(int[] nums, boolean[] used, List<Integer> current, List
<List<Integer>> result) {
if ([Link]() == [Link]) {
[Link](new ArrayList<>(current));
return;
}
for (int i = 0; i < [Link]; i++) {
if (!used[i]) {
used[i] = true;
[Link](nums[i]);
permuteHelper(nums, used, current, result);
[Link]([Link]() - 1);
used[i] = false;
}
}
}
}
1. Write a Java program to implement a stack with the ability to get the minimum
element in constant time.
import [Link].*;
public class MinStack {
private Stack<Integer> stack;
Java Coding Questions 74
private Stack<Integer> minStack;
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int val) {
[Link](val);
if ([Link]() || val <= [Link]()) {
[Link](val);
}
}
public void pop() {
if (![Link]()) {
int val = [Link]();
if (val == [Link]()) {
[Link]();
}
}
}
public int top() {
return [Link]() ? -1 : [Link]();
}
public int getMin() {
return [Link]() ? -1 : [Link]();
}
}
1. Implement a function to find the maximum sum subarray of a given array using
Kadane's algorithm.
public class MaximumSubarray {
public int maxSubArray(int[] nums) {
int maxSum = nums[0];
int currentSum = nums[0];
for (int i = 1; i < [Link]; i++) {
currentSum = [Link](nums[i], currentSum + nums[i]);
maxSum = [Link](maxSum, currentSum);
}
return maxSum;
}
}
1. Given an n x n matrix representing an image, write a Java program to rotate the
image by 90 degrees (clockwise).
Java Coding Questions 75
public class RotateImage {
public void rotate(int[][] matrix) {
int n = [Link];
// Transpose the matrix
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
// Reverse each row
for (int i = 0; i < n; i++) {
for (int j = 0; j < n / 2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n - 1 - j];
matrix[i][n - 1 - j] = temp;
}
}
}
}
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 class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for (char c : [Link]()) {
int index = c - 'a';
if ([Link][index] == null) {
[Link][index] = new TrieNode();
}
node = [Link][index];
}
Java Coding Questions 76
[Link] = true;
}
public boolean search(String word) {
TrieNode node = findNode(word);
return node != null && [Link];
}
public boolean startsWith(String prefix) {
TrieNode node = findNode(prefix);
return node != null;
}
private TrieNode findNode(String word) {
TrieNode node = root;
for (char c : [Link]()) {
int index = c - 'a';
if ([Link][index] == null) {
return null;
}
node = [Link][index];
}
return node;
}
public void delete(String word) {
deleteHelper(root, word, 0);
}
private boolean deleteHelper(TrieNode node, String word, int depth) {
if (node == null) {
return false;
}
if (depth == [Link]()) {
if (![Link]) {
return false;
}
[Link] = false;
return allChildrenNull(node);
}
int index = [Link](depth) - 'a';
if (deleteHelper([Link][index], word, depth + 1)) {
[Link][index] = null;
return ![Link] && allChildrenNull(node);
}
return false;
}
private boolean allChildrenNull(TrieNode node) {
for (TrieNode child : [Link]) {
if (child != null) {
return false;
}
}
return true;
Java Coding Questions 77
}
}
1. Given a list of non-overlapping intervals, insert a new interval and merge if
necessary.
import [Link].*;
public class InsertInterval {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> mergedIntervals = new ArrayList<>();
int i = 0;
while (i < [Link] && intervals[i][1] < newInterval[0]) {
[Link](intervals[i]);
i++;
}
while (i < [Link] && intervals[i][0] <= newInterval[1]) {
newInterval[0] = [Link](newInterval[0], intervals[i][0]);
newInterval[1] = [Link](newInterval[1], intervals[i][1]);
i++;
}
[Link](newInterval);
while (i < [Link]) {
[Link](intervals[i]);
i++;
}
return [Link](new int[[Link]()][]);
}
}
1. Write a Java program to find the maximum profit by buying and selling stocks
(multiple transactions allowed).
public class BestTimeToBuyAndSellStockII {
public int maxProfit(int[] prices) {
int maxProfit = 0;
for (int i = 1; i < [Link]; i++) {
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1];
}
}
return maxProfit;
Java Coding Questions 78
}
}
1. Implement a function to serialize and deserialize a binary tree.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
[Link] = val;
}
}
public class SerializeDeserializeBinaryTree {
// Serialize a binary tree to a string
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serializeHelper(root, sb);
return [Link]();
}
private void serializeHelper(TreeNode node, StringBuilder sb) {
if (node == null) {
[Link]("null").append(",");
return;
}
[Link]([Link]).append(",");
serializeHelper([Link], sb);
serializeHelper([Link], sb);
}
// Deserialize a string to a binary tree
public TreeNode deserialize(String data) {
String[] nodes = [Link](",");
Queue<String> queue = new LinkedList<>([Link](nodes));
return deserializeHelper(queue);
}
private TreeNode deserializeHelper(Queue<String> queue) {
String val = [Link]();
if ([Link]("null")) {
return null;
}
TreeNode node = new TreeNode([Link](val));
[Link] = deserializeHelper(queue);
[Link] = deserializeHelper(queue);
return node;
}
}
Java Coding Questions 79
1. Given an array of integers, write a Java program to find the largest sum of a
contiguous subarray.
public class MaximumSubarraySum {
public int maxSubArray(int[] nums) {
int maxSum = nums[0];
int currentSum = nums[0];
for (int i = 1; i < [Link]; i++) {
currentSum = [Link](nums[i], currentSum + nums[i]);
maxSum = [Link](maxSum, currentSum);
}
return maxSum;
}
}
1. Write a Java program to implement a priority queue using a min-heap.
import [Link].*;
public class MinHeapPriorityQueue {
private int[] heap;
private int size;
private static final int DEFAULT_CAPACITY = 10;
public MinHeapPriorityQueue() {
heap = new int[DEFAULT_CAPACITY];
size = 0;
}
public void offer(int val) {
if (size == [Link] - 1) {
resize();
}
size++;
int index = size;
heap[index] = val;
while (index > 1 && heap[index] < heap[index / 2]) {
swap(index, index / 2);
index = index / 2;
}
}
public int poll() {
if (size == 0) {
throw new NoSuchElementException("Priority queue is empty.");
}
int min = heap[1];
heap[1] = heap[size];
Java Coding Questions 80
size--;
int index = 1;
while (true) {
int smallest = index;
int leftChild = index * 2;
int rightChild = index * 2 + 1;
if (leftChild <= size && heap[leftChild] < heap[smallest]) {
smallest = leftChild;
}
if (rightChild <= size && heap[rightChild] < heap[smallest]) {
smallest = rightChild;
}
if (smallest == index) {
break;
}
swap(index, smallest);
index = smallest;
}
return min;
}
public int peek() {
if (size == 0) {
throw new NoSuchElementException("Priority queue is empty.");
}
return heap[1];
}
public boolean isEmpty() {
return size == 0;
}
private void resize() {
int[] newHeap = new int[[Link] * 2];
[Link](heap, 0, newHeap, 0, [Link]);
heap = newHeap;
}
private void swap(int i, int j) {
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
}
1. Implement a function to find the longest common prefix among an array of
strings.
Java Coding Questions 81
public class LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if (strs == null || [Link] == 0) {
return "";
}
String prefix = strs[0];
for (int i = 1; i < [Link]; i++) {
while (!strs[i].startsWith(prefix)) {
prefix = [Link](0, [Link]() - 1);
}
}
return prefix;
}
}
1. Given a list of intervals, find the minimum number of intervals to be removed to
make the rest of the intervals non-overlapping.
import [Link].*;
class Interval {
int start;
int end;
Interval(int start, int end) {
[Link] = start;
[Link] = end;
}
}
public class NonOverlappingIntervals {
public int eraseOverlapIntervals(Interval[] intervals) {
if (intervals == null || [Link] <= 1) {
return 0;
}
[Link](intervals, (a, b) -> [Link] - [Link]);
int count = 0;
int end = intervals[0].end;
for (int i = 1; i < [Link]; i++) {
if (intervals[i].start < end) {
count++;
} else {
end = intervals[i].end;
}
}
return count;
Java Coding Questions 82
}
}
1. Write a Java program to find the longest palindromic substring in a given string.
public class LongestPal
indromicSubstring {
public String longestPalindrome(String s) {
int n = [Link]();
boolean[][] dp = new boolean[n][n];
String longestPalindrome = "";
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
dp[i][j] = ([Link](i) == [Link](j) && (j - i < 3 || dp[i + 1][j -
1]));
if (dp[i][j] && ([Link]() || j - i + 1 > longestPal
[Link]())) {
longestPalindrome = [Link](i, j + 1);
}
}
}
return longestPalindrome;
}
}
1. Given a list of words, write a Java program to find all valid word squares.
import [Link].*;
public class WordSquares {
public List<List<String>> wordSquares(String[] words) {
List<List<String>> result = new ArrayList<>();
Map<String, List<String>> prefixMap = new HashMap<>();
for (String word : words) {
for (int i = 1; i <= [Link](); i++) {
String prefix = [Link](0, i);
[Link](prefix, new ArrayList<>());
[Link](prefix).add(word);
}
}
for (String word : words) {
List<String> wordSquare = new ArrayList<>();
[Link](word);
findWordSquares(prefixMap, wordSquare, result);
}
Java Coding Questions 83
return result;
}
private void findWordSquares(Map<String, List<String>> prefixMap, List<String> wor
dSquare, List<List<String>> result) {
int size = [Link](0).length();
int index = [Link]();
if (index == size) {
[Link](new ArrayList<>(wordSquare));
return;
}
StringBuilder prefixBuilder = new StringBuilder();
for (String word : wordSquare) {
[Link]([Link](index));
}
String prefix = [Link]();
if () {
return;
}
for (String nextWord : [Link](prefix)) {
[Link](nextWord);
findWordSquares(prefixMap, wordSquare, result);
[Link]([Link]() - 1);
}
}
}
1. Implement a function to find the kth largest element in an unsorted array.
import [Link].*;
public class KthLargestElement {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int num : nums) {
[Link](num);
if ([Link]() > k) {
[Link]();
}
}
return [Link]();
}
}
1. Write a Java program to find the longest increasing subsequence in an array.
Java Coding Questions 84
public class LongestIncreasingSubsequence {
public int lengthOfLIS(int[] nums) {
int[] dp = new int[[Link]];
int maxLength = 0;
for (int i = 0; i < [Link]; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = [Link](dp[i], dp[j] + 1);
}
}
maxLength = [Link](maxLength, dp[i]);
}
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 [Link].*;
public class LongestWordMadeOfOtherWords {
public String longestWord(String[] words) {
Set<String> wordSet = new HashSet<>([Link](words));
[Link](words, (a, b) -> [Link]() != [Link]() ? [Link]() - [Link]
() : [Link](b));
for (String word : words) {
[Link](word);
if (isMadeOfOtherWords(word, wordSet)) {
return word;
}
[Link](word);
}
return "";
}
private boolean isMadeOfOtherWords(String word, Set<String> wordSet) {
if ([Link]()) {
return true;
}
for (int i = 1; i <= [Link](); i++) {
if ([Link]([Link](0, i)) && isMadeOfOtherWords([Link]
tring(i), wordSet)) {
return true;
}
}
Java Coding Questions 85
return false;
}
}
Java Coding Questions 86