Coding problems in Java
41 questions in 10 subtopics.
Number problems
Write a Java method booleanisPalindrome(int x) that checks whether an integer reads the same backwards (121 yes, -121 no, 10 no) without converting it to a String. State the time complexity and how you avoid overflow.Write a Java method that returns all prime numbers up to n, where n can be 10,000,000. Explain the algorithm, its complexity, the memory you need, and one overflow bug that is easy to introduce.Review this code and list every numeric bug:int mid = (lo + hi) / 2;
int bucket = key.hashCode() % buckets;
int abs = Math.abs(Integer.MIN_VALUE);
int total = 0;
for (int v : values) total += v; // values has 3 million ints near 1,000
double price = 0.1 + 0.2;
if (price == 0.3) charge();
String problems
Write a Java method that checks whether two strings are anagrams, ignoring case and spaces ("Dormitory" and "dirty room"). Compare a sorting solution with a counting solution.Write a Java method that returns the index of the first non-repeating character in a String (for "swiss" the answer is 1, for 'w'), or -1 if none. Give its complexity and say how your solution behaves with text that contains emoji.A method reverses user-entered display names withnew StringBuilder(name).reverse().toString(). Most names are fine, but names with flags, skin-tone emoji or letters with combining accents come out broken. Explain what reverse() does with surrogate pairs and what it cannot handle, and how you would reverse text correctly.Write a Java method that returns the length of the longest substring without repeating characters ("abcabcbb" gives 3, "pwwkew" gives 3). Explain the sliding window and why it is O(n).Array problems
Given int[] nums and int target, return the indices of two different elements that add up to target. Write an O(n) solution, then a solution for a sorted array with O(1) extra space.Write a Java method that rotates an int array to the right by k steps in place ([1,2,3,4,5,6,7] with k = 3 gives [5,6,7,1,2,3,4]). Use O(1) extra space and handle k larger than the array length.Given int[][] intervals such as [[1,3],[2,6],[8,10],[9,12],[15,18]], write a Java method that merges all overlapping intervals. Explain the complexity and how you treat touching intervals like [1,4] and [4,5].Write a Java method that returns the maximum sum of a contiguous subarray and the start and end index of that subarray. The input can contain only negative numbers and up to 10 million elements with values up to 1 billion.You lead engineering hiring for a large Java organization. Interview loops rely on array and string puzzles from public practice sites, candidates increasingly arrive with memorized or AI-assisted answers, and some strong practitioners fail them. How would you redesign the coding part of the loop over the next two years?Linked list problems
Write a Java method that detects whether a singly linked list has a cycle, and returns the node where the cycle begins. Explain why the method works and its complexity.Write a Java method that reverses a singly linked list, givenclass Node {
int val;
Node next;
}
java.util.LinkedList is almost never the right choice. What does this gap say about how data structure knowledge should be taught and assessed in your organization, and what coding standards would you set?Matrix problems
Write a Java method that rotates an n x n int matrix 90 degrees clockwise in place. Explain the steps and the complexity, and say what changes for a non-square matrix.Write a Java method that returns the elements of an m x n matrix in spiral order (clockwise from the top left). Show how you avoid repeating elements when the matrix has a single row or column left.A method counts islands of '1' cells in a char[][] grid with recursive DFS. It passes all tests but fails in production withStackOverflowError on a 4,000 x 4,000 grid that is mostly land. Explain why and rewrite the approach.A Java pricing service multiplies 2,000 x 2,000 double matrices for each risk calculation using double[][] and a naive i-j-k triple loop. It is too slow and the team proposes rewriting in C++. What would you try first in Java, and how do you decide?Collections and streams exercises
GivenList<Employee> with getEmail(), find the emails that appear more than once. Then a colleague converts the list to a Map with Collectors.toMap(Employee::getEmail, e -> e) and gets IllegalStateException. Explain and fix both.Given List<String> words, use streams to produce a map from word length to the number of words of that length, sorted by length. Then produce a map from first letter to the list of words in alphabetical order.Write Java code that reads a 2 GB text log file and prints the 10 most frequent words, case-insensitive, without loading the file into memory. Discuss complexity and whether a parallel stream helps.This code sometimes returns fewer results than expected and occasionally throws ArrayIndexOutOfBoundsException:List<Result> results = new ArrayList<>();
orders.parallelStream().map(this::price).forEach(results::add);
Multithreading coding problems
Write Java code with two threads where one prints odd numbers and the other prints even numbers so that the output is 1 to 10 in order. Show a solution with a shared lock and explain why the wait must be in a loop.Implement a bounded blocking queue in Java withput(T) that waits when full and take() that waits when empty, using ReentrantLock and Condition. Then explain why you would still use ArrayBlockingQueue in production.You must call an external pricing API for 5,000 product ids. The provider allows at most 20 concurrent requests, each call takes about 200 ms, and the whole job must finish within 2 minutes or report partial results. Write the Java 25 approach and explain the choices.Implement a thread-safe token bucket rate limiter in Java (tryAcquire() returns true if a request may pass, capacity 100, refill 50 tokens per second) for one service, then explain what changes when the limit must hold across 40 instances of the service.Implementing an LRU cache
Implement an LRU cache in Java withget(key) and put(key, value) and a fixed capacity, using LinkedHashMap. Explain the constructor argument that makes it work and whether the result is thread-safe.Implement an LRU cache in Java without LinkedHashMap, with O(1) get and put. Explain your data structures, how sentinel nodes simplify the code, and how you would make it safe for concurrent use.A team wrote its own synchronized LRU cache years ago and now uses it in 30 services. Profiling shows lock contention at high load, and a nightly batch that touches every key empties the cache of useful entries every night. How do you handle this across the organization?Object-oriented design exercises
Design the classes for a parking lot in Java: several levels, spots for motorcycles, cars and trucks, tickets on entry and fees on exit with rates that change. Show the main types and explain where you would use interfaces, enums and records.Design an expense-sharing module in Java (like splitting bills among friends): users, groups, expenses split equally, by exact amounts or by percentages, balances per user, and a "settle up" that minimizes the number of payments. Explain your classes and the algorithm for settling.In a senior design exercise, design a discount rules engine for an online shop: product managers add rules weekly (percent off a category, buy 2 get 1, coupon codes, customer tiers), rules can stack or exclude each other, and every price must be explainable to customer support. What do you design, and what would you expect from a strong candidate?Java has moved from deep class hierarchies and design-pattern-heavy code toward records, sealed interfaces and pattern matching, often called data-oriented programming. As the person who sets coding standards and design interview expectations for a large Java organization, what do you change and what do you keep?Output prediction puzzles
What does each method return?static int f() {
int x = 1;
try {
return x;
} finally {
x = 2;
}
}
static int g() {
try {
return 1;
} finally {
return 2;
}
}
static StringBuilder h() {
StringBuilder sb = new StringBuilder("a");
try {
return sb;
} finally {
sb.append("b");
}
}
static int k() {
try {
throw new RuntimeException();
} finally {
return 3;
}
}
Integer a = 127, b = 127, c = 128, d = 128;
System.out.println(a == b);
System.out.println(c == d);
System.out.println('a' + 'b');
System.out.println("" + 'a' + 'b');
short s = 1;
s += 1; // and what about
s = s + 1;
class Base {
Base() {
show();
}
void show() {
System.out.println("base");
}
}
class Child extends Base {
private String name = "child";
private final int n = 5;
private final Integer boxed = 7;
@Override void show() {
System.out.println(name + " " + n + " " + boxed);
}
}
new Child();
static void m(Object o) {
System.out.println("Object");
}
static void m(String s) {
System.out.println("String");
}
static void p(long x) {
System.out.println("long");
}
static void p(Integer x) {
System.out.println("Integer");
}
static void p(int... x) {
System.out.println("varargs");
}
m(null);
p(5);
Object o = "hi";
m(o);
No question matches these choices.