Scrivio Interview library

Algorithms and data structures in Java

49 questions in 12 subtopics.

Sorting algorithms

ConceptFoundations7 min read
Which algorithms does the JDK use for Arrays.sort(int[]), Arrays.sort(Object[]) and Collections.sort(List), and why are primitives and objects sorted differently?
CodingFoundations7 min read
Write a Comparator<Employee> that sorts by department ascending, then salary descending, then name ascending with nulls last for name. Employee is a record(String department, BigDecimal salary, String name).
DebuggingIntermediate8 min read
A batch job sorting 2 million records fails intermittently with java.lang.IllegalArgumentException: Comparison method violates its general contract! The comparator compares two double scores and returns 1 if a > b, -1 otherwise. What is wrong and how do you fix it?
DesignAdvanced8 min read
A reporting service must sort 500 GB of order events by customer and timestamp every night, and the machine has 32 GB of heap. How would you design the sort, and when would you push the work to the database or a data platform instead?
LeadershipPrincipal7 min read
Over twenty years, sort implementations in standard libraries changed several times: Java moved from merge sort to TimSort for objects and to dual-pivot quicksort for primitives, and a correctness bug was found in TimSort itself through formal verification. What does that history teach about relying on platform algorithms versus writing your own in a large organisation?

Searching algorithms

CodingFoundations8 min read
Write a binary search that returns the index of the first element >= target in a sorted int[] (lower bound), or a.length if none. Explain how you avoid off-by-one and overflow bugs.
ScenarioIntermediate9 min read
A service looks up product prices by SKU 50,000 times per second. Data is 2 million entries loaded at startup and refreshed hourly. Compare a sorted array with binary search, a HashMap, and a TreeMap for this use, including memory and refresh behaviour.
DesignAdvanced7 min read
Several teams implement their own in-memory search over reference data (binary search over arrays, ad hoc tries, linear scans with filters). Lookups are slow and inconsistent across services. How would you decide what belongs in a shared library, what belongs in a search engine or database, and how to roll it out?

Recursion

CodingFoundations7 min read
Write a recursive method that returns all permutations of a String with distinct characters, then explain its time complexity and how deep the recursion goes for a 10-character input.
DebuggingFoundations7 min read
A method that walks a category tree recursively throws StackOverflowError for one customer whose data has about 40,000 nested levels caused by a bad import. What are your options to fix the code, and why does Java not save you with tail calls?
InternalsIntermediate7 min read
Explain how memoization changes a naive recursive solution such as counting the ways to climb n stairs with steps of 1, 2 or 3. Compare a HashMap memo, an array memo, and a bottom-up loop in Java, including pitfalls with computeIfAbsent.
LeadershipPrincipal7 min read
Recursive designs keep appearing in your products: recursive JSON parsers, recursive SQL for org charts, recursive permission resolution across group hierarchies. Several outages came from unbounded depth or cycles. What engineering standards would you set across the company?

Big-O complexity

ConceptFoundations7 min read
Give the time complexity of these Java operations and the reason: ArrayList.get, ArrayList.add at the end, ArrayList.remove(0), LinkedList.get(i), HashMap.get, TreeMap.get, and String concatenation with += inside a loop of n iterations.
DebuggingIntermediate7 min read
An endpoint that deduplicates order lines runs in 20 ms for 1,000 lines but takes 30 seconds for 50,000. The code is: for (Line l : lines) if (!result.contains(l)) result.add(l); where result is an ArrayList. Explain the growth, fix it, and say how you would catch this kind of problem before production.
ScenarioAdvanced7 min read
Big-O says an algorithm is O(n log n) but your measured latency grows much faster as data grows from 1 GB to 20 GB in memory. What factors that big-O hides would you look at across the stack?
LeadershipPrincipal6 min read
Interview loops at many companies lean on algorithm puzzles while your engineers mostly integrate services and tune databases. As an engineering leader, how would you decide how much algorithmic knowledge to test in hiring and to grow on teams?

Data structure implementations

CodingFoundations7 min read
Implement a generic fixed-capacity ring buffer class RingBuffer<T> with offer(T), poll() and size(), backed by an array. Explain how you handle wrap-around and the generic array creation problem.
InternalsIntermediate7 min read
Why does ArrayDeque usually outperform LinkedList as a stack or queue in Java? Explain the memory layout and when LinkedList is still justified.
DesignIntermediate8 min read
Design an in-memory LFU (least frequently used) cache with O(1) get and put in Java. Describe the data structures and how ties are broken.
LeadershipAdvanced7 min read
A team proposes adding a third-party primitive collections library (for example fastutil, Eclipse Collections or HPPC) to cut heap use in several services by 40 percent. How do you evaluate and govern that decision?

Trees and binary search trees

