Algorithms and data structures in Java
49 questions in 12 subtopics.
Sorting algorithms
Which algorithms does the JDK use forArrays.sort(int[]), Arrays.sort(Object[]) and Collections.sort(List), and why are primitives and objects sorted differently?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).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?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?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
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.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, aHashMap, and a TreeMap for this use, including memory and refresh behaviour.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
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.A method that walks a category tree recursively throwsStackOverflowError 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?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.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
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.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.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?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
Implement a generic fixed-capacity ring buffer classRingBuffer<T> with offer(T), poll() and size(), backed by an array. Explain how you handle wrap-around and the generic array creation problem.Why does ArrayDeque usually outperform LinkedList as a stack or queue in Java? Explain the memory layout and when LinkedList is still justified.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.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
Why doesjava.util.TreeMap use a red-black tree instead of a plain binary search tree, and what guarantees does that give?Givenclass Node {
int val;
Node left, right;
}
Graphs, BFS and DFS
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.Services declare dependencies on other services as aMap<String, List<String>>. Write an algorithm that returns a valid startup order or reports a cycle, and explain its complexity.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?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.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
How isjava.util.PriorityQueue implemented, and what are the costs of offer, poll, peek, remove(Object) and contains?Write Java code that returns the k most frequent words from a List<String> using a PriorityQueue, and give the complexity.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?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.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
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.Explain consistent hashing and why a cache or sharding layer would use it instead ofhash(key) % n. How do virtual nodes help?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?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
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.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.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?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
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).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.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
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.Explain where bit manipulation appears inside JDK classes such asHashMap, BitSet and EnumSet, and why these choices matter for performance.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.No question matches these choices.