Scrivio Interview library

Coding problems in Java

41 questions in 10 subtopics.

Number problems

CodingFoundations6 min read
Write a Java method boolean isPalindrome(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.
CodingFoundations7 min read
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.
DebuggingIntermediate7 min read
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();
ScenarioAdvanced9 min read
An audit finds that 15 services calculate prices, taxes and currency conversions with double, and some invoices are off by a cent. As the senior engineer asked to fix it across teams, what standard do you set for monetary arithmetic in Java, and how do you roll it out?

String problems

CodingFoundations7 min read
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.
CodingFoundations8 min read
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.
InternalsIntermediate7 min read
A method reverses user-entered display names with new 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.
CodingIntermediate6 min read
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

CodingFoundations7 min read
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.
CodingFoundations7 min read
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.
CodingIntermediate6 min read
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].
CodingIntermediate6 min read
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.
LeadershipPrincipal7 min read
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

CodingFoundations7 min read
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.
CodingFoundations6 min read
Write a Java method that reverses a singly linked list, given
class Node {
int val;
Node next;
}
iteratively and recursively. Which version would you use in production for a list of 1 million nodes, and why?
CodingIntermediate7 min read
Merge k sorted linked lists into one sorted list in Java, where k can be 10,000 and the total number of nodes N is 10 million. Give two approaches with their complexity and choose one.
DesignPrincipal7 min read
Linked list exercises remain common in interviews, yet in production Java code 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

CodingFoundations7 min read
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.
CodingIntermediate6 min read
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.
DebuggingIntermediate8 min read
A method counts islands of '1' cells in a char[][] grid with recursive DFS. It passes all tests but fails in production with StackOverflowError on a 4,000 x 4,000 grid that is mostly land. Explain why and rewrite the approach.
ScenarioAdvanced8 min read
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

CodingFoundations7 min read
Given List<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.
CodingFoundations6 min read
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.
CodingIntermediate8 min read
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.
DebuggingIntermediate7 min read
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);
Explain why, fix it, and list two other stream side-effect bugs you look for in reviews.

Multithreading coding problems

CodingFoundations7 min read
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.
CodingIntermediate7 min read
Implement a bounded blocking queue in Java with put(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.
CodingIntermediate7 min read
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.
DesignAdvanced8 min read
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

CodingFoundations7 min read
Implement an LRU cache in Java with get(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.
CodingIntermediate7 min read
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.
ScenarioAdvanced7 min read
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

DesignFoundations7 min read
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.
DesignIntermediate9 min read
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.
DesignAdvanced8 min read
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?
LeadershipPrincipal7 min read
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

ConceptFoundations6 min read
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;
}
}
ConceptFoundations6 min read
What does this print, and why?
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;
ConceptIntermediate6 min read
What does this print, and why?
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();
ConceptIntermediate6 min read
Which method is called in each case, and why?
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);
LeadershipPrincipal7 min read
Many Java interviews ask output-prediction puzzles about integer caching, initialization order and overload resolution. In your organization the same traps also show up as production bugs. As a technical leader, how do you balance puzzle knowledge in hiring with preventing these bugs systematically?