ConceptFoundations8 min read
Why does java.util.TreeMap use a red-black tree instead of a plain binary search tree, and what guarantees does that give?
CodingFoundations7 min read
Given
class Node {
int val;
Node left, right;
}
write a method that checks whether a binary tree is a valid binary search tree. Explain why checking only each node against its direct children is wrong.
ConceptIntermediate7 min read
Databases use B+ trees for indexes while in-memory libraries use binary trees. Explain why, and what that means for a Java developer reasoning about index lookups.
DesignAdvanced8 min read
You need an in-memory structure for interval queries: given 5 million time ranges for bookings, find all bookings overlapping a query range in under a millisecond. What structures would you consider, and how would you keep updates safe under concurrency?
DesignPrincipal7 min read
Log-structured merge trees replaced B-trees in many newer storage engines (RocksDB, Cassandra), while PostgreSQL and MySQL InnoDB still use B-trees. As the person setting data platform direction, how do you explain the trade-off and decide which engines your company supports?

Graphs, BFS and DFS

CodingFoundations7 min read
Given a grid char[][] of '1' (land) and '0' (water), write Java code that counts islands of connected land cells (up, down, left, right). Explain whether you would use BFS or DFS and why.
CodingIntermediate8 min read
Services declare dependencies on other services as a Map<String, List<String>>. Write an algorithm that returns a valid startup order or reports a cycle, and explain its complexity.
ScenarioIntermediate8 min read
A permissions service resolves a user's effective roles by walking group memberships: groups can contain groups. Requests are slow for some users and one request ran until timeout. What went wrong and how would you redesign it?
DesignAdvanced8 min read
Your company wants a dependency graph of 2,000 services built from tracing data, with queries like blast radius of a failure and shortest call path. Would you build it on a graph database, a relational database, or in-memory Java graphs? Justify.
LeadershipPrincipal7 min read
Many of your platform problems are graph problems in disguise: dependency upgrades, data lineage, access control and service ownership. How would you build organisational capability so teams recognise and solve them consistently?

Heaps and priority queues

InternalsFoundations8 min read
How is java.util.PriorityQueue implemented, and what are the costs of offer, poll, peek, remove(Object) and contains?
CodingFoundations7 min read
Write Java code that returns the k most frequent words from a List<String> using a PriorityQueue, and give the complexity.
ScenarioIntermediate8 min read
A scheduling service holds 10 million pending jobs in a PriorityQueue ordered by due time, and jobs can be cancelled. Cancellation calls queue.remove(job) and CPU is saturated. How do you fix it?
DesignAdvanced7 min read
You must merge sorted event streams from 300 Kafka partitions into one globally time-ordered stream with bounded memory and late events up to 5 seconds. Describe the algorithm and its failure modes.
LeadershipPrincipal7 min read
Priority and fairness decisions show up in job schedulers, support queues and API rate limits across your company. Some customers complain they are always starved. How do you set principles for prioritisation systems at company scale?

Hashing

CodingFoundations7 min read
Write a method that returns the indices of two numbers in an int[] that add up to a target, in one pass. Explain the time and space complexity and what changes if the array is sorted.
ConceptIntermediate7 min read
Explain consistent hashing and why a cache or sharding layer would use it instead of hash(key) % n. How do virtual nodes help?
ScenarioAdvanced7 min read
You need to deduplicate 5 billion click events per day by event id and cannot keep a full set in memory. What approaches would you consider, and what are their error trade-offs?
LeadershipPrincipal7 min read
Hash functions in your systems serve very different purposes: HashMap buckets, sharding keys, cache keys, password storage and integrity checks. After an incident where a team used MD5 to store API tokens, how would you set company-wide rules?

Dynamic programming

CodingFoundations7 min read
Write a Java method for the coin change problem: given coins int[] {1, 5, 10, 25} and an amount, return the minimum number of coins, or -1 if impossible. Explain the recurrence.
CodingIntermediate8 min read
Write the longest common subsequence length of two strings in Java with O(min(m, n)) memory, and say how you would also reconstruct the subsequence.
ScenarioAdvanced7 min read
A pricing team wrote a recursive DP over product bundles that takes 40 minutes per run and now must run per request. How would you approach making this feasible?
LeadershipPrincipal6 min read
Optimisation problems such as routing, scheduling and pricing often start as clever in-house algorithms written by one engineer. Years later nobody can maintain them. How do you decide between in-house algorithms, commercial or open source solvers, and simpler heuristics?

Two pointers and sliding window

CodingFoundations6 min read
Write a Java method that returns the length of the longest substring without repeating characters, for example 'abcabcbb' gives 3. Explain why it is O(n).
ScenarioIntermediate7 min read
An API gateway must enforce 100 requests per minute per client. Compare a fixed window counter, a sliding window log, and a sliding window counter, and say which you would use with Redis across many gateway instances.
DesignAdvanced7 min read
A monitoring platform computes p99 latency over sliding 5-minute windows for 50,000 time series. A naive implementation keeps every sample and sorts each window. How would you redesign it?

Bit manipulation

CodingFoundations7 min read
Write Java methods to check if an int is a power of two, count set bits, and find the single number that appears once in an array where all others appear twice. Explain each trick.
InternalsIntermediate8 min read
Explain where bit manipulation appears inside JDK classes such as HashMap, BitSet and EnumSet, and why these choices matter for performance.
DesignAdvanced7 min read
A feature flag and permission system stores user permissions as a long bitmask in a database column. Now there are 90 permissions and multiple products. Evaluate the design and propose a migration path.