r/LowLevelDesign • • Oct 09 '26

Atlassian LLD: Design a Middleware Router for Matching Paths

52 Upvotes

This is another one of the most common questions asked in Atlassian low level design rounds. I have started with a simple brute force solution which scans through each path, but is useful in understanding the matching rules. After that I have used the more efficient Trie approach so that each prefix is listed once. This tutorial is in Java.

Here is the Python version: https://github.com/prsnt558908/CodeZymSolutions/tree/main/1-100/36-design-middleware-router/q-36-python-tutorial.md

You can practice this and other Atlassian LLD and DSA round questions on CodeZym.

PS: I also take LLD Mock interviews https://topmate.io/prashant_priyadarshi


Problem Statement

Build an in-memory router that maps path patterns to a result string (a server id). For each request path, return the result of the best matching pattern.

Pattern segments (split on /)

  • Static, like users: must match exactly.
  • Wildcard *: matches exactly one non-empty segment.
  • Param :name, like :id: matches exactly one non-empty segment.

Methods

  • addRoute(pathPattern, result): adds a route. Adding an existing pattern updates its result but keeps its original position.
  • callRoute(path): returns the result of the best match, or "NOT_FOUND".
  • searchRoutes(wildcardPattern): returns, in insertion order, the results of all stored routes that could match the same path as the query.

Precedence: more static segments wins (static beats :param, which beats *), then the longer pattern, then the route added earlier.


Overview

A router keeps a table of path patterns and, for each request, returns the result of the most specific pattern that matches. We start with the brute force, which checks every route on every request. Then we build a trie of path segments that looks only at routes that could match, and skips any branch that cannot beat the best match found so far.

Pin down the rules

A few small details decide whether a solution passes, so settle them before writing code.

Segments. Drop the leading / and split on /, keeping empty pieces. /bar/a/baz is ["bar", "a", "baz"], /bar/ is ["bar", ""], and / on its own has zero segments.

Matching. A pattern matches a path when both have the same number of segments and every pair of segments matches. A static segment must be equal. A * or :name segment accepts any non-empty segment, so /bar/* does not match /bar/.

Rank. When several patterns match, the winner is decided by:

  1. More static segments wins.
  2. Then more :param segments wins. Both patterns have the same length, so more params means fewer wildcards.
  3. Then the route added earlier wins.

The statement also says a longer pattern wins, but that rule never decides anything here: two patterns that match the same path always have the same length.

Specificity is counted over the whole pattern. It is not decided at the first position where two patterns differ. For /a/b/c, the pattern /*/b/c beats /a/*/* because it has two static segments instead of one. Keep this in mind, because it breaks the most common trie shortcut.

Search. searchRoutes takes a pattern that may contain placeholders and returns every stored route that could match at least one common concrete path. Placeholders can appear on either side:

Stored segment ↓ / query segment →static q* or :name
static scompatible if s equals qcompatible if s is non-empty
* or :namecompatible if q is non-emptyalways compatible

That is why the static query /bar/a/baz also returns /bar/*/baz and /bar/:x/baz. Results come back in insertion order, one per route even when two routes share a result string, and they are never sorted by rank.

Updates. Adding a pattern that already exists changes only its result. Its position stays the same, which matters both for tie-breaks and for search order. /a/:x/c and /a/:y/c are different strings, so they are two different routes.

Request paths in callRoute are concrete, so they only ever use the static q column of the table. Using the same compatibility rule for both methods keeps the code small and consistent.

Brute force: check every route

Store two lists in insertion order: the patterns and their results.

  • addRoute looks for the pattern in the list. If it is there, replace the result in place. Otherwise append it.
  • callRoute splits the request. For every stored pattern, it splits the pattern, checks compatibility, counts static and param segments, and keeps the best route. We scan in insertion order and replace the best only when a route is strictly better, so a full tie keeps the earlier route.
  • searchRoutes returns the result of every compatible route. The list is already in insertion order.
import java.util.ArrayList;
import java.util.List;

public class Router {
    private final List<String> patterns = new ArrayList<>(); // insertion order
    private final List<String> results = new ArrayList<>();  // results.get(i) belongs to patterns.get(i)

    public Router() {
    }

    public void addRoute(String pathPattern, String result) {
        int index = patterns.indexOf(pathPattern); // linear search for an existing pattern
        if (index >= 0) {
            results.set(index, result);            // same position, new result
            return;
        }
        patterns.add(pathPattern);
        results.add(result);
    }

    public String callRoute(String path) {
        String[] request = split(path);
        String bestResult = "NOT_FOUND";
        int bestStatic = -1;
        int bestParams = -1;

        for (int i = 0; i < patterns.size(); i++) {
            String[] pattern = split(patterns.get(i)); // parsed again on every call
            if (!compatible(pattern, request)) {
                continue;
            }
            int statics = 0;
            int params = 0;
            for (String segment : pattern) {
                if (segment.startsWith(":")) {
                    params++;
                } else if (!segment.equals("*")) {
                    statics++;
                }
            }
            // Only a strictly better route replaces the best one, so a full tie keeps the earlier route.
            if (statics > bestStatic || (statics == bestStatic && params > bestParams)) {
                bestResult = results.get(i);
                bestStatic = statics;
                bestParams = params;
            }
        }
        return bestResult;
    }

    public List<String> searchRoutes(String wildcardPattern) {
        String[] query = split(wildcardPattern);
        List<String> found = new ArrayList<>();
        for (int i = 0; i < patterns.size(); i++) {
            if (compatible(split(patterns.get(i)), query)) {
                found.add(results.get(i));
            }
        }
        return found;
    }

    /** "/" has no segments. Other empty segments are kept: "/a/" is ["a", ""]. */
    private static String[] split(String path) {
        if (path.equals("/")) {
            return new String[0];
        }
        return path.substring(1).split("/", -1);
    }

    private static boolean isPlaceholder(String segment) {
        return segment.equals("*") || segment.startsWith(":");
    }

    /** Could one concrete path match both? Placeholders may be on either side. */
    private static boolean compatible(String[] a, String[] b) {
        if (a.length != b.length) {
            return false;
        }
        for (int i = 0; i < a.length; i++) {
            if (isPlaceholder(a[i]) || isPlaceholder(b[i])) {
                if (a[i].isEmpty() || b[i].isEmpty()) {
                    return false; // a placeholder needs a non-empty segment
                }
            } else if (!a[i].equals(b[i])) {
                return false;
            }
        }
        return true;
    }
}

With R routes and paths of up to P characters, every operation costs O(R × P).

This is correct, and it is a fine first answer in an interview. But every request repeats work it does not need:

  • Every pattern is split and counted again on every call.
  • Routes with the wrong number of segments are still checked, although they can never match.
  • Routes that share a prefix, such as hundreds of routes under /api/v1, compare that prefix again for each route.
  • addRoute scans the whole list to find an existing pattern.

Parsing each pattern once and storing routes in a LinkedHashMap fixes the first and last points. The lookup still visits every route, though. Fixing the middle two needs a different structure.

Three observations

  1. Length is a hard filter. A pattern with three segments can only match a path with three segments. If routes are grouped by segment count, a request never looks at routes of another length.

  2. A route's rank does not depend on the request. Its static count, param count and insertion order all come from the pattern. We can compute them once when the route is added and compare two routes without looking at the request at all.

  3. Routes share prefixes, and static segments can be looked up by hash. /users/:id and /users/:id/orders/:orderId both start with users followed by a param. A trie keyed by segment stores each shared prefix once and finds the matching static child at each level in O(1).

Better approach: a segment trie with pruning

The structure

  • Route holds the result, the insertion order, and the two rank counts, computed once.
  • routesByPattern maps the exact pattern string to its Route, so an update is a single hash lookup and keeps the order.
  • triesByLength holds one trie per segment count (observation 1).
  • Each TrieNode has:
    • staticChildren, a HashMap from segment to child
    • paramChild, one child shared by every :name
    • wildcardChild, the child for *
    • routes, the routes that end at this node, oldest first
    • bestInSubtree, the highest-ranked route at or below this node (observation 2)

All :name segments share one child because a param's name changes neither what it matches nor how the route ranks. So /a/:x/c and /a/:y/c end at the same node, and its routes list keeps them in insertion order. That is exactly the tie-break from Example 5.

Here is the length-3 trie after the routes from the search example. The numbers are insertion order:

#0  /bar/*/baz   server-wild-v2   rank: 2 static, 0 params
#1  /bar/:x/baz  server-param     rank: 2 static, 1 param
#2  /bar/a/baz   server-static    rank: 3 static
#3  /bar/*/qux   server-qux       rank: 2 static, 0 params

trie for length 3                     bestInSubtree
root                                  #2
└── bar                               #2
    ├── a     (static)                #2
    │   └── baz    routes: [#2]       #2
    ├── :     (param)                 #1
    │   └── baz    routes: [#1]       #1
    └── *     (wildcard)              #0   (#0 and #3 tie on counts; #0 is older)
        ├── baz    routes: [#0]       #0
        └── qux    routes: [#3]       #3

addRoute

If the pattern already exists, update its result and stop. Otherwise create a Route with the next order number, pick the trie for its length, and walk down, creating children as needed. At every node on the way, root included, offer the new route as bestInSubtree. It replaces the current one only if it outranks it. Finally, add the route to the last node's routes. That is L steps for a pattern with L segments.

callRoute: the first match is not enough

A common trie shortcut is to try the static child first, then the param child, then the wildcard child, and to return the first complete match. That is fast, but it implements positional precedence, where a static segment near the start beats anything after it. In this problem, precedence is counted. With routes /a/*/* and /*/b/c, the shortcut reaches /a/*/* first through the static child a and returns it, but /*/b/c has more static segments and must win.

So we have to consider every compatible branch and keep the best route found. Doing that blindly would visit the whole compatible part of the trie. bestInSubtree lets us skip most of it. This technique is called branch and bound:

  • Visit children in the order static, param, wildcard. Static branches tend to hold the strongest routes, so a good candidate appears early.
  • Before entering a node, compare its bestInSubtree with the best match so far. bestInSubtree is the strongest route in that subtree, whether it matches or not. If it does not outrank the current best, nothing below it can, so skip the whole subtree.
  • Once the walk has used every segment, every route stored at that node has the same shape and therefore the same counts, so the oldest one wins. That is the node's bestInSubtree.

Each trie holds routes of a single length, which keeps the bound tight. For example, once a fully static route matches, every other compatible branch contains a placeholder, has fewer static segments, and is skipped without being entered.

The tie-break no longer depends on the order in which nodes are visited. outranks compares insertion order explicitly, so the iteration order of a HashMap cannot change the answer.

searchRoutes

It uses the same walk, with two differences:

  • A placeholder in the query can face any non-empty static segment. At a * or :name query segment, visit every static child with a non-empty key, plus the param and wildcard children.
  • We want every compatible route, so nothing is pruned. Once the walk has used every segment, collect all of the node's routes, then sort what was collected by insertion order.

Both methods ask a node for childrenCompatibleWith(segment), and that one method encodes the compatibility table. The two methods cannot disagree about what matches.

Walkthrough

Using the trie above:

  • callRoute("/bar/a/baz") goes root → bar → static a → baz and finds #2, with 3 static segments. Back at bar, the param branch's best is #1 and the wildcard branch's best is #0. Neither outranks #2, so both branches are skipped without being entered. The answer is server-static.
  • callRoute("/bar/b/baz") finds no static child b. The param branch yields #1. The wildcard branch's best, #0, has the same static count but fewer params, so it is skipped. The answer is server-param.
  • searchRoutes("/bar/*/baz") reaches the * query segment at bar and visits a, : and *. Each has a baz child, so it collects #2, #1 and #0, then sorts them into ["server-wild-v2", "server-param", "server-static"]. The update to #0 changed its result, not its position.

Which data structures and design patterns help

Most of the improvement comes from data structures:

  • A HashMap from exact pattern to route turns an update into one hash lookup that keeps insertion order.
  • Bucketing by segment count is an index on the one property every match checks first.
  • A trie over segments, with static children in a HashMap, stores and compares each shared prefix once, and each static step is an O(1) lookup.
  • A subtree summary on each node (bestInSubtree) makes the pruning possible. It is the same idea as storing a subtree maximum in a segment tree or an augmented binary search tree, and it costs O(L) per insert to maintain.
  • Sorting only the k search results restores insertion order without walking every route in order.

Design patterns play a smaller role:

  • Chain of Responsibility. The word "middleware" suggests it: each route is a handler that either takes the request or passes it on. A plain chain returns the first handler that takes the request, which is wrong here unless the chain is sorted by rank. Observation 2 makes that sorting possible, and "keep the routes sorted by rank, return the first match" is a reasonable intermediate answer. Each request still walks the chain, though, so the worst case stays O(R × L). Chain of Responsibility fits what middleware does after routing, such as running auth, then logging, then the handler.
  • Strategy for segment types. Each kind of segment could be a class with matches() and rank() methods. With three fixed kinds that the trie already stores in separate slots, those classes would add code without removing any logic. The small SegmentType enum is the place to grow: if you add regex-constrained params such as :id(\d+) or a catch-all segment, it can become a SegmentMatcher interface with one class per kind.
  • Composite. The trie is recursive, but every node has the same type and the same job, so it is simply a tree. Calling it a Composite adds nothing.

The design choice that matters most here is not a named pattern: keep each rule in one place. The matching rule lives only in TrieNode.childrenCompatibleWith, and the ranking rule lives only in Route.outranks. Both public lookups are built from those two methods.

Complexity

Let R be the number of distinct patterns, L the number of segments in the request or query, P its length in characters, V the number of trie nodes a lookup visits, and k the number of search results. Treat hashing or comparing one segment as O(1), since segments are short. Splitting a path then costs O(P).

ApproachaddRoutecallRoutesearchRoutes
Brute forceO(R × P)O(R × P)O(R × P)
Pre-parsed scanO(P)O(P + R × L)O(P + R × L)
Segment trieO(P)O(P + V)O(P + V + k log k)

All three use space proportional to the total size of the stored patterns.

The trie's cost depends on V, not on R. For a table of mostly static routes with some params, V stays close to L, so a lookup takes time proportional to the request alone. In a quick benchmark with about 20,000 REST-style routes, the trie answered callRoute several hundred times faster than the pre-parsed scan, with identical results.

The worst case does not improve. A table built so that many branches stay compatible and nothing can be pruned makes V reach every node of the trie, which costs the same O(R × L) as a scan. A search such as /*/*/* must visit every node of that length by definition, since every route of that length is a result.

Edge cases

  • / has zero segments, and only the pattern / matches it.
  • A trailing or double slash creates an empty segment. The pattern /bar/ matches the path /bar/, but /bar/* does not, because a placeholder needs a non-empty segment.
  • /a/:x/c and /a/:y/c are separate routes. The earlier one wins callRoute, and searchRoutes returns both.
  • An update keeps the route's position, both for the tie-break and for search order.
  • Search returns one entry per route, so a result string shared by two routes appears twice.
  • In a search query, :name behaves exactly like *.

Code

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Router {
    // Exact pattern string -> its route, so adding a pattern again is an O(1) update.
    private final Map<String, Route> routesByPattern = new HashMap<>();
    // One trie per segment count: a pattern can only match paths of its own length.
    private final Map<Integer, TrieNode> triesByLength = new HashMap<>();
    private int nextOrder = 0;

    public Router() {
    }

    /** Adds a pattern, or replaces its result while keeping its original position. */
    public void addRoute(String pathPattern, String result) {
        Route existing = routesByPattern.get(pathPattern);
        if (existing != null) {
            existing.result = result;
            return;
        }

        String[] segments = splitPath(pathPattern);
        Route route = new Route(segments, result, nextOrder++);
        routesByPattern.put(pathPattern, route);

        TrieNode node = triesByLength.computeIfAbsent(segments.length, length -> new TrieNode());
        node.offer(route);
        for (String segment : segments) {
            node = node.childFor(segment);
            node.offer(route);
        }
        node.routes.add(route);
    }

    /** Returns the result of the highest-ranked matching route, or "NOT_FOUND". */
    public String callRoute(String path) {
        String[] segments = splitPath(path);
        Route best = findBest(triesByLength.get(segments.length), segments, 0, null);
        return best == null ? "NOT_FOUND" : best.result;
    }

    /** Returns the results of all routes compatible with the query, in insertion order. */
    public List<String> searchRoutes(String wildcardPattern) {
        String[] segments = splitPath(wildcardPattern);
        List<Route> found = new ArrayList<>();
        collect(triesByLength.get(segments.length), segments, 0, found);

        found.sort(Comparator.comparingInt(route -> route.order));
        List<String> results = new ArrayList<>(found.size());
        for (Route route : found) {
            results.add(route.result);
        }
        return results;
    }

    /**
     * Returns the best route under node that matches segments[depth..],
     * or best if nothing under node outranks it.
     */
    private Route findBest(TrieNode node, String[] segments, int depth, Route best) {
        if (node == null) {
            return best;
        }
        // Branch and bound: if the best route anywhere below cannot win, skip the whole subtree.
        if (best != null && !node.bestInSubtree.outranks(best)) {
            return best;
        }
        if (depth == segments.length) {
            // All routes here have the same shape, so the oldest one (bestInSubtree) wins.
            return node.bestInSubtree;
        }
        for (TrieNode child : node.childrenCompatibleWith(segments[depth])) {
            best = findBest(child, segments, depth + 1, best);
        }
        return best;
    }

    /** Adds every route under node that is compatible with segments[depth..]. */
    private void collect(TrieNode node, String[] segments, int depth, List<Route> found) {
        if (node == null) {
            return;
        }
        if (depth == segments.length) {
            found.addAll(node.routes);
            return;
        }
        for (TrieNode child : node.childrenCompatibleWith(segments[depth])) {
            collect(child, segments, depth + 1, found);
        }
    }

    /** "/" has no segments. Other empty segments are kept: "/a/" is ["a", ""]. */
    static String[] splitPath(String path) {
        if (path.equals("/")) {
            return new String[0];
        }
        return path.substring(1).split("/", -1);
    }
}

/** The three kinds of segment a pattern can contain. */
enum SegmentType {
    STATIC, PARAM, WILDCARD;

    static SegmentType of(String segment) {
        if (segment.equals("*")) {
            return WILDCARD;
        }
        if (segment.startsWith(":")) {
            return PARAM;
        }
        return STATIC;
    }
}

/** A stored pattern. Its rank depends only on the pattern, never on the request. */
class Route {
    final int order;  // insertion position; an update keeps it
    final int staticCount;
    final int paramCount;
    String result;

    Route(String[] segments, String result, int order) {
        this.result = result;
        this.order = order;
        int statics = 0;
        int params = 0;
        for (String segment : segments) {
            SegmentType type = SegmentType.of(segment);
            if (type == SegmentType.STATIC) {
                statics++;
            } else if (type == SegmentType.PARAM) {
                params++;
            }
        }
        this.staticCount = statics;
        this.paramCount = params;
    }

    /** True if this route beats other when both match the same path. */
    boolean outranks(Route other) {
        if (staticCount != other.staticCount) {
            return staticCount > other.staticCount;
        }
        if (paramCount != other.paramCount) {
            return paramCount > other.paramCount;
        }
        return order < other.order;
    }
}

/** One level of path segments. */
class TrieNode {
    final Map<String, TrieNode> staticChildren = new HashMap<>();
    TrieNode paramChild;     // shared by every ":name"; names affect neither matching nor rank
    TrieNode wildcardChild;
    final List<Route> routes = new ArrayList<>(); // routes ending here, oldest first
    Route bestInSubtree;     // highest-ranked route at or below this node

    void offer(Route route) {
        if (bestInSubtree == null || route.outranks(bestInSubtree)) {
            bestInSubtree = route;
        }
    }

    /** Returns the child for a pattern segment, creating it if needed. */
    TrieNode childFor(String segment) {
        SegmentType type = SegmentType.of(segment);
        if (type == SegmentType.WILDCARD) {
            if (wildcardChild == null) {
                wildcardChild = new TrieNode();
            }
            return wildcardChild;
        }
        if (type == SegmentType.PARAM) {
            if (paramChild == null) {
                paramChild = new TrieNode();
            }
            return paramChild;
        }
        return staticChildren.computeIfAbsent(segment, key -> new TrieNode());
    }

    /**
     * Children whose segment can match the same request segment as the given one.
     * Static comes first, then param, then wildcard, so strong candidates are found early.
     */
    List<TrieNode> childrenCompatibleWith(String segment) {
        List<TrieNode> children = new ArrayList<>();
        if (SegmentType.of(segment) == SegmentType.STATIC) {
            TrieNode exact = staticChildren.get(segment);
            if (exact != null) {
                children.add(exact);
            }
        } else {
            // A placeholder in a search query can stand for any non-empty static segment.
            for (Map.Entry<String, TrieNode> entry : staticChildren.entrySet()) {
                if (!entry.getKey().isEmpty()) {
                    children.add(entry.getValue());
                }
            }
        }
        // Stored placeholders match any non-empty segment.
        if (!segment.isEmpty()) {
            if (paramChild != null) {
                children.add(paramChild);
            }
            if (wildcardChild != null) {
                children.add(wildcardChild);
            }
        }
        return children;
    }
}

Thanks for reading. Best of Luck For Your Interview Prep.


r/LowLevelDesign • • Oct 06 '26

Atlassian LLD: Design a customer support agent rating leaderboard

71 Upvotes

This is one of the most common questions asked in Atlassian low level design rounds. Rate Limiter, Last Lap Hero and Middleware Router are also asked frequently. I have started with a simple solution which use sum and count of ratings. After that I have extended the solution using observer design pattern. This gives us the benefit of adding more display lists without altering existing code. This tutorial is in Java.

Here is the Python version: https://github.com/prsnt558908/CodeZymSolutions/tree/main/1-100/35-design-customer-support-agent-rating-leaderboard/q-35-python-tutorial.md

You can practice this and other Atlassian LLD and DSA round questions on CodeZym.

PS: I also take LLD Mock interviews https://topmate.io/prashant_priyadarshi


Problem Statement

Design an in-memory leaderboard where each customer interaction gives an agent a rating from 1 to 5.

Methods

  • void rateAgent(String agentName, int rating, String date): records one rating; date is YYYY-MM-DD.
  • List<String> getAverageRatings(): every agent with their overall average rating.
  • List<String> getBestAgentsByMonth(String month): the same, but counting only ratings in month (YYYY-MM).

Output rules

  • Each entry is "agentName,averageRating", e.g. "Bob,4.5".
  • Averages are rounded half-up to one decimal place (4.33 → 4.3, 4.35 → 4.4) and always show one decimal (4.0).
  • Sort by average, highest first. Break ties by agent name in ascending order.

Constraints: Agent names are non-empty and case-sensitive. The design should scale to thousands of agents and millions of ratings.

Example: Alice is rated 5 and 3, and Bob is rated 4 and 5. getAverageRatings() returns ["Bob,4.5", "Alice,4.0"].

High Level Solution Overview

The core idea is simple: do the math when a rating comes in, not when someone asks for the leaderboard.

To find an average, we never need the individual ratings. We only need two numbers per agent: the sum of the ratings and the count of ratings.

So we keep these two numbers for every agent overall, and once more for every agent in every month. A leaderboard query only turns each sum and count into a rounded average and sorts.

At the end, we add more leaderboards like this year and last 7 days, using the Observer pattern so that adding them never changes rateAgent.

Understanding the Problem

We need three methods:

  • rateAgent(agentName, rating, date): records one rating (1 to 5) for an agent on a date.
  • getAverageRatings(): returns every agent with their overall average, best first.
  • getBestAgentsByMonth(month): same as above, but only ratings from that month count.

Each entry in the result looks like "Bob,4.5".

The system should handle thousands of agents and millions of ratings, so the speed of each method matters.

Two Small Details That Matter

1. Rounding to one decimal

Averages are rounded to one decimal, and a 5 in the second decimal rounds up. So 4.33 becomes 4.3, while 4.35 and 4.37 become 4.4.

A double cannot store 4.35 exactly. It is really stored as 4.3499999999999996..., so new BigDecimal(4.35).setScale(1, RoundingMode.HALF_UP) gives 4.3, not 4.4.

To stay safe, we round using whole numbers only, which are always exact:

averageInTenths = (sum * 10 + count / 2) / count

Integer division always rounds down. Adding half of count before dividing pushes anything at .5 or above up to the next number.

The result is the average in tenths, so 43 means 4.3.

RatingsExact average(sum * 10 + count / 2) / countResult
5, 34.0(80 + 1) / 2 = 404.0
5, 4, 44.333...(130 + 1) / 3 = 434.3
5, 4, 4, 44.25(170 + 2) / 4 = 434.3
7 fives, 13 fours4.35(870 + 10) / 20 = 444.4

To print it, tenths / 10 gives the part before the dot and tenths % 10 gives the digit after it. So 43 becomes "4.3".

2. Sorting

We sort by the rounded average, highest first, because that is the number we print.

If two agents show the same rounded average, the name that comes first lexicographically goes first. For example, Bob (4.33) and Alice (4.25) both show 4.3, so Alice comes before Bob.

Names are case-sensitive, so we use plain compareTo. In this order capital letters come before small letters, so "Zoe" comes before "adam".

Solution: Keep Running Totals

rateAgent adds the rating to the agent's running totals and then forgets it. The leaderboard methods only sort what is already there.

No design pattern is needed for these three methods. One small helper class and two hash maps are enough.

Data structures

overallStats : agentName -> AgentStats
monthlyStats : month -> (agentName -> AgentStats)
  • AgentStats: an agent's name, rating sum and rating count, plus the rounding logic.
  • overallStats: finds an agent's totals in O(1) whenever a rating comes in.
  • monthlyStats: first find the month, then the agent. A monthly query reads only the agents rated in that month.

How each method works

  • rateAgent: get the month with date.substring(0, 7). Add the rating to the agent's overall totals and to the agent's totals for that month.
  • getAverageRatings: copy all values of overallStats into a list, sort it, and format each entry as "name,average".
  • getBestAgentsByMonth: same steps, using the inner map of that month. If nobody was rated in that month, return an empty list.

Walkthrough with Example 2

After the five ratings, monthlyStats looks like this:

"2025-02" -> Alice (sum 5, count 1), Bob (sum 3, count 1), Charlie (sum 4, count 1)
"2025-03" -> Bob (sum 5, count 1), Alice (sum 2, count 1)

getBestAgentsByMonth("2025-02") reads only the first inner map and returns ["Alice,5.0", "Charlie,4.0", "Bob,3.0"]. The March ratings are never touched.

Code

import java.util.*;

public class AgentRatingLeaderboard {

    // agentName -> totals of all ratings of that agent
    Map<String, AgentStats> overallStats = new HashMap<>();

    // month ("YYYY-MM") -> (agentName -> totals of that agent in that month)
    Map<String, Map<String, AgentStats>> monthlyStats = new HashMap<>();

    public AgentRatingLeaderboard() {
    }

    /**
     * O(1): the rating is added to two running totals and then thrown away.
     * computeIfAbsent returns the value for a key, creating and storing it first if missing.
     */
    public void rateAgent(String agentName, int rating, String date) {
        String month = date.substring(0, 7); // "2025-03-12" -> "2025-03"

        // 1. overall totals of this agent
        overallStats.computeIfAbsent(agentName, name -> new AgentStats(name))
                .addRating(rating);

        // 2. totals of this agent for this month
        monthlyStats.computeIfAbsent(month, m -> new HashMap<>())
                .computeIfAbsent(agentName, name -> new AgentStats(name))
                .addRating(rating);
    }

    public List<String> getAverageRatings() {
        return buildLeaderboard(overallStats.values());
    }

    public List<String> getBestAgentsByMonth(String month) {
        Map<String, AgentStats> statsOfMonth = monthlyStats.get(month);
        if (statsOfMonth == null) {
            return new ArrayList<>(); // nobody was rated in this month
        }
        return buildLeaderboard(statsOfMonth.values());
    }

    /**
     * Sorts agents by rounded average (highest first), then by name (ascending),
     * and formats each one as "agentName,average".
     */
    List<String> buildLeaderboard(Collection<AgentStats> agents) {
        List<AgentStats> sorted = new ArrayList<>(agents);
        sorted.sort((a, b) -> {
            long avgA = a.getAverageInTenths();
            long avgB = b.getAverageInTenths();
            if (avgA != avgB) {
                return Long.compare(avgB, avgA); // higher average first
            }
            return a.agentName.compareTo(b.agentName); // same average: name in ascending order
        });

        List<String> leaderboard = new ArrayList<>();
        for (AgentStats stats : sorted) {
            leaderboard.add(stats.agentName + "," + stats.getAverageText());
        }
        return leaderboard;
    }
}

/**
 * Running totals of one agent's ratings.
 * We never keep individual ratings, only their sum and count.
 */
class AgentStats {
    String agentName;
    long ratingSum = 0;
    long ratingCount = 0;

    AgentStats(String agentName) {
        this.agentName = agentName;
    }

    void addRating(int rating) {
        ratingSum += rating;
        ratingCount++;
    }

    /**
     * Average x 10, rounded half up, using whole numbers only.
     * Example: sum = 13, count = 3 gives (130 + 1) / 3 = 43, which means 4.3
     */
    long getAverageInTenths() {
        return (ratingSum * 10 + ratingCount / 2) / ratingCount;
    }

    /** Average as text with exactly one decimal, like "4.3" or "5.0" */
    String getAverageText() {
        long tenths = getAverageInTenths();
        return (tenths / 10) + "." + (tenths % 10);
    }
}

Complexity

Here A is the number of agents and M is the number of agents rated in the asked month.

OperationTime
rateAgentO(1)
getAverageRatingsO(A log A)
getBestAgentsByMonthO(M log M)
MemoryO(A + number of (agent, month) pairs)

A query never looks at individual ratings. No matter how many ratings came in, it only sorts the agents.

Can we skip sorting on every call? The answer itself has A lines, so a query is at least O(A) anyway. Keeping agents always sorted in a TreeSet would slow down every rating and make the code harder to follow.

Follow Up: More Leaderboards with the Observer Pattern

Now suppose we need two more leaderboards:

  • getBestAgentsByYear(year): best agents of a year like "2026". Passing the current year shows the best agents of this year.
  • getBestAgentsInLast7Days(today): best agents over today and the 6 days before it.

Why not just add more maps?

We could add a yearlyStats map and a dailyStats map, and update both inside rateAgent. That works for now.

But every future leaderboard would again add a map and edit rateAgent. Soon rateAgent becomes a long list of unrelated updates, and each new feature risks breaking code that already works.

The Observer pattern

In the Observer pattern, one object (the subject) keeps a list of observers and notifies all of them whenever something happens.

Here the subject is AgentRatingLeaderboard, the event is a new rating, and every leaderboard is an observer.

  • RatingObserver: an interface with one method, onRating(agentName, rating, date).
  • Boards: every leaderboard implements RatingObserver and keeps its own totals in its own way.
  • rateAgent: passes the new rating to every board in the observers list.
rateAgent("Alice", 5, "2025-03-12")
  -> overallBoard.onRating(...)     adds to Alice's overall totals
  -> monthlyBoard.onRating(...)     adds to Alice's totals in "2025-03"
  -> yearlyBoard.onRating(...)      adds to Alice's totals in "2025"
  -> last7DaysBoard.onRating(...)   adds to Alice's totals on "2025-03-12"

Adding a leaderboard is now one new class plus one entry in observers, and rateAgent never changes. This is the Open/Closed principle: we add new features without modifying working code.

Sorting and formatting stay in buildLeaderboard, so every leaderboard follows the same rules.

The boards

  • OverallBoard: agentName -> AgentStats, same as overallStats before.
  • PeriodBoard: period -> (agentName -> AgentStats). The period is the first few characters of the date: new PeriodBoard(7) groups by month ("2025-03") and new PeriodBoard(4) groups by year ("2025").
  • LastDaysBoard: keeps totals per day and adds up the days of the window when asked.

The monthly and yearly leaderboards are the same class. So "this year" needed no new class at all.

Why last 7 days is different

A month or a year is a fixed bucket. Once a rating lands in March, it stays in March, so one running total per bucket works.

Last 7 days is a moving window. Every day, the oldest day leaves the window and a new one joins it. A single running total cannot remove the ratings of the day that left.

So LastDaysBoard keeps totals per day, using a PeriodBoard with the whole date as the period. A query adds up each agent's daily totals over the 7 days of the window.

That is at most 7 small maps, no matter how many ratings came in.

Our system has no clock. Every date comes from the caller, so the caller also passes today.

To step back one day at a time, we use LocalDate, which handles month and year changes. For example, one day before "2024-03-01" is "2024-02-29".

rateAgent("Alice", 5, "2025-03-01")
rateAgent("Alice", 5, "2025-03-02")
rateAgent("Bob", 4, "2025-03-05")
rateAgent("Alice", 3, "2025-03-07")

getAverageRatings()                    -> ["Alice,4.3", "Bob,4.0"]
getBestAgentsInLast7Days("2025-03-09") -> ["Bob,4.0", "Alice,3.0"]

The window of "2025-03-09" is March 3 to March 9. Alice's two 5s fall outside it, so only her 3 counts.

Code

import java.time.LocalDate;
import java.util.*;

public class AgentRatingLeaderboard {

    // each board keeps its own totals and answers its own query
    OverallBoard overallBoard = new OverallBoard();
    PeriodBoard monthlyBoard = new PeriodBoard(7);        // "2025-03-12" -> month "2025-03"
    PeriodBoard yearlyBoard = new PeriodBoard(4);         // "2025-03-12" -> year "2025"
    LastDaysBoard last7DaysBoard = new LastDaysBoard(7);  // today and the 6 days before it

    // every board that wants to hear about new ratings
    List<RatingObserver> observers = List.of(overallBoard, monthlyBoard, yearlyBoard, last7DaysBoard);

    public AgentRatingLeaderboard() {
    }

    /** Passes the new rating to every board. Adding a new board never changes this method. */
    public void rateAgent(String agentName, int rating, String date) {
        for (RatingObserver observer : observers) {
            observer.onRating(agentName, rating, date);
        }
    }

    public List<String> getAverageRatings() {
        return buildLeaderboard(overallBoard.getStats());
    }

    public List<String> getBestAgentsByMonth(String month) {
        return buildLeaderboard(monthlyBoard.getStats(month));
    }

    /** year is "YYYY". Pass the current year to get the best agents of this year. */
    public List<String> getBestAgentsByYear(String year) {
        return buildLeaderboard(yearlyBoard.getStats(year));
    }

    /** today is "YYYY-MM-DD". Counts ratings from today and the 6 days before it. */
    public List<String> getBestAgentsInLast7Days(String today) {
        return buildLeaderboard(last7DaysBoard.getStats(today));
    }

    /**
     * Sorts agents by rounded average (highest first), then by name (ascending),
     * and formats each one as "agentName,average". Shared by every leaderboard.
     */
    List<String> buildLeaderboard(Collection<AgentStats> agents) {
        List<AgentStats> sorted = new ArrayList<>(agents);
        sorted.sort((a, b) -> {
            long avgA = a.getAverageInTenths();
            long avgB = b.getAverageInTenths();
            if (avgA != avgB) {
                return Long.compare(avgB, avgA); // higher average first
            }
            return a.agentName.compareTo(b.agentName); // same average: name in ascending order
        });

        List<String> leaderboard = new ArrayList<>();
        for (AgentStats stats : sorted) {
            leaderboard.add(stats.agentName + "," + stats.getAverageText());
        }
        return leaderboard;
    }
}

/** Every board implements this to hear about each new rating */
interface RatingObserver {
    void onRating(String agentName, int rating, String date);
}

/** Totals of each agent over all time */
class OverallBoard implements RatingObserver {
    // agentName -> totals of all ratings of that agent
    Map<String, AgentStats> statsByAgent = new HashMap<>();

    public void onRating(String agentName, int rating, String date) {
        statsByAgent.computeIfAbsent(agentName, name -> new AgentStats(name))
                .addRating(rating);
    }

    Collection<AgentStats> getStats() {
        return statsByAgent.values();
    }
}

/**
 * Totals of each agent in fixed periods, like months or years.
 * The period is the first periodLength characters of the date.
 */
class PeriodBoard implements RatingObserver {
    int periodLength; // 4 -> year "2025", 7 -> month "2025-03", 10 -> day "2025-03-12"

    // period -> (agentName -> totals of that agent in that period)
    Map<String, Map<String, AgentStats>> statsByPeriod = new HashMap<>();

    PeriodBoard(int periodLength) {
        this.periodLength = periodLength;
    }

    public void onRating(String agentName, int rating, String date) {
        String period = date.substring(0, periodLength);
        statsByPeriod.computeIfAbsent(period, p -> new HashMap<>())
                .computeIfAbsent(agentName, name -> new AgentStats(name))
                .addRating(rating);
    }

    Collection<AgentStats> getStats(String period) {
        // an empty map if nobody was rated in this period
        return statsByPeriod.getOrDefault(period, new HashMap<>()).values();
    }
}

/**
 * Totals of each agent over the last N days.
 * The window moves every day, so we keep totals per day
 * and add up the days of the window when asked.
 */
class LastDaysBoard implements RatingObserver {
    int numberOfDays;

    // a day is also a period: the whole date "2025-03-12"
    PeriodBoard dailyBoard = new PeriodBoard(10);

    LastDaysBoard(int numberOfDays) {
        this.numberOfDays = numberOfDays;
    }

    public void onRating(String agentName, int rating, String date) {
        dailyBoard.onRating(agentName, rating, date);
    }

    /** Adds up each agent's daily totals, from today back to (numberOfDays - 1) days ago */
    Collection<AgentStats> getStats(String today) {
        Map<String, AgentStats> windowStats = new HashMap<>();
        LocalDate day = LocalDate.parse(today);
        for (int i = 0; i < numberOfDays; i++) {
            for (AgentStats dayStats : dailyBoard.getStats(day.toString())) {
                windowStats.computeIfAbsent(dayStats.agentName, name -> new AgentStats(name))
                        .addStats(dayStats);
            }
            day = day.minusDays(1); // LocalDate handles month and year changes
        }
        return windowStats.values();
    }
}

/**
 * Running totals of one agent's ratings.
 * We never keep individual ratings, only their sum and count.
 */
class AgentStats {
    String agentName;
    long ratingSum = 0;
    long ratingCount = 0;

    AgentStats(String agentName) {
        this.agentName = agentName;
    }

    void addRating(int rating) {
        ratingSum += rating;
        ratingCount++;
    }

    /** New: adds the totals of the same agent from another day, used by LastDaysBoard */
    void addStats(AgentStats other) {
        ratingSum += other.ratingSum;
        ratingCount += other.ratingCount;
    }

    /**
     * Average x 10, rounded half up, using whole numbers only.
     * Example: sum = 13, count = 3 gives (130 + 1) / 3 = 43, which means 4.3
     */
    long getAverageInTenths() {
        return (ratingSum * 10 + ratingCount / 2) / ratingCount;
    }

    /** Average as text with exactly one decimal, like "4.3" or "5.0" */
    String getAverageText() {
        long tenths = getAverageInTenths();
        return (tenths / 10) + "." + (tenths % 10);
    }
}

Complexity

Here B is the number of boards, Y is the number of agents rated in the asked year, and W is the number of agents rated in the 7 day window.

OperationTime
rateAgentO(B), and B is a small constant
getBestAgentsByYearO(Y log Y)
getBestAgentsInLast7DaysO(7W + W log W)

The other two queries cost the same as before.

Daily totals keep growing over time. If today only moves forward, days older than the window can be deleted to save memory.


Thanks for reading. Best of Luck For Your Interview Prep.


r/LowLevelDesign • • Oct 02 '26

Microsoft LLD: Design Notification System

60 Upvotes

This is one of the most common questions asked in Microsoft low level design rounds. Ofcourse LRU cache, LFU cache are undisputedly the most asked ones. I have started with a brute force solution and then moved on to solving it using observer design pattern. This tutorial is in Java.

Here is the Python version: https://github.com/prsnt558908/CodeZymSolutions/blob/main/101-300/133-design-notification-system/q-133-python-tutorial.md

You can practice this and other Microsoft LLD questions on CodeZym.


Problem Statement

Build a notification system that supports multiple channels such as EMAIL, SMS and PUSH. Users register, then subscribe to event types on one or more supported channels. When a notification is sent for an event type, it is delivered exactly once to every subscribed (userId, channel) pair.

Operations

  • NotificationSystem(supportedChannels): set up the system with its allowed channels. Duplicate channel names count as one.
  • registerUser(userId): add a user. Registering an existing user does nothing.
  • subscribe(userId, eventType, channel): add a subscription if the user exists and the channel is supported. Duplicate subscriptions are ignored.
  • unsubscribe(userId, eventType, channel): remove an existing subscription.
  • sendNotification(notificationId, eventType, content): deliver the notification to all subscribers. Returns the deliveries sorted by userId, then by channel.
  • getUserInbox(userId): return the user's deliveries in the order they arrived.

High level solution approach

A notification system is a classic publish and subscribe setup. Users sign up for an event type (like ORDER_PLACED) on one or more channels. When a notification is sent for that event, every subscriber gets one copy in their inbox for each channel they picked.

This is exactly what the Observer pattern is made for. Each event type is a subject that keeps track of its listeners. Each (user, channel) pair is an observer that receives a delivery when the event fires. Observer alone is the best fit here. We don't need to combine it with other patterns because every channel behaves the same way.

The two tricky rules are "no duplicate deliveries" and "results sorted by userId, then by channel". A sorted set of subscribers for each event type handles both at once. A set ignores duplicates, and a sorted set keeps everyone in order, so sending a notification is just a simple loop.

We will start with a simple brute force version, see where it is slow, and then improve it step by step.


Solution 1: Brute Force (One Big List)

Store every subscription as a {userId, eventType, channel} entry in one list. Store a map of userId -> inbox. If a user has an inbox, the user is registered.

  • subscribe: ignore unknown users and unsupported channels. Scan the list and add the entry only if it is not there yet.
  • unsubscribe: scan the list and remove the entry if it is found.
  • sendNotification: scan the whole list and pick the entries of this eventType. Sort them by userId, then by channel. Build each delivery string and add it to that user's inbox.
  • getUserInbox: return a copy of the inbox, or an empty list for an unknown user.

Watch out: sort by the (userId, channel) pair, not by the final delivery string. The | character has a bigger code than letters and digits, so "U10|EMAIL|..." would wrongly come before "U1|EMAIL|...", even though "U1" comes before "U10".

Code

import java.util.*;

public class NotificationSystem {

    Set<String> supportedChannels = new HashSet<>();

    // userId -> inbox. A user is registered only if it has an inbox.
    Map<String, List<String>> inboxes = new HashMap<>();

    // every subscription, stored as {userId, eventType, channel}
    List<String[]> subscriptions = new ArrayList<>();

    public NotificationSystem(List<String> supportedChannels) {
        this.supportedChannels.addAll(supportedChannels);
    }

    public void registerUser(String userId) {
        inboxes.putIfAbsent(userId, new ArrayList<>());
    }

    public void subscribe(String userId, String eventType, String channel) {
        if (!inboxes.containsKey(userId) || !supportedChannels.contains(channel)) {
            return;
        }
        if (indexOf(userId, eventType, channel) == -1) {
            subscriptions.add(new String[]{userId, eventType, channel});
        }
    }

    public void unsubscribe(String userId, String eventType, String channel) {
        int index = indexOf(userId, eventType, channel);
        if (index != -1) {
            subscriptions.remove(index);
        }
    }

    public List<String> sendNotification(String notificationId, String eventType, String content) {
        // 1. pick the subscriptions of this event
        List<String[]> matching = new ArrayList<>();
        for (String[] sub : subscriptions) {
            if (sub[1].equals(eventType)) {
                matching.add(sub);
            }
        }

        // 2. sort by userId (index 0), then by channel (index 2)
        matching.sort((a, b) -> {
            int byUser = a[0].compareTo(b[0]);
            return byUser != 0 ? byUser : a[2].compareTo(b[2]);
        });

        // 3. build each delivery and drop it in the user's inbox
        List<String> deliveries = new ArrayList<>();
        for (String[] sub : matching) {
            String delivery = sub[0] + "|" + sub[2] + "|" + notificationId + "|" + eventType + "|" + content;
            inboxes.get(sub[0]).add(delivery);
            deliveries.add(delivery);
        }
        return deliveries;
    }

    public List<String> getUserInbox(String userId) {
        return new ArrayList<>(inboxes.getOrDefault(userId, new ArrayList<>()));
    }

    /** Linear search over all subscriptions. Returns -1 when not found. */
    int indexOf(String userId, String eventType, String channel) {
        for (int i = 0; i < subscriptions.size(); i++) {
            String[] sub = subscriptions.get(i);
            if (sub[0].equals(userId) && sub[1].equals(eventType) && sub[2].equals(channel)) {
                return i;
            }
        }
        return -1;
    }
}

Problems with this approach

  • subscribe and unsubscribe scan all subscriptions, even the ones for other events.
  • sendNotification scans everything too, and then sorts again on every call, even when nothing changed since the last send.
  • One class does everything, so it is hard to see who is listening to which event.

It works for small inputs, but we can do better.


Solution 2: Observer Pattern with Sorted Subscribers

Fixing the problems one by one

Problem in Solution 1Fix
Scanning the subscriptions of other eventsGroup subscribers by event type in a Map<String, EventTopic>
Scanning to find a duplicate or to unsubscribeKeep each event's subscribers in a set
Sorting again on every sendUse a sorted set (TreeSet), so the order is always ready

After these fixes, every event type becomes a small object that owns its subscribers. That object is the subject of the Observer pattern.

Why the Observer pattern?

The problem describes Observer almost word for word: listeners attach to an event, detach from it, and every current listener is notified when the event fires.

  • EventTopic is the subject. It has attach, detach and publish (notify everyone).
  • Subscriber is the observer. Its deliver method builds the delivery string and puts it in the user's inbox.
  • NotificationSystem is the front door. It checks the input and hands the call to the right topic.

In Solution 1 one class did all of this. Now each class has one small job, so the code is easier to read and change.

We skip a separate Observer interface because there is only one kind of subscriber. If another kind shows up later, Subscriber can easily become an interface.

A pattern that looks useful but doesn't fit

Strategy (with a Factory). It is tempting to write EmailChannel, SmsChannel and PushChannel classes and a factory to create them. But here every channel does exactly the same thing: build a string and save it in an inbox.

Channel names are also any strings given at runtime, so one class per channel is not even possible. A Set<String> of channel names is all we need.

Important classes and data structures

  • User: userId plus an ArrayList inbox. A list keeps deliveries in the exact order they arrived.
  • Subscriber: one (user, channel) pair. It holds a reference to its User, so it can drop a delivery straight into the inbox. Its compareTo orders by userId, then by channel.
  • EventTopic: one event type plus a TreeSet<Subscriber>. TreeSet uses compareTo for two jobs at once:
    • it keeps subscribers sorted by (userId, channel).
    • it treats two subscribers with the same user and channel as one item, so a duplicate subscription is simply ignored.
  • NotificationSystem:
    • Set<String> supportedChannels: a fast "is this channel allowed?" check. Duplicate names in the input collapse into one.
    • Map<String, User> users: who is registered.
    • Map<String, EventTopic> topics: jump straight to the subscribers of one event without touching other events.

How each method works

  • registerUser: add a new User only if the id is new.
  • subscribe: do nothing for an unknown user or an unsupported channel. Otherwise create the event's topic if needed and attach a new Subscriber. The TreeSet ignores a duplicate.
  • unsubscribe: do nothing for an unknown user or an event nobody subscribed to. Otherwise detach the subscriber. Removing something that is not there does nothing.
  • sendNotification: no topic means no subscribers, so return an empty list. Otherwise walk the already sorted subscribers and let each one deliver.
  • getUserInbox: return a copy of the user's inbox, or an empty list for an unknown user.

Code

import java.util.*;

/**
 * A registered user.
 * The inbox keeps every delivery in the exact order it arrived.
 */
class User {
    String userId;
    List<String> inbox = new ArrayList<>();

    User(String userId) {
        this.userId = userId;
    }
}

/**
 * Observer: one (user, channel) pair listening to an event type.
 */
class Subscriber implements Comparable<Subscriber> {
    User user;
    String channel;

    Subscriber(User user, String channel) {
        this.user = user;
        this.channel = channel;
    }

    /** Called when the event fires. Builds the delivery and drops it in the user's inbox. */
    String deliver(String notificationId, String eventType, String content) {
        String delivery = user.userId + "|" + channel + "|" + notificationId + "|" + eventType + "|" + content;
        user.inbox.add(delivery);
        return delivery;
    }

    /**
     * Order by userId, then by channel.
     * TreeSet also uses this to spot duplicates: same user and same channel means same subscriber.
     */
    @Override
    public int compareTo(Subscriber other) {
        int byUser = user.userId.compareTo(other.user.userId);
        if (byUser != 0) {
            return byUser;
        }
        return channel.compareTo(other.channel);
    }
}

/**
 * Subject: one event type and everyone subscribed to it.
 * The TreeSet keeps subscribers unique and always sorted by (userId, channel).
 */
class EventTopic {
    String eventType;
    TreeSet<Subscriber> subscribers = new TreeSet<>();

    EventTopic(String eventType) {
        this.eventType = eventType;
    }

    void attach(Subscriber subscriber) {
        subscribers.add(subscriber);      // a duplicate is ignored
    }

    void detach(Subscriber subscriber) {
        subscribers.remove(subscriber);   // a missing subscriber is ignored
    }

    /** Notifies every subscriber in sorted order and returns their deliveries. */
    List<String> publish(String notificationId, String content) {
        List<String> deliveries = new ArrayList<>();
        for (Subscriber subscriber : subscribers) {
            deliveries.add(subscriber.deliver(notificationId, eventType, content));
        }
        return deliveries;
    }
}

/**
 * Entry point. Checks every call and passes it to the right EventTopic.
 */
public class NotificationSystem {

    Set<String> supportedChannels = new HashSet<>();   // duplicate names collapse into one
    Map<String, User> users = new HashMap<>();          // userId -> User
    Map<String, EventTopic> topics = new HashMap<>();   // eventType -> EventTopic

    public NotificationSystem(List<String> supportedChannels) {
        this.supportedChannels.addAll(supportedChannels);
    }

    public void registerUser(String userId) {
        users.putIfAbsent(userId, new User(userId));
    }

    public void subscribe(String userId, String eventType, String channel) {
        User user = users.get(userId);
        if (user == null || !supportedChannels.contains(channel)) {
            return;
        }
        // create the topic the first time anyone subscribes to this event
        EventTopic topic = topics.computeIfAbsent(eventType, key -> new EventTopic(key));
        topic.attach(new Subscriber(user, channel));
    }

    public void unsubscribe(String userId, String eventType, String channel) {
        User user = users.get(userId);
        EventTopic topic = topics.get(eventType);
        if (user == null || topic == null) {
            return;
        }
        topic.detach(new Subscriber(user, channel));
    }

    public List<String> sendNotification(String notificationId, String eventType, String content) {
        EventTopic topic = topics.get(eventType);
        if (topic == null) {
            return new ArrayList<>();
        }
        return topic.publish(notificationId, content);
    }

    public List<String> getUserInbox(String userId) {
        User user = users.get(userId);
        if (user == null) {
            return new ArrayList<>();
        }
        return new ArrayList<>(user.inbox);   // a copy, so callers can't change the real inbox
    }
}

Complexity

S = total subscriptions, k = subscribers of the given event, m = number of deliveries in the user's inbox.

MethodSolution 1Solution 2
registerUserO(1)O(1)
subscribeO(S)O(log k)
unsubscribeO(S)O(log k)
sendNotificationO(S + k log k)O(k)
getUserInboxO(m)O(m)

Building the delivery strings takes extra time based on their length, and that cost is the same in both solutions.


Thanks for reading. Best of Luck For Your Interview Prep.


r/LowLevelDesign • • Oct 01 '26

DoorDash CodeCraft Round: Design Dasher Payout Service

20 Upvotes

This is one of the most common questions from DoorDash CodeCraft round. Doordash has a pretty small question bank anyway.

I have started with a high level overview then explained a simple solution and then improved it. At the end I have discussed the most common follow-up questions that were asked with this question during interview rounds.

I have used Java code with this editorial. Here is the Python version:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/1-100/97-design-dasher-payout-service/q-97-python-tutorial.md

This is 97. Codecraft: Design Dasher Payout Service on CodeZym.


Problem Statement

Design a Dasher payout service that calculates how much a Dasher earns in a day. Every order pays basePayRate cents per minute from its START time to its END time, both minutes included. When orders overlap, each minute pays ongoingDeliveries * basePayRate. A Dasher also earns bonusPay cents for every deliveryCountsToGetBonus completed deliveries. Delivery records look like orderId=O1,action=START,time=09:00 and can arrive in any order, across multiple calls.

  • addOrUpdatePayoutMetadata(dasherId, basePayRate, bonusPay, deliveryCountsToGetBonus): sets a Dasher's pay rates.
  • addDeliveryActivity(dasherId, deliveryActivities): adds START and END records for a Dasher.
  • payout(dasherId): returns the Dasher's total payout in cents.

Solution approach

A dasher earns basePayRate cents for every minute they spend on an order. When orders overlap, each minute pays ongoingDeliveries * basePayRate. It sounds like we must find all the overlaps, but we don't. Paying 2 * basePayRate for a minute where 2 orders overlap is the same as paying each of those 2 orders basePayRate. So every order simply pays for its own minutes, end - start + 1, and the overlap rule takes care of itself. We start with a simple brute force, improve it step by step, and discuss common follow-up questions at the end.

For each dasher we keep just two running numbers: total delivery minutes and completed deliveries. A small map holds half-finished orders until their other record arrives, because START and END can come in any order and even in different calls. Payout then becomes one line of math.

No design pattern is needed here. Every dasher is paid with the same formula, only the numbers (rate and bonus) change. So a few plain classes and hash maps give the simplest and fastest design.

Interview Focus

The emphasis in this question is on API design and clean code. The interviewer is looking more for brainstorming and requirement gathering than for an end-to-end working solution.

So spend the first few minutes asking questions. Here are good ones, with the answers this problem gives:

  • Are both the start minute and the end minute paid? Yes, an order pays for end - start + 1 minutes.
  • Can START and END arrive out of order, or in different calls? Yes.
  • Which orders count toward the bonus? Only the ones with both START and END.
  • What if start > end? The order pays for 0 minutes.
  • Is payout for a single day? Yes. In a real service, payout() would also take a date.

For the API, money stays an int in cents, so there are no decimal rounding errors. For clean code, each class has one job: DasherPayoutService reads the input, Dasher keeps one dasher's pay data, and Order holds one order's times.

The most common follow-up questions, and how to answer them, are discussed at the end.

Do We Need a Design Pattern?

Two patterns look useful at first, but here they only add extra classes.

Strategy pattern for pay rules: Strategy helps when the way we calculate pay changes, for example one dasher paid per minute and another paid per order. Here every dasher uses the same formula. Only the numbers differ (rate, bonus amount, bonus target), and numbers are just data that we store in a Dasher object. Even the follow-ups at the end, country rates and peak hour pay, stay as plain data.

State pattern for an order: An order moves from "waiting" to "complete". But START and END can arrive in any order, so the only question is: do we have both times yet? Two fields, start and end, answer that. Separate state classes would be a lot of code for a two-field check.

Solution 1: Brute Force (Count Every Minute)

The most direct way is to follow the payment rule word by word. For every minute of the day, count the ongoing deliveries and pay ongoingDeliveries * basePayRate for that minute.

Storing the data

  • Map<String, Dasher> dashers: finds a dasher by id in O(1). Order ids like O1 can repeat for different dashers, so each dasher keeps its own orders.
  • Dasher: keeps one dasher's pay settings and its orders map (orderId -> Order) together, instead of spreading them over many maps.
  • Order: holds start and end as minutes of the day, so 09:00 becomes 540. We use -1 for "not received yet", because 0 is a valid time (00:00).

START and END of an order may arrive in any order, even in different calls. So we just fill in whichever half arrives and calculate nothing until payout() is called.

Calculating payout

  1. Create ongoing[1440], one slot for every minute of the day.
  2. For every order that has both START and END, count it as a completed delivery and add 1 to every minute from start to end. If start > end, the loop never runs, so the order adds 0 minutes.
  3. Base pay is the sum of ongoing[minute] * basePayRate over all minutes.
  4. Bonus is (completedDeliveries / deliveryCountsToGetBonus) * bonusPay. Integer division gives the number of full bonus groups.
import java.util.*;

/**
 * One order of a dasher.
 * Times are minutes of the day (09:00 -> 540).
 * -1 means "not received yet", because 0 is a valid time (00:00).
 */
class Order {
    int start = -1;
    int end = -1;

    boolean isComplete() {
        return start != -1 && end != -1;
    }
}

/**
 * Pay settings and all orders of one dasher.
 */
class Dasher {
    int basePayRate;              // cents per minute for each ongoing delivery
    int bonusPay;                 // cents for every group of completed deliveries
    int deliveryCountsToGetBonus; // deliveries needed for one bonus
    Map<String, Order> orders = new HashMap<>(); // orderId -> order

    void addRecord(String orderId, boolean isStart, int time) {
        Order order = orders.get(orderId);
        if (order == null) {
            order = new Order();
            orders.put(orderId, order);
        }
        if (isStart) {
            order.start = time;
        } else {
            order.end = time;
        }
    }

    int calculatePayout() {
        int[] ongoing = new int[24 * 60]; // ongoing[m] = deliveries running at minute m
        int completedDeliveries = 0;

        for (Order order : orders.values()) {
            if (!order.isComplete()) continue;
            completedDeliveries++;
            // when start > end this loop never runs, so the order adds 0 minutes
            for (int minute = order.start; minute <= order.end; minute++) {
                ongoing[minute]++;
            }
        }

        // payment rule: every minute pays ongoingDeliveries * basePayRate
        int basePay = 0;
        for (int minute = 0; minute < ongoing.length; minute++) {
            basePay += ongoing[minute] * basePayRate;
        }

        int bonus = 0;
        if (deliveryCountsToGetBonus > 0) { // avoids division by zero if metadata was never set
            bonus = (completedDeliveries / deliveryCountsToGetBonus) * bonusPay;
        }
        return basePay + bonus;
    }
}

public class DasherPayoutService {
    Map<String, Dasher> dashers = new HashMap<>(); // dasherId -> dasher

    public DasherPayoutService() {
    }

    public void addOrUpdatePayoutMetadata(String dasherId, int basePayRate, int bonusPay, int deliveryCountsToGetBonus) {
        Dasher dasher = getOrCreateDasher(dasherId);
        dasher.basePayRate = basePayRate;
        dasher.bonusPay = bonusPay;
        dasher.deliveryCountsToGetBonus = deliveryCountsToGetBonus;
    }

    public void addDeliveryActivity(String dasherId, List<String> deliveryActivities) {
        Dasher dasher = getOrCreateDasher(dasherId);
        for (String activity : deliveryActivities) {
            // "orderId=O1,action=START,time=09:00" -> ["orderId=O1", "action=START", "time=09:00"]
            String[] parts = activity.split(",");
            String orderId = readValue(parts[0]);
            boolean isStart = readValue(parts[1]).equals("START");
            int time = toMinutes(readValue(parts[2]));
            dasher.addRecord(orderId, isStart, time);
        }
    }

    public int payout(String dasherId) {
        Dasher dasher = dashers.get(dasherId);
        if (dasher == null) return 0;
        return dasher.calculatePayout();
    }

    Dasher getOrCreateDasher(String dasherId) {
        Dasher dasher = dashers.get(dasherId);
        if (dasher == null) {
            dasher = new Dasher();
            dashers.put(dasherId, dasher);
        }
        return dasher;
    }

    // "time=09:00" -> "09:00"
    String readValue(String keyValue) {
        return keyValue.substring(keyValue.indexOf('=') + 1).trim();
    }

    // "09:00" -> 540 (minutes since midnight)
    int toMinutes(String hhmm) {
        String[] hourAndMinute = hhmm.split(":");
        return Integer.parseInt(hourAndMinute[0]) * 60 + Integer.parseInt(hourAndMinute[1]);
    }
}

What's wrong with it?

  • Every payout call walks through every minute of every order. One order can cover up to 1440 minutes, so many long orders make payout slow.
  • Every payout call starts again from scratch, even if nothing changed.
  • All orders stay in memory forever.

Key Observation: Every Order Pays for Its Own Minutes

Let's draw Example 2. Each = or digit is one minute. The last row shows how many orders are ongoing in that minute.

time      09:00     09:10     09:20     09:30
O10       =====================
O11                 =====================
ongoing   1111111111222222222221111111111
  • Minute by minute: the last row adds up to 10*1 + 11*2 + 10*1 = 42.
  • Order by order: O10 covers 21 minutes (09:00 to 09:20) and O11 covers 21 minutes (09:10 to 09:30), so 21 + 21 = 42.

Same number, so pay is 42 * 30 = 1260 either way.

Think of every order as having its own meter. During an overlap two meters run together, and that is exactly why the pay doubles. So we never have to find overlaps. We don't need the minute array, or even a sweep line that sorts all START and END events. We just add up each order's own minutes.

Solution 2: Optimal (Running Totals)

We improve Solution 1 in two parts.

  1. Better math: base pay is totalMinutes * basePayRate, where totalMinutes is the sum of end - start + 1 over all completed orders. No minute array.
  2. Better data structure: once an order has both START and END, its minutes never change. So we add them to the running totals right away and delete the order. Payout no longer loops over anything.

Why these data structures?

  • Map<String, Order> pendingOrders: START and END can arrive in any order and in different calls. The first half waits here until its partner arrives. Only unfinished orders stay in memory.
  • totalMinutes and completedDeliveries: two plain counters are all that payout needs.

We store minutes and counts, not cents. So if addOrUpdatePayoutMetadata() changes the rates later, payout still uses the latest rates.

Walkthrough of Example 3

Records arrive unordered and in two calls. basePayRate = 25, bonusPay = 150, deliveryCountsToGetBonus = 2.

RecordWhat happenstotalMinutescompletedDeliveries
O20 END 10:05O20 waits in pendingOrders00
O21 START 10:08O21 waits in pendingOrders00
O20 START 10:00O20 complete: 10:00 to 10:05 = 6 minutes61
O21 END 10:10O21 complete: 10:08 to 10:10 = 3 minutes92

Payout = 9 * 25 + (2 / 2) * 150 = 225 + 150 = 375 cents.

Edge cases

  • start > end: the order adds 0 minutes. It still has both records, which is how the problem defines a delivered order, so it counts toward the bonus.
  • Only START or only END received: the order waits in pendingOrders and adds nothing.
  • 00:00 is minute 0, which is why -1 marks a missing time.
  • No records at all: payout is 0.
import java.util.*;

/**
 * An order that is still waiting for its START or END record.
 * Times are minutes of the day (09:00 -> 540).
 * -1 means "not received yet", because 0 is a valid time (00:00).
 */
class Order {
    int start = -1;
    int end = -1;

    boolean isComplete() {
        return start != -1 && end != -1;
    }

    // [start, end] includes both minutes. If start > end the order pays nothing.
    int minutes() {
        if (start > end) return 0;
        return end - start + 1;
    }
}

/**
 * Pay settings and running totals of one dasher.
 */
class Dasher {
    int basePayRate;              // cents per minute for each ongoing delivery
    int bonusPay;                 // cents for every group of completed deliveries
    int deliveryCountsToGetBonus; // deliveries needed for one bonus

    Map<String, Order> pendingOrders = new HashMap<>(); // orderId -> order still missing START or END
    int totalMinutes = 0;         // minutes of all completed orders
    int completedDeliveries = 0;  // orders that have both START and END

    void addRecord(String orderId, boolean isStart, int time) {
        Order order = pendingOrders.get(orderId);
        if (order == null) {
            order = new Order();
            pendingOrders.put(orderId, order);
        }
        if (isStart) {
            order.start = time;
        } else {
            order.end = time;
        }

        // Both halves are here, so its minutes can't change anymore.
        // Add them to the totals and forget the order.
        if (order.isComplete()) {
            totalMinutes += order.minutes();
            completedDeliveries++;
            pendingOrders.remove(orderId);
        }
    }

    int calculatePayout() {
        // overlapping orders each pay for their own minutes,
        // so this already includes the multi-order pay
        int basePay = totalMinutes * basePayRate;

        int bonus = 0;
        if (deliveryCountsToGetBonus > 0) { // avoids division by zero if metadata was never set
            bonus = (completedDeliveries / deliveryCountsToGetBonus) * bonusPay;
        }
        return basePay + bonus;
    }
}

public class DasherPayoutService {
    Map<String, Dasher> dashers = new HashMap<>(); // dasherId -> dasher

    public DasherPayoutService() {
    }

    public void addOrUpdatePayoutMetadata(String dasherId, int basePayRate, int bonusPay, int deliveryCountsToGetBonus) {
        Dasher dasher = getOrCreateDasher(dasherId);
        dasher.basePayRate = basePayRate;
        dasher.bonusPay = bonusPay;
        dasher.deliveryCountsToGetBonus = deliveryCountsToGetBonus;
    }

    public void addDeliveryActivity(String dasherId, List<String> deliveryActivities) {
        Dasher dasher = getOrCreateDasher(dasherId);
        for (String activity : deliveryActivities) {
            // "orderId=O1,action=START,time=09:00" -> ["orderId=O1", "action=START", "time=09:00"]
            String[] parts = activity.split(",");
            String orderId = readValue(parts[0]);
            boolean isStart = readValue(parts[1]).equals("START");
            int time = toMinutes(readValue(parts[2]));
            dasher.addRecord(orderId, isStart, time);
        }
    }

    public int payout(String dasherId) {
        Dasher dasher = dashers.get(dasherId);
        if (dasher == null) return 0;
        return dasher.calculatePayout();
    }

    Dasher getOrCreateDasher(String dasherId) {
        Dasher dasher = dashers.get(dasherId);
        if (dasher == null) {
            dasher = new Dasher();
            dashers.put(dasherId, dasher);
        }
        return dasher;
    }

    // "time=09:00" -> "09:00"
    String readValue(String keyValue) {
        return keyValue.substring(keyValue.indexOf('=') + 1).trim();
    }

    // "09:00" -> 540 (minutes since midnight)
    int toMinutes(String hhmm) {
        String[] hourAndMinute = hhmm.split(":");
        return Integer.parseInt(hourAndMinute[0]) * 60 + Integer.parseInt(hourAndMinute[1]);
    }
}

Complexity

VersionaddDeliveryActivitypayoutMemory
Solution 1O(k)O(n × 1440) worst caseall orders
Solution 2O(k)O(1)only unfinished orders

k is the number of records in one call and n is the number of orders of the dasher.

Follow-up Questions

Each one needs only a small change to Solution 2.

1. Different base pay rates across countries

  • Rates are just data. Keep a Map<String, PayConfig> from country code to that country's default base rate, bonus and currency, and store a countryCode in each Dasher.
  • At payout, use the dasher's own rate if one was set, else the country default. Keep amounts in the local currency's smallest unit (cents, paise), so currencies never mix.
  • Only if a country needs a different formula, not just different numbers, add a Strategy per country.

2. Double pay during peak hours

  • Keep the peak windows, for example 12:00 to 13:59, as a list of [start, end] minute pairs.
  • When an order completes, count its minutes inside each window: min(end, peakEnd) - max(start, peakStart) + 1, or 0 when that is negative. Add them to a second counter, peakMinutes.
  • Base pay becomes (totalMinutes + peakMinutes) * basePayRate, because every peak minute is paid one extra time. Overlapping orders still work, since each order counts its own peak minutes.

3. What if the upstream Delivery API fails?

In an actual interview, the records may come from an upstream Delivery API instead of addDeliveryActivity().

  • Wrap the call in a small DeliveryClient class with a timeout and a few retries with growing wait times (exponential backoff), so retry logic stays out of the payout code.
  • If it still fails, never return a guessed or partial amount. Mark the payout as pending (or return an error) and retry it later from a queue, because paying late is better than paying wrong.
  • Retries can send the same records twice. Keep a Set of completed order ids and skip repeats, so no order is paid twice.

Thanks for reading. Wish you the best of luck with your interview prep.


r/LowLevelDesign • • Sep 29 '26

Amazon LLD: Pizza Pricing System

29 Upvotes

This is one of the four most common Amazon Low Level Design Interview Questions. LRU Cache, Parking Lot and Unix 'find' command for file search are the other three.

I have started with a simple solution and then moved on to one which uses strategy design pattern. This is the java version.

Python Version:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/1-100/19-design-pizza-pricing-system-followup/q-19-python-tutorial.md

You can practice this question on CodeZym.


Problem Statement

Design a pizza pricing system. A pizza has a base price, a tax percentage and a size (small, medium or large). You can add toppings to it and get its final price.

Implement the PizzaPricing class:

  • PizzaPricing(int basePrice, int taxPercentage, String size): creates a new pizza.
  • boolean addTopping(String topping, int servingsCount): adds servings of a topping. Returns true if all rules pass, otherwise returns false and leaves the pizza unchanged.
  • int getFinalPrice(): returns subtotal plus tax, rounded half up. Subtotal is the base price plus the cost of all toppings, and tax is taxRate percent of the subtotal.

Toppings (price per serving): cheeseburst 100, corn 50, onion 30, capsicum 50, pineapple 60, mushroom 40.

Business rules:

  • cheeseburst: raises the tax rate by 30% of its current value, only once no matter how many servings. At most 1 serving on small and 2 on medium. Cannot be added if mushroom is already on the pizza.
  • pineapple: allowed only on medium and large pizzas.
  • mushroom: lowers the tax rate by 10% of its current value, only once no matter how many servings. Cannot be added if cheeseburst is already on the pizza.
  • corn: on medium, the first serving costs 50 and each additional serving costs 40. On large, every serving costs 20.

The design should make it easy to add more rules later, such as size-based caps, combos and promos.


High Level Idea

A pizza only needs to remember a few things: its base price, tax percentage, size and how many servings of each topping it has. Every business rule in this problem is one of just three kinds: a check before adding a topping, a special price for a topping, or a change to the tax rate.

So we give every topping its own small class that answers these three questions for itself. This is the Strategy pattern. A Simple Factory (a map from topping name to its object) gives us the right topping object for a name. This combination of Strategy + Simple Factory is the best fit here.

The problem statement suggests the Decorator pattern, but we do not need it. Decorators work best when each layer just adds something on top of the layer below. Here most rules need to look at the whole pizza, which decorators make hard. We explain why below.

We will start with a simple one-class solution, see where it gets messy, and then clean it up with Strategy + Simple Factory.

Understanding the Rules

ToppingPrice per servingCan be added only ifSpecial priceTax effect
cheeseburst100no mushroom on the pizza, total servings at most 1 on small and 2 on medium-+30% of current tax
mushroom40no cheeseburst on the pizza--10% of current tax
pineapple60size is medium or large--
corn50-medium: 50 for the first serving, 40 for each next one. large: 20 each-
onion30---
capsicum50---

A few things to keep in mind:

  • A tax effect is applied once per topping type, no matter how many servings are added.
  • Servings add up across calls. On a small pizza, adding 1 cheeseburst works, but adding 1 more later fails because the total becomes 2.
  • Corn works the same way. "First serving" means the first corn serving on the pizza, so on a medium pizza, corn added in a later call costs 40 per serving.
  • A failed addTopping() returns false and changes nothing. An unknown topping name also returns false.

The final price is:

subtotal   = basePrice + cost of all toppings
taxAmount  = subtotal * taxRate / 100
finalPrice = (int) (subtotal + taxAmount + 0.5)     // round half up

Solution 1: Simple Approach (One Class)

The simplest approach puts everything inside PizzaPricing.

Why a map for servings? Almost every rule asks "how many servings of X are on the pizza?". A Map<String, Integer> from topping name to total servings answers that in O(1).

Why build the price only in getFinalPrice()? addTopping() only checks the rules with if-else and updates the servings map. getFinalPrice() then builds the whole price from scratch: topping costs, tax change for cheeseburst or mushroom, and rounding. This keeps adding simple, and corn's tiered price always sees the full corn count.

import java.util.HashMap;
import java.util.Map;

public class PizzaPricing {
    int basePrice;
    int taxPercentage;
    String size;

    // topping name -> price of one serving
    Map<String, Integer> menu = new HashMap<>();

    // topping name -> total servings added to this pizza so far
    Map<String, Integer> servings = new HashMap<>();

    public PizzaPricing(int basePrice, int taxPercentage, String size) {
        this.basePrice = basePrice;
        this.taxPercentage = taxPercentage;
        this.size = size;

        menu.put("cheeseburst", 100);
        menu.put("corn", 50);
        menu.put("onion", 30);
        menu.put("capsicum", 50);
        menu.put("pineapple", 60);
        menu.put("mushroom", 40);
    }

    public boolean addTopping(String topping, int servingsCount) {
        if (!menu.containsKey(topping)) return false;

        // every rule of every topping is checked here
        if (topping.equals("cheeseburst")) {
            if (getServings("mushroom") > 0) return false;
            int total = getServings("cheeseburst") + servingsCount;
            if (size.equals("small") && total > 1) return false;
            if (size.equals("medium") && total > 2) return false;
        }
        if (topping.equals("mushroom") && getServings("cheeseburst") > 0) return false;
        if (topping.equals("pineapple") && size.equals("small")) return false;

        servings.put(topping, getServings(topping) + servingsCount);
        return true;
    }

    public int getFinalPrice() {
        double subtotal = basePrice;
        for (String topping : servings.keySet()) {
            int count = servings.get(topping);
            if (topping.equals("corn") && size.equals("medium")) {
                subtotal += 50 + 40 * (count - 1);
            } else if (topping.equals("corn") && size.equals("large")) {
                subtotal += 20 * count;
            } else {
                subtotal += menu.get(topping) * count;
            }
        }

        double taxRate = taxPercentage;
        if (getServings("cheeseburst") > 0) taxRate = taxRate * 1.3; // +30%
        if (getServings("mushroom") > 0) taxRate = taxRate * 0.9;    // -10%

        double finalPrice = subtotal + subtotal * taxRate / 100;
        return (int) (finalPrice + 0.5);
    }

    int getServings(String topping) {
        return servings.getOrDefault(topping, 0);
    }
}

Problems with this approach

It works, but the rules of all toppings are mixed together in two big methods.

  • Every new rule (a new size cap, a combo, a promo) means editing the same two methods, and one wrong edit can break a rule that was already working.
  • The rules of one topping are spread across both methods, so you have to read everything to understand a single topping.
  • You cannot test one topping's rules on their own.

The problem asks us to make new rules easy to add, so let's pick a design pattern.

Choosing the Right Design Pattern

Why not Decorator?

With Decorator, every addTopping() call wraps the pizza in one more layer, like new Onion(new Cheeseburst(new BasePizza())). Each layer adds its own cost and can change the tax rate.

It sounds natural for "adding toppings", but these rules make it awkward:

  • Rules need to see the whole pizza. "No cheeseburst with mushroom", "max 2 cheeseburst on medium" and "first corn serving costs 50" all need topping counts. A layer only knows the layer it wraps, so it has to ask every layer below it. We end up rebuilding a map of topping counts through the chain anyway.
  • Tax must change only once. A second cheeseburst layer has to search the layers below it to find out whether tax was already raised.
  • The chain keeps growing. Every addTopping() adds a layer, and every price or rule check walks through all of them.

Decorator shines when each layer is independent and just adds something on top. Here the rules depend on what is already on the pizza, so a plain map of servings is much simpler.

Why not Chain of Responsibility?

We could build a chain of rule checkers where any checker can reject a topping. But every rule here is tied to the topping being added, so each checker would first ask "is this my topping?". A map lookup takes us straight to the right rules instead. A chain would also cover only the checks, not the special prices or tax effects.

Why Strategy works best

All toppings answer the same three questions, each in its own way. That is exactly what the Strategy pattern is for.

  • PizzaPricing calls canAdd(), getCost() and applyTax() without knowing which topping it is talking to.
  • Each topping's rules live in one small class, so they are easy to read, change and test.
  • A new topping is one new class plus one line in the factory. PizzaPricing does not change.

Solution 2: Strategy Pattern + Simple Factory

Classes

Topping (the strategy)

The base class of every topping. It stores the price per serving and has three methods with default behavior:

  • canAdd(pizza, newServings): returns true, no restriction.
  • getCost(pizza, totalServings): returns pricePerServing * totalServings.
  • applyTax(taxRate): returns taxRate unchanged.

Onion and capsicum have no special rules, so they are simply new Topping(30) and new Topping(50).

The whole pizza is passed to canAdd() and getCost(), so a topping can look at the size or at other toppings. That is what turns a rule like "no cheeseburst with mushroom" into a single line.

Cheeseburst, Mushroom, Pineapple, Corn

Each one extends Topping and overrides only the rules it needs.

ClassOverridesRule
CheeseburstcanAdd(), applyTax()blocked by mushroom, size caps, +30% tax
MushroomcanAdd(), applyTax()blocked by cheeseburst, -10% tax
PineapplecanAdd()not allowed on small
CorngetCost()tiered price on medium and large

ToppingFactory (simple factory)

Holds a Map<String, Topping> from topping name to its object. getTopping(name) returns the right object, or null if the topping is not on the menu. The whole menu lives in one place, so adding a topping never touches PizzaPricing.

PizzaPricing

Holds the pizza's state: base price, tax percentage, size and the servings map. It has no topping-specific rule inside it.

  • addTopping(): gets the topping from the factory and asks canAdd(). Only if that passes, it updates servings.
  • getFinalPrice(): loops over the toppings on the pizza, adds each getCost() to the subtotal and passes the tax rate through each applyTax(). The loop visits each topping type once, so cheeseburst and mushroom change the tax only once, no matter how many servings there are.

Walkthrough of Example B

new PizzaPricing(350, 8, "medium")

  1. addTopping("mushroom", 1): Mushroom.canAdd() finds no cheeseburst and returns true. servings = {mushroom: 1}.
  2. addTopping("corn", 3): Corn uses the default canAdd(), which returns true. servings = {mushroom: 1, corn: 3}.
  3. addTopping("cheeseburst", 1): Cheeseburst.canAdd() finds mushroom and returns false. Nothing changes.
  4. getFinalPrice(): subtotal = 350 + 40 + (50 + 40 + 40) = 520. Mushroom.applyTax() turns tax 8 into 7.2. Final = 520 + 520 × 7.2 / 100 = 557.44, which rounds to 557.

A small floating point trap

Compute the tax as subtotal * taxRate / 100, not (taxRate / 100) * subtotal.

Dividing first can leave a tiny error. With base price 100, tax 201% and one capsicum, the subtotal is 150 and the exact final price is 451.5, which should round up to 452. Dividing first gives 451.49999999999994, which rounds down to 451. Multiplying first gives exactly 451.5.

Adding new rules later

  • New topping with no special rules: one line in ToppingFactory, like toppings.put("olive", new Topping(45)).
  • New size cap or restriction: override canAdd() in that topping's class.
  • New special price or combo: override getCost(). It gets the whole pizza, so it can check other toppings too. Prices are built only in getFinalPrice(), so a combo works no matter which topping was added first.
  • New tax effect: override applyTax().

Code

import java.util.HashMap;
import java.util.Map;

/**
 * A topping with a fixed price per serving and no special rules.
 * Special toppings extend this class and override only the rules they need.
 */
class Topping {
    int pricePerServing;

    Topping(int pricePerServing) {
        this.pricePerServing = pricePerServing;
    }

    /** Can these new servings be added to the pizza? By default, yes. */
    boolean canAdd(PizzaPricing pizza, int newServings) {
        return true;
    }

    /** Cost of all servings of this topping. By default, each costs the same. */
    double getCost(PizzaPricing pizza, int totalServings) {
        return pricePerServing * totalServings;
    }

    /** Tax rate after this topping's effect. By default, tax does not change. */
    double applyTax(double taxRate) {
        return taxRate;
    }
}

class Cheeseburst extends Topping {
    Cheeseburst() {
        super(100);
    }

    @Override
    boolean canAdd(PizzaPricing pizza, int newServings) {
        if (pizza.getServings("mushroom") > 0) return false;

        int total = pizza.getServings("cheeseburst") + newServings;
        if (pizza.getSize().equals("small")) return total <= 1;
        if (pizza.getSize().equals("medium")) return total <= 2;
        return true; // no cap on large
    }

    @Override
    double applyTax(double taxRate) {
        return taxRate * 1.3; // +30% of current tax
    }
}

class Mushroom extends Topping {
    Mushroom() {
        super(40);
    }

    @Override
    boolean canAdd(PizzaPricing pizza, int newServings) {
        return pizza.getServings("cheeseburst") == 0;
    }

    @Override
    double applyTax(double taxRate) {
        return taxRate * 0.9; // -10% of current tax
    }
}

class Pineapple extends Topping {
    Pineapple() {
        super(60);
    }

    @Override
    boolean canAdd(PizzaPricing pizza, int newServings) {
        return !pizza.getSize().equals("small");
    }
}

class Corn extends Topping {
    Corn() {
        super(50);
    }

    @Override
    double getCost(PizzaPricing pizza, int totalServings) {
        if (pizza.getSize().equals("medium")) return 50 + 40 * (totalServings - 1);
        if (pizza.getSize().equals("large")) return 20 * totalServings;
        return super.getCost(pizza, totalServings); // small: normal price
    }
}

/**
 * Simple factory: gives back the topping object for a name.
 * The whole menu lives here, so a new topping is one new line.
 */
class ToppingFactory {
    Map<String, Topping> toppings = new HashMap<>();

    ToppingFactory() {
        toppings.put("cheeseburst", new Cheeseburst());
        toppings.put("corn", new Corn());
        toppings.put("onion", new Topping(30));
        toppings.put("capsicum", new Topping(50));
        toppings.put("pineapple", new Pineapple());
        toppings.put("mushroom", new Mushroom());
    }

    /** Returns null if the topping is not on the menu. */
    Topping getTopping(String name) {
        return toppings.get(name);
    }
}

/**
 * Stores the pizza's state and lets each topping apply its own rules.
 */
public class PizzaPricing {
    int basePrice;
    int taxPercentage;
    String size;

    // topping name -> total servings added to this pizza so far
    Map<String, Integer> servings = new HashMap<>();

    ToppingFactory toppingFactory = new ToppingFactory();

    public PizzaPricing(int basePrice, int taxPercentage, String size) {
        this.basePrice = basePrice;
        this.taxPercentage = taxPercentage;
        this.size = size;
    }

    public boolean addTopping(String name, int servingsCount) {
        Topping topping = toppingFactory.getTopping(name);
        if (topping == null || !topping.canAdd(this, servingsCount)) return false;

        servings.put(name, getServings(name) + servingsCount);
        return true;
    }

    public int getFinalPrice() {
        double subtotal = basePrice;
        double taxRate = taxPercentage;

        for (String name : servings.keySet()) {
            Topping topping = toppingFactory.getTopping(name);
            subtotal += topping.getCost(this, servings.get(name));
            // runs once per topping type, so extra servings never change tax again
            taxRate = topping.applyTax(taxRate);
        }

        // multiply first, divide last: avoids results like 451.4999 instead of 451.5
        double finalPrice = subtotal + subtotal * taxRate / 100;
        return (int) (finalPrice + 0.5);
    }

    int getServings(String name) {
        return servings.getOrDefault(name, 0);
    }

    String getSize() {
        return size;
    }
}

Complexity

  • addTopping(): O(1), one map lookup and a quick rule check.
  • getFinalPrice(): O(T), where T is the number of different toppings on the pizza (at most 6 here).

r/LowLevelDesign • • Sep 25 '26

Amazon LLD: Design Unix "find" Command for File Search

46 Upvotes

This is one of the most asked questions in Amazon low level design rounds is past few years. In this tutorial I have explained how to approach this problem using strategy design pattern.

If you have an upcoming Amazon LLD round and you have very little preparation time then try to cover at least these 4 questions:

  • LRU cache,
  • Parking Lot Design,
  • Unix find command (this question) and
  • Pizza Pricing System

So this is a very important question. I have discussed the Java version.

You can find the python version here: https://github.com/prsnt558908/CodeZymSolutions/tree/main/1-100/14-design-unix-find-command-file-search/q-14-python-tutorial.md

You can practice all these and other Amazon Questions on CodeZym


Problem Statement

Build an in-memory file lookup tool similar to a Unix "find" command. The system should support two starter Search Criterias and be easy to extend with new Search Criterias later.

Initial Search Criterias

  • Search Criteria 1: Return all files strictly larger than a given size (in MB) under a specified directory (recursive).
  • Search Criteria 2: Return all files with a given file extension (for example, ".xml") under a specified directory (recursive).

A search here is really two separate questions glued together. First, which files sit under this directory. Second, out of those files, which ones do we keep.

Keeping these two questions apart is the whole design. The "which ones do we keep" part is the part that keeps changing, because the problem tells us new search criterias will be added later, so it goes behind the Strategy pattern: one tiny class per criteria, all of them exposing the same single method, picked out of a map by id. The "which files sit under this directory" part never changes, so it just needs the right data structure, and that turns out to be a directory tree instead of a flat list of paths.

Strategy alone is enough here, no combination of patterns is needed. The only helper is a plain Map<Integer, SearchCriteria> that maps a criteria id to its object, which works as a very small registry so that search() never needs to know any criteria class by name.

We will build the flat, obvious version first, look at exactly where it hurts, and then fix both halves.

Understanding the problem

Two operations, and both are short.

  • putFile(path, sizeMb) stores a file, and storing the same path twice replaces the old size.
  • search(criteriaId, dirPath, args) returns every file under dirPath, including files in nested subdirectories, that passes the criteria. Criteria 1 keeps files strictly larger than args MB. Criteria 2 keeps files whose name ends with the extension in args.

One rule is easy to skim past: the result must always come back in ascending lexicographical order with no duplicates. So for the first example in the problem statement, /data/pics/movie.mp4 is returned before /data/pics/photoA.jpg, because m sorts before p.

Solution 1: one flat map and a linear scan

The simplest thing that can possibly work. Keep every file in a single HashMap from full path to size, and when a search comes in, walk the whole map and keep whatever matches.

Why a HashMap<String, Integer> and not a list of file objects. Two reasons, both free. The key is the full path, so put on an existing path overwrites the old size, which is exactly the "add or replace" rule we were asked for. And because keys are unique, duplicates can never appear in the output.

There is one trap worth calling out. It is tempting to test path.startsWith(dirPath), but that is wrong. The string /data2/big.mp4 starts with /data, even though /data2 is a completely different directory. The fix is to compare against the directory plus a trailing slash.

import java.util.*;

public class FileSearch {

    // Absolute file path -> size in MB.
    // Map.put() overwrites an existing key, which is exactly the "add or replace" rule.
    private final Map<String, Integer> files = new HashMap<>();

    public FileSearch() {
    }

    public void putFile(String path, int sizeMb) {
        files.put(path, sizeMb);
    }

    public List<String> search(int ruleId, String dirPath, String args) {
        // "/data" must match "/data/pics/a.jpg" but must NOT match "/data2/a.jpg",
        // so we always compare against the directory plus a trailing slash.
        String prefix = dirPath.endsWith("/") ? dirPath : dirPath + "/";

        // Parse once instead of inside the loop.
        int minSizeMb = ruleId == 1 ? Integer.parseInt(args.trim()) : 0;
        String extension = args.trim();

        List<String> result = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : files.entrySet()) {
            String path = entry.getKey();
            if (!path.startsWith(prefix)) continue;

            if (ruleId == 1 && entry.getValue() > minSizeMb) {
                result.add(path);
            } else if (ruleId == 2 && path.endsWith(extension)) {
                result.add(path);
            }
        }

        Collections.sort(result);   // strict ascending lexicographical order
        return result;
    }
}

What is wrong with it

It passes, and with at most 2000 files it is fast enough. But it has two real problems.

The if-else chain grows forever. Every new criteria means opening search() and adding another branch to a method that already works. Criteria 5 and criteria 6 end up living inside the same method as criteria 1, so a careless edit while adding one criteria can quietly break another. Testing one criteria on its own is also impossible, because there is nothing to test except the whole method.

It ignores the directory structure completely. Asking for files under /media/images/thumbnails still walks all 2000 files, even if that folder holds three of them. We flattened a tree into a bag of strings and then pay for it on every single search.

Solution 2: Strategy for the criterias, a tree for the directories

Fixing the criterias with the Strategy pattern

Strategy says: when one step of an algorithm has several interchangeable versions, pull that step out into its own interface and give each version its own class.

Here the interchangeable step is "does this file qualify". So we define one interface with one method.

private interface SearchCriteria {
    boolean matches(String path, int sizeMb, String args);
}

Each criteria becomes a small class that answers only that question for itself, and knows nothing about directories, traversal or sorting. MinSizeCriteria compares the size. ExtensionCriteria checks the ending of the path. That is the whole class.

Then a Map<Integer, SearchCriteria> holds id to object. search() looks up one object and calls matches on it, so search() contains no criteria specific code at all. Adding a third criteria is a new class plus one line in the constructor, with zero edits to the searching code.

Why Strategy and not something else

Chain of Responsibility is the usual runner up, because it also replaces an if-else chain with objects. But a chain is for when you do not know who should handle a request, so you pass it along until someone accepts it. Here the caller already hands us the exact criteria id, so a chain would walk past handlers that can never apply and would add an ordering between criterias that has no meaning in this problem. It buys nothing and costs a lookup that used to be free.

Visitor also gets suggested whenever a tree is involved. Visitor pays off when you have many different node types and want to add new operations that work across all of them. Here it is the opposite: there is exactly one kind of thing to inspect, a file with a path and a size, and many operations on it. When the types are fixed and the operations keep growing, a one method interface per operation is lighter and far easier to read than a visitor with an accept method threaded through the tree.

Fixing the traversal with a directory tree

Instead of storing "/media/images/aa.jpg" as one long string, store it the way a real file system does. Every directory becomes a node, and each node holds two maps: its child directories by name, and its own files by name.

private static class Directory {
    final Map<String, Directory> subDirs = new HashMap<>();
    final Map<String, Integer> files = new HashMap<>();
}

Two maps, both plain HashMap, nothing exotic. subDirs lets us jump from a directory to a child in one step, so walking down to /media/images costs two lookups no matter how big the store is. files is keyed by name, so writing the same file name twice overwrites it, keeping the "add or replace" behaviour we had before and still guaranteeing no duplicates.

putFile splits the path and walks down, creating any missing directory on the way, then drops the size into the last node.

search splits dirPath, walks down to that node, and does a depth first walk of everything below it. If any step of the walk down finds no such child, the directory does not exist and we return an empty list.

Two nice things fall out of this. The scan now visits only the files under the requested directory instead of every file in the system. And the /data versus /data2 trap disappears on its own, because data and data2 are two different keys under the root, so descending into one can never reach the other.

We still sort the matches at the end. A depth first walk does not come out in lexicographical order, so one Collections.sort on the matches is the honest and simple way to meet that requirement.

import java.util.*;

public class FileSearch {

    /** Every search criteria implements this one method. args is the raw string from search(). */
    private interface SearchCriteria {
        boolean matches(String path, int sizeMb, String args);
    }

    /** Criteria 1: keep files strictly larger than the given size in MB. */
    private static class MinSizeCriteria implements SearchCriteria {
        @Override
        public boolean matches(String path, int sizeMb, String args) {
            return sizeMb > Integer.parseInt(args.trim());
        }
    }

    /** Criteria 2: keep files whose name ends with the given extension. */
    private static class ExtensionCriteria implements SearchCriteria {
        @Override
        public boolean matches(String path, int sizeMb, String args) {
            return path.endsWith(args.trim());
        }
    }

    /** One node of the directory tree: child directories by name and files by name. */
    private static class Directory {
        final Map<String, Directory> subDirs = new HashMap<>();
        final Map<String, Integer> files = new HashMap<>();
    }

    private final Directory root = new Directory();

    /** Criteria id -> the object that knows how to test a file for that criteria. */
    private final Map<Integer, SearchCriteria> criterias = new HashMap<>();

    public FileSearch() {
        criterias.put(1, new MinSizeCriteria());
        criterias.put(2, new ExtensionCriteria());
        // A new criteria later needs one new class and one line here.
    }

    public void putFile(String path, int sizeMb) {
        List<String> parts = split(path);
        if (parts.isEmpty()) return;

        Directory current = root;
        for (int i = 0; i < parts.size() - 1; i++) {
            current = current.subDirs.computeIfAbsent(parts.get(i), name -> new Directory());
        }
        // Same name in the same directory overwrites the old size, so no duplicates appear.
        current.files.put(parts.get(parts.size() - 1), sizeMb);
    }

    public List<String> search(int ruleId, String dirPath, String args) {
        List<String> result = new ArrayList<>();
        SearchCriteria criteria = criterias.get(ruleId);
        if (criteria == null) return result;

        // Walk down to the starting directory. Everything below it is the search space.
        Directory start = root;
        StringBuilder prefix = new StringBuilder();
        for (String part : split(dirPath)) {
            start = start.subDirs.get(part);
            if (start == null) return result;   // directory does not exist
            prefix.append('/').append(part);
        }

        collect(start, prefix.toString(), criteria, args, result);
        Collections.sort(result);               // strict ascending lexicographical order
        return result;
    }

    /** Depth first walk of one sub tree, keeping only files the criteria accepts. */
    private void collect(Directory dir, String prefix, SearchCriteria criteria,
                         String args, List<String> out) {
        for (Map.Entry<String, Integer> file : dir.files.entrySet()) {
            String fullPath = prefix + "/" + file.getKey();
            if (criteria.matches(fullPath, file.getValue(), args)) {
                out.add(fullPath);
            }
        }
        for (Map.Entry<String, Directory> child : dir.subDirs.entrySet()) {
            collect(child.getValue(), prefix + "/" + child.getKey(), criteria, args, out);
        }
    }

    /** "/a/b/c.txt" -> ["a", "b", "c.txt"]. Empty pieces from "/" or "//" are dropped. */
    private List<String> split(String path) {
        List<String> parts = new ArrayList<>();
        for (String piece : path.split("/")) {
            if (!piece.isEmpty()) parts.add(piece);
        }
        return parts;
    }
}

Adding a third criteria

This is the payoff. Say we now want "files whose name contains some text". We write one class and register it, and we do not touch search, collect, putFile or either of the existing criterias.

/** Criteria 3: keep files whose name contains the given text. */
private static class NameContainsCriteria implements SearchCriteria {
    @Override
    public boolean matches(String path, int sizeMb, String args) {
        String name = path.substring(path.lastIndexOf('/') + 1);
        return name.contains(args.trim());
    }
}
criterias.put(3, new NameContainsCriteria());

Complexity

Let d be the number of parts in a path, k the number of files under the requested directory and m the number of matches.

  • putFile is O(d), just a walk down the tree.
  • search is O(k + m log m): visit the sub tree once, then sort the matches. The flat version was O(n + m log m) where n is every file in the system, so the tree only helps more as the store grows and the searched directory stays small.


r/LowLevelDesign • • Sep 18 '26

Amazon Low Level Design Interview Round Questions 2026

24 Upvotes

I am listing the top low level design questions that you will come across during Amazon LLD interview rounds. I have built this list from recent interview experiences of candidates.

Low Level Design is fair game even for SDE-1. Although LLD rounds are much more common for SDE-2 and above positions. Don't skip it. Focus on SOLID principles and writing extensible code. Follow-ups become trivial when your base design is clean.

For LLD rounds, expectation is to write production ready classes with proper syntax on paper.


During first 10-15 minutes Leadership Principles questions are asked like

  • Any situation where you pushed the customer back .
  • Have you made any thing in thinking long term vision and did you sacrified any short term goals for that.
  • Tell me about time when you did something outside your comfort zone or something different than regular work.

LLD question asked in Bar Raiser

Many times low level design questions can also be asked in the bar raiser round.

One person interviewing for SDE 2 position had their first round itself as the bar raiser round. They were asked to design a system that handles audio buffers across different stages at X frames per second

This is unusual since most candidates have the Bar Raiser towards the end, often as a DS & Algo round.

It was an engaging discussion. But the problem was that he kept going deeper into the system design (high level) and, before he realized it, most of the available time was spent discussing the HLD aspects of the problem rather than the LLD implementation.

With only around 5–10 minutes left, the interviewer asked him to code whatever he felt was ideal for the design. He quickly wrote a few classes and functions, but they ran out of time.

He had 2 DSA + 1 HLD (hiring manager) round after that, but eventually he was rejected. LLD round performance was one of the reasons for that.

During LLD rounds you are always running out of time. It is important that you keep your discussion focussed on the problem statement.


Not understanding question context or not able to code the solution

Asking clarifying questions and thinking out loud is the best thing you can do if you donot understand the question or are running out of time.

One person was asked LLD of unix "find" command for file search.

Although this is one of the most common LLD questions asked by Amazon, candidate was not familiar with it.

Also he had very little Unix knowledge. But he remained calm and asked more clarifing questions. Then proceeded to create classes and write the logic while trying to explain his thought process aloud. He felt very skeptical about this round and thought his chances were slim. But eventually he had a positive feedback and ended up receiving the offer.


Answering follow-ups, extending functionality while avoiding too many changes to existing code

Follow up questions are mostly around adding a new functionality without making too many changes to existing code or arranging your classes a bit differently.

For example one person was asked to design a notification system.

One they gave an intial solution then interviewer asked them if a new notification type comes, eg. push notification , how to handle it ? Interviewer also wanted him to avoid change in the existing service class.

More follow up questions were asked:

  • In the Message object, you have type that varies. What if the content also varies ? Eg. For email,the content will be large. For SMS, small.
  • Should you make Message class abstract and have EmailMessage,SMSMessage,WhatsappMessage ? Is that better?
  • A user may want to receive messages via multiple channels .eg. both SMS and email. How will you handle it: two messages or within one message?

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/11-amazon-lld-sep-2026.md



r/LowLevelDesign • • Sep 11 '26

Article: Amazon DS & Algo Round Interview Questions Asked in 2026

11 Upvotes

This list contains recently asked DSA questions in Amazon for SDE, SDET positions. It also includes questions from Bar Raiser rounds.

Amazon hires (and fires) lots of people and this cycle keeps repeating.

Questions do repeat, hence it is better to solve Amazon tagged questions at least 2–3 times, rather than solving a lot of new questions just once.

Doing questions multiple times will help you understand the patterns and when you see a question which is rephrased differently but has same solution, you will be able to do it.

You will be frequently asked leadership principles in behavioral questions. So prepare your stories around them. There can be long period of silences between rounds.

Wait time Between Rounds

Wait time is often the most frustrating part. No updates, no recruiter contact, just uncertainty.

One person (SDE-1) got their OA results just after two days. But when first round was scheduled, their scheduled interviewer didn't join. After this there was 14 days of silence. After round 1 again 20 days of silence.

After round 2, candidate thought he was rejected because he couldn’t solve one of the questions.

35 days passed in complete silence after that. Out of desperation, he reached out to someone at Amazon on LinkedIn, asking if they could help him get an update from his recruiter.

And that very same day, he finally got the update. Infact bar raiser was scheduled and he did very well in it. But 2 days after his interview, he received a rejection email from AUTA.

Surprisingly a few days later his HR called asking for location preferences but didn't confirm the results. However offer arrived two days later.

Hints from Interviewer/Fumbles

Many people fumble or may need some hint from interviewer. And its alright. One person was asked the below:

  • Longest Substring Without Repeating Characters
  • Longest Substring with At Most K Distinct Characters

They did well on the first question but fumbled on the second. However they coded it up correctly in the end.

They didn't receive any update after that and thought they were rejected. But they got the call 4 days later and another round was scheduled which was completely behavioral. They got selected the next day after that.

No Solution

This can lead to rejection. But not always depending on how other rounds went.

One person with 4 years of experience and interviewed for an SDE2 role. In one round they were not able to code the solution, just gave the approach. After the loops they were offered SDE-1. Downleveled but not a complete rejection.


I created this list from people posting their experiences on forums, blogs, etc.

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/10-amazon-dsa-sep-2026.md


r/LowLevelDesign • • Sep 04 '26

Google DS & Algo Interview Questions 2026

48 Upvotes

This is a preparation list for Google software engineer coding rounds. I prepared it using interview experiences shared by people on forums/blogs etc.

Google has one of the toughest DS & Algo rounds in the industry. DSA rounds are there for both frontend and backend roles.


Google's interview codebase is very large, with questions of all difficulty levels from super easy to super hard. One question can be a medium question with a couple of follow-ups for optimizations, or it can be just one hard question. It all depends on which question the interviewer chooses.

There are two common things about candidates who clear Google interviews and whose overall process is smooth.

  1. At least 2 "Strong-Hire" votes and no "No-Hire" in the on-site packet.
  2. Candidates who narrated trade-offs and edge cases, and correctly answered counter questions, got bumped from "Hire" to "Strong Hire" even with small bugs.

Now above points have lots of exceptions. For example one person bombed one coding round badly. But they were given a redo by their recruiter. It was late 2024 and he was working long hours, spending even the weekends on call. Still he was laid off alongside other teammates.

Lay off was a blow to his morale. He didn't tell even his parents, just pretended he was working from home. Avoided video calls during "work hours". Initially he spent the days watching anime. But slowly preparation started and when the Google call came, he has already been rejected by multiple companies.

He thought it was all over after he messed up one DSA round. But he was able to do well in the redo round and finally ended up receiving the offer.


Judging how the interview went

Many a times you may not be able to guess correctly , how well or how bad you did. There are tons of experiences where candidate thought something and the opposite happend. A lot of things can go right or wrong. One person had done 400+ leetcode problems but during interviews, panic setup and they were able to only come up with a brute force solution.

Another person had two back to back coding rounds scheduled at a gap of just 15 minutes. And during the first round they realised that solution they provided is incorrect. They thought that they had bombed this round and should just cancel the next round. But interviewer provided some guidance and they were able to solve slightly easier version of the problem. However other rounds went well and they ended up receiving the offer.


What if you are rejected

Even if you are rejected its not the end of world. Google recruiters will almost certainly reach out to you a year later. Just keep preparing. One person was rejected by google for L4 position in 2024. But they reapplied 6 months later and surprisingly got a response. However their first two coding rounds got lean hire. Still recruiter decided to go through with other rounds which wents well. During hiring committee their prospects were weak because of two lean hires in coding. However another DSA round was scheduled for them in which they did well.

They ended up receiving offer for L5. That's like getting a promotion within one year. Although they were lowballed but still it was a 20% raise from their current salary. So overall not a bad end.


I created this list from people posting their experiences on forums, blogs, etc.

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/09-google-dsa-sep-2026.md


r/LowLevelDesign • • Aug 28 '26

Article: Amazon Internship Interview Round Coding Questions 2026

14 Upvotes

This is a preparation list for Amazon SDE and SDET internship coding rounds, along with an overview of the online assessment and interview process. I prepared it using interview experiences shared by people on forums/blogs etc.

Apart from the online assessment (OA), the internship process usually includes two DS & Algo interviews of around one hour each, together with behavioral questions.

Some candidates think if you are not asked any behavioral questions then it means you did not do well and are already rejected. This is not entirely true, one candidate reported that they were not asked any behavioral questions during interview but still ended up receiving the internship offer 15 days later.

---------------------------------------------------------

Low Level Design questions are generally not asked for internship roles. However one candidate reported an elevator-system LLD question for SDET internship, but those cases appear to be exception rather than the norm.

Online assessment: the OA includes DSA and an AI-assisted coding question.

For the AI-assisted coding round, you choose one repository. Options may include C++, Django, Spring Boot, ReactJS, Node.js, Ruby on Rails, and similar stacks. The interface provides a code editor and an AI assistant for project-related questions. You have 60 minutes to implement the required behavior and pass the test cases, usually around six. The assistant can help you search the project, locate files, and understand the codebase.

------------------------------------------------------

For candidates in India: Amazon HackOn can be an effective route to an internship call. Amazon may contact eligible participants who performed well in the coding round, not only the finalists. Strong performers may receive an AUTA interest form.

Infact one person even reported that their team was eliminated in the very first round of HackOn in May 2025. But in july end he ended up receiving an email stating that he has been shortlisted for an Amazon Online Assessment based on his HackOn performance. Infact he gave his OA got shortlisted for interview, had his interview in september then got waitlisted and finally received SDE intern offer in last week of november.

For the USA and other countries, direct applications through Amazon's jobs portal and employee referrals are the usual routes.

------------------------------------------------------

This list includes coding-round questions reported for both SDE intern and SDET intern interviews.

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/08-amazon-internship-2026.md


r/LowLevelDesign • • Aug 27 '26

In actual Low Level Design (LLD) Interview Rounds, are we expected to write the full code end to end or is it just pseudo code plus discussion

24 Upvotes

Answer: This is one of the most common questions in a candidate's mind. Now with more and more companies taking AI assisted coding rounds you need to have clarity on what is expected.

1. Machine coding LLD round: If this is a machine coding LLD round of 75 to 90 minutes then you will need full working code with a main method that runs the tests. This round is taken by Flipkart, ClearTrip, Phonepe, Meesho and sometimes Uber, RazorPay etc.

Most times this will be the first screening round.

2. AI Assisted Coding/LLD/Debugging Round: Initially Canva and then DoorDash started it but it is becoming more common. Now Microsoft, Amazon OA also have this round. This round is more similar to a low level design round rather than a traditional DS & Algo round.

You will be given a problem statement along with a chunk of code and you will be asked to add one or more new functionalities. You will be given an AI assistant chat just like chatgpt/gemini. You can use the AI assistant to ask questions and understand the project, maybe generate some boilerplate code.

But do not try to generate the whole solution using only the AI assistant. Goal of this round is to see how you code in real life. How well you arrange your classes and keep change to old code small when adding a new functionality. You LLD skills and knowledge of design patterns like factory, strategy, observer etc come in handy.

As you can guess, for this round also end to end fully working code is expected.

3. Face to Face LLD round: This is a 45-60 minute round and is the most common LLD interview format. It is taken by Amazon, Uber, Microsoft, Walmart and basically every company that takes a LLD round. Here the discussion will happen on pen and paper or a plain text editor, google docs etc.

It has 4 steps:

  1. Requirements gathering : list down functionalities
  2. Class diagram: break functionalities in different classes
  3. Implementation: pick 1-2 most important features and discuss their implementation. write code.
  4. Design patterns, multi-threading: once a basic solution is provided then discussion moves more in depth.

You will be expected to write code or discuss the logic for a few functionalities. Only drawing UML diagrams or writing the names of classes will not be enough.. e.g. if you are asked Design of a parking lot then interviewer will discuss logic of park and unpark feature.

Although for this round your interviewer can allow pseudocode but it is always better to pick a standard language like Java, Python, C++ etc and stick to its syntax. For low level design, Java is the prominent language as of now.

This is what I had to share, you can practice company wise LLD, DS & Algo and AI Assisted round questions on CodeZym. Best of Luck for your interview prep. Thanks for reading.


r/LowLevelDesign • • Aug 13 '26

Microsoft DS & Algo Round Interview Questions Asked in 2026

21 Upvotes

Microsoft frequently opens and closes requisitions to manage referral batches.

The AA (As Appropriate) round generally has behavioral and High Level Design questions, along with architectural deep dives into your previous projects. In some cases, a DSA question may also be asked.

LRU Cache can be asked in either a DSA or a Low Level Design round.

DS & Algo questions for this list have been picked from Microsoft interview experiences shared on forums/blogs etc in 2026. Use this list for final preparation of your Microsoft DSA interview rounds.

Interviewers may also discuss the following questions:

  • What is the difference between a process and a thread?
  • If multiple threads access the same variable without writing to it, can any problem occur?
  • What issues arise when multiple threads access a shared variable?
  • What is the difference between a variable created on the heap and a variable created inside a function?
  • If every thread has its own function-local variables, how can conflicts arise when multiple threads execute the same function?
  • What exactly causes race conditions in multithreaded programs?

------------------------------------------------------

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/07-microsoft-dsa-2026.md


r/LowLevelDesign • • Aug 09 '26

How I can break into low level/system engineering as a fresher?

1 Upvotes

I am a final year IT engineering student in India and I want to build the career in the system engineering / low level rather than typical web development.

I am particularly interested in :-

- Operating systems and kernel development

- System programming

- Linux internals

- Networking and High performance server

- AI infrastructure ( specially inference infrastructure)

I am currently doing:-

- Learning os from the OSTEP and the mit xv6 labs

- Build a HTTP server in C and now planning to add thread pool and epoll.

- Practicing DSA on codeforces and leetcode

- building the distributed inference system as a major project.

My problem is figuring out how to turn out an actual job.

For people currently working in systems/low-level engineering:-

  1. What skills actually expected from a new graduate?
  2. Which areas should I prioritize? OS, networking, compilers, Linux kernel, distributed systems, or something else?
  3. What projects would make a fresher's resume credible for systems roles?
  4. What kind of companies/roles should I target as my first job?
  5. If you were starting again as a student from a non-elite college, what would you spend the next 6 - 12 months doing?

6)What are the mistakes I should avoid when trying to get into low-level engineering?

I would appreciate advice from people who actually work in these areas.


r/LowLevelDesign • • Aug 07 '26

Microsoft Low Level Design and AI-Assisted LLD Round Interview Questions Asked in 2026

22 Upvotes

Microsoft has introduced an AI-assisted Low Level Design round. This is a unique interactive pair-programming round divided into three phases.

Instead of simply writing code from scratch, you have to architect a system, prompt an AI model such as ChatGPT or Gemini to generate the implementation, and then analyze the AI-generated output.

LRU cache and concurrency have been the discussed frequently.

LLD rounds are generally conducted for SDE-2 and above roles. There may also be more than one LLD round during the interview process.

Low Level Design (LLD) questions for this list have been picked from Microsoft interview experiences shared on forums/blogs etc in 2026. Use this list for final preparation of your Microsoft LLD interview rounds.

------------------------------------------------------

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/06-microsoft-lld-2026.md


r/LowLevelDesign • • Aug 05 '26

Mircosoft Interviews coming ahead

Thumbnail reddit.com
1 Upvotes

r/LowLevelDesign • • Jul 31 '26

Goldman Sachs Interview Questions 2026 for CoderPad, SuperDay Coding and LLD Rounds

11 Upvotes

Goldman Sachs is hiring now a days. I complied this list of Goldman Sachs interview questions some time ago using GS interview experiences shared on forums/blogs etc in 2026. It has both DS & Algo and low level design round questions. You can use this list for final preparation of your GS interview rounds..

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/05-goldman-sachs-2026.md


r/LowLevelDesign • • Jul 24 '26

Walmart Low Level Design Round Interview Questions Asked in 2026

22 Upvotes

Ticket booking apps with database discussion, cache implementation, and payment systems are among the most discussed questions in Walmart LLD rounds in 2026.

Database-table design may also be discussed in questions such as designing a movie-ticket booking system like BookMyShow. Be prepared to explain concurrency handling at both the database and application levels, including how to apply row-level locks.

Interviewers may ask about optimistic locking, pessimistic locking, and isolation levels: For example, the default isolation level used by an SQL database.

In LLD, a clear explanation of design choices matters more than just coding.

You may also be asked which design patterns you used recently and deep dive into them.

Java is generally preferred, although candidates do use other languages.

-----------------------------------------------------

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/04-walmart-lld-2026.md

Best of luck for your preparation.


r/LowLevelDesign • • Jul 21 '26

Salesforce Low Level Design Round Interview Questions Asked in 2026

30 Upvotes

Low Level Design (LLD) questions for this list have been picked from Salesforce interview experiences shared on forums/blogs etc in 2026. Use this list for final preparation of your Salesforce interview rounds.

Low Level Design of pub-sub queue, kafka and observer pattern are discussed frequently.

Apart from that cache like LRU cache, LFU cache questions are common.

LRU Cache

https://leetcode.com/problems/lru-cache/description/

LFU Cache

https://leetcode.com/problems/lfu-cache/description/

Requirements and clarifying questions

In Salesforce LLD rounds, sometimes actual requirements may not be clear from problem statement and interviewer will expect you to figure it out by asking clarifying questions.

For example, A message queue is asked indirectly in the form of something like a connection pool or a job scheduler.

It follows the pattern that resources like connections, machines or cpu (in case of job scheduler) are limited and they may not be assigned immediately.

-----------------------------------------------------

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/03-salesforce-lld-2026.md

Best of luck for your preparation.


r/LowLevelDesign • • Jul 17 '26

Walmart DS & Algo Round Interview Questions Asked in 2026

38 Upvotes

I have created list of DSA questions using Walmart interview experiences shared by candidates in blogs/forums etc. Use this list for final preparation of your Walmart interviews.

Walmart interviews can include DS & Algo questions along with Java, Spring Boot, database and problem-solving discussions. Here are a few of them.

Java Questions

  1. New features introduced in Java 8
  2. Why and where to use lambda expressions
  3. Purpose of functional interfaces, their types, and writing sample code
  4. Explanation of ConcurrentModificationException

Spring Boot Questions

  1. Annotations used in your project
  2. Concept of Dependency Injection
  3. What is a Circular Dependency
  4. How to efficiently insert 1000 rows into the database
  5. Basics of JPA (Java Persistence API)

The list starts with questions which you can practice on leetcode for free and then additional questions are there including follow ups that were asked.

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/02-walmart-ds-algo-2026.md

Best of luck for your preparation.


r/LowLevelDesign • • Jul 14 '26

Doordash Codecraft and DS & Algo Round Interview Questions Asked in 2026

13 Upvotes

I have created list of Doordash DSA questions using recent interview experiences shared by candidates in blogs/forums etc. Use this list for final preparation of your DoorDash interviews.

Doordash hires software engineer for E3, E4, E5 roles and so on. SDE 2 role is called E4.

The rounds are Phone Screen (DSA), Codecraft, Debugging, System Design, Hiring Manager

Codecraft round is more of real world api style question. It is similar to a low level design question.

Even for frontend and MLE roles, there will be DSA rounds.

Good thing is that questions are repeated frequently. Their question bank is not that large. This is true for all rounds including codecraft, ds & algo or debugging round.

The list starts with questions which you can practice on leetcode for free and then additional questions are there including follow ups that were asked.

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/01-doordash-ds-algo-2026.md

Best of luck for your preparation.


r/LowLevelDesign • • Jul 08 '26 Heartwarming

Salesforce DS & Algo Round Interview Questions Asked in 2026

21 Upvotes

DS & Algo questions for this list have been picked from Salesforce interview experiences shared on forums/blogs etc in 2026. Use this list for final preparation of your Salesforce interview rounds.

Salesforce hires for Member of Technical Staff i.e. MTS/SMTS/LMTS positions. MTS role is around 3 years experience. LLD rounds may be there for MTS role as well.

List starts with free questions that you can find on leetcode and then more questions including actual follow-ups asked during interview rounds.

You can see company-wise interview questions list on r/LowLevelDesign

Complete DS & Algo Questions List: https://codezym.com/lld/salesforce-dsa

Low Level Design Questions List: https://codezym.com/lld/salesforce

I also take LLD mock interviews: https://topmate.io/prashant_priyadarshi

----------------------------------------------------

Below is list of questions you can directly find on LeetCode (free ones):

Remove Stones to Minimize the Total

https://leetcode.com/problems/remove-stones-to-minimize-the-total/description/

Insert Delete GetRandom O(1)

https://leetcode.com/problems/insert-delete-getrandom-o1/description

Coin Change II

https://leetcode.com/problems/coin-change-ii/description/

Maximal Square

https://leetcode.com/problems/maximal-square/description/

Maximal Rectangle

https://leetcode.com/problems/maximal-rectangle/description/

Rotting Oranges

https://leetcode.com/problems/rotting-oranges/

Course Schedule II

https://leetcode.com/problems/course-schedule-ii/description/

LRU Cache

https://leetcode.com/problems/lru-cache/description/

LFU Cache

https://leetcode.com/problems/lfu-cache/description/

Lowest Common Ancestor of a Binary Tree

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/

Number of Islands

https://leetcode.com/problems/number-of-islands/description/

Find Median from Data Stream

https://leetcode.com/problems/find-median-from-data-stream/description/

Implement Trie (Prefix Tree)

https://leetcode.com/problems/implement-trie-prefix-tree/description/

String Compression

https://leetcode.com/problems/string-compression/description/

Time Needed to Rearrange a Binary String

https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/description/

Minimum Operations to Reduce an Integer to 0

https://leetcode.com/problems/minimum-operations-to-reduce-an-integer-to-0/description/

Top K Frequent Words

https://leetcode.com/problems/top-k-frequent-words/description/

Merge Intervals

https://leetcode.com/problems/merge-intervals/description/

Intersection of Two Linked Lists

https://leetcode.com/problems/intersection-of-two-linked-lists/description/

Partition Array Into Two Arrays to Minimize Sum Difference

https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/description/

Reorganize String

https://leetcode.com/problems/reorganize-string/description/

Combination Sum II

https://leetcode.com/problems/combination-sum-ii/description/

Remove All Adjacent Duplicates in String II

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/description/

First Missing Positive

https://leetcode.com/problems/first-missing-positive/description/

Unique Email Addresses

https://leetcode.com/problems/unique-email-addresses/description/

All O`one Data Structure

https://leetcode.com/problems/all-oone-data-structure/description/

Longest Substring without Repeating Characters

https://leetcode.com/problems/longest-substring-without-repeating-characters/

Time Based Key-Value Store

https://leetcode.com/problems/time-based-key-value-store/

Pairs of Songs with Total Durations Divisible by 60

https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/description/

Asteroid Collision

https://leetcode.com/problems/asteroid-collision/description/

Longest Substring of All Vowels in Order

https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/description/

Zigzag Conversion

https://leetcode.com/problems/zigzag-conversion/description/

Letter Combinations of a Phone Number

https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

Search in Rotated Sorted Array

https://leetcode.com/problems/search-in-rotated-sorted-array/description/

Path with Maximum Gold

https://leetcode.com/problems/path-with-maximum-gold/description/

House Robber II

https://leetcode.com/problems/house-robber-ii/description/

Basic Calculator II

https://leetcode.com/problems/basic-calculator-ii/description/

---------------------------------------------------------

Below are other questions, these include follow-ups asked during interview rounds.

1. Good Ways to Split an Array in 3 Contiguous Parts

You are given a List<Integer> nums containing non-negative integers. Split the list into three non-empty contiguous parts: A1, A2, and A3.

Let:

S1 be the sum of elements in A1

S2 be the sum of elements in A2

S3 be the sum of elements in A3

Count how many splits are valid such that:

S2 ≤ S1 + S3

https://codezym.com/question/248-good-ways-to-split-array

---------------------------------------------------------

2. ATM Queue Leaving Order

There are n people standing in an ATM queue, numbered from 1 to n. Initially, they stand in increasing order of their number.

Person i wants to withdraw amounts[i - 1] units of money. In one turn, a person can withdraw at most maxWithdraw units.

If a person still needs more money after their turn, they go to the end of the queue. Otherwise, they leave the queue.

Return the order in which all people leave the queue.

https://codezym.com/question/249-atm-queue-leaving-order

---------------------------------------------------------

3. Minimum Knight Moves on Infinite Chessboard

A knight is placed at coordinate [0, 0] on an infinite chessboard. The board has no boundary, so coordinates may be positive or negative.

In a single move, the knight travels two squares along one axis and one square along the other axis. Given a target coordinate [x, y], return the fewest moves needed for the knight to reach that target.

https://codezym.com/question/250-min-knight-moves-chess

---------------------------------------------------------

4. Serialize Nearly Sorted Stream of Numbers

You are given a stream of numbers and an integer bufferSize. Every number is at most bufferSize positions away from where it should appear in the correctly ordered stream.

Return the numbers in sorted order, meaning the final list should be in non-decreasing order.

If two numbers are equal, keep their relative order from the input stream to make the output deterministic.

https://codezym.com/question/251-serialize-nearly-sorted-stream

---------------------------------------------------------

5. Minimum Meeting Rooms Required

You are given a list of meeting time intervals.

Each interval is provided as a string in the format "start,end", where start is the meeting start time and end is the meeting end time. You need to split each interval string and extract the integer values start and end.

Each interval is half-open, represented as [start, end). This means a meeting ending at time x does not overlap with another meeting starting at time x. For example, [1, 3) does not overlap with [3, 5).

Your task is to determine the minimum number of meeting rooms required so that no two overlapping meetings are placed in the same meeting room.

https://codezym.com/question/179-minimum-meeting-rooms-required

---------------------------------------------------------

6. Rotting Oranges With Different Connection Times

You are given a grid of oranges and a list of connection times between adjacent cells. Each cell contains one of the following values:

0: an empty cell

1: a fresh orange

2: a rotten orange

A rotten orange can make a connected fresh orange rotten, but each connection may take a different amount of time. A connection is given as "row1,col1,row2,col2,time", meaning the cell at [row1, col1] and the cell at [row2, col2] are connected, and rotting can spread across this connection in time minutes.

Since different connections may take different amounts of time, rotting should always use the earliest possible time at which each orange can become rotten.

Return the minimum time needed for all fresh oranges to become rotten.

https://codezym.com/question/252-rotting-oranges-weighted

---------------------------------------------------------

7. Count Ways to Split String Into Prime Numbers

You are given a string s that represents a positive integer. Count the number of ways to split s into one or more prime numbers.

The digits must remain in the same order, and every digit of s must be used exactly once. Each split part must represent a prime number.

A prime number is an integer greater than 1 that has exactly two positive divisors: 1 and itself.

https://codezym.com/question/253-count-ways-to-split-to-prime-numbers

---------------------------------------------------------

8. Token Bucket Resource Allocation

You are given a token bucket with a fixed number of tokens. Users can request tokens from the bucket. A request is granted only when enough tokens are currently available.

When a request is granted, that user holds those tokens for exactly 1 hour. After 1 hour, the tokens expire automatically and return to the bucket.

A user may also manually release all currently active tokens held by them before expiry. Expired tokens must be cleaned up before processing every method call.

https://codezym.com/question/255-token-bucket-resource-allocation

---------------------------------------------------------

9. Maximum Requests in Continuous Time Window

You are given a list timestamp, where each value represents the minute at which one request occurred. You are also given an integer windowSize. Return the maximum number of requests that can be found inside any continuous time window of length windowSize minutes.

The timestamps may be given in any order. The method should count requests based on their time values, not their original positions.

https://codezym.com/question/256-max-requests-continuous-time-window

---------------------------------------------------------

10. Minimum Time Task Scheduling with Constraints

You are given a list of task types, a list of memory required by each task, and a server memory limit. Each task takes exactly 1 unit of time to complete.

In one unit of time, multiple tasks can run together if they satisfy both constraints: at most 2 tasks of the same type can run in parallel, and the total memory of all running tasks must not exceed the server memory limit.

Return the minimum time required to execute all tasks.

https://codezym.com/question/258-min-time-task-scheduling

---------------------------------------------------------

11. Grid With K Jumps Minimum Steps

You are given an m x n grid. Each cell is either empty or blocked by an obstacle. From any empty cell, you may move in one of four directions: left, right, up, or down.

In one step, you may jump from 1 to k cells in the chosen direction. Every cell crossed during the jump, including the landing cell, must be inside the grid and must not be an obstacle.

Return the minimum number of steps required to reach the destination cell from the source cell. If the destination cannot be reached, return -1.

https://codezym.com/question/259-grid-with-k-jumps

---------------------------------------------------------

12. Count Number of Distinct Islands in Grid

You are given a non-empty grid containing only 0 and 1.

Each 1 represents land, and each 0 represents water.

An island is a connected group of land cells. Two land cells are connected if they share a side horizontally or vertically.

You may assume that all four outer edges of the grid are surrounded by water.

Your task is to count how many distinct island shapes exist in the grid.

Two islands are considered the same only if one island can be shifted up, down, left, or right to exactly match the other island.

Rotating or reflecting an island is not allowed when comparing island shapes.

https://codezym.com/question/190-count-distinct-islands-grid

---------------------------------------------------------

13. Bottle Recycling Perk Maximization

You are given an initial number of bottles and an initial amount of money. You may either recycle bottles to earn money or spend bottles and money to buy perks.

Recycling one bottle gives recycleVal dollars. Buying one perk costs exactly 1 bottle and perkVal dollars.

Each bottle can be used at most once. A bottle that is recycled cannot be used to buy a perk, and a bottle used to buy a perk cannot be recycled. Return the maximum number of perks that can be obtained.

https://codezym.com/question/260-bottle-recycling-perk-maximization

---------------------------------------------------------

14. Maximum Number of Non-Overlapping Palindromic Substrings

You are given a string s and an integer k. Choose the maximum possible number of non-overlapping substrings such that every chosen substring is a palindrome and has length at least k.

A palindrome is a string that reads the same from left to right and from right to left.

The chosen substrings do not need to cover the entire string. Characters between chosen substrings and any remaining characters may be ignored.

Return the chosen palindromic substrings as a List<String>. The substrings must be returned in the same left-to-right order in which they appear in s.

https://codezym.com/question/261-max-non-overlapping-palindromes

---------------------------------------------------------

15. Count Special Subarrays With Odd Divisors

You are given a list of positive integers called nums. A contiguous subarray is considered special when the product of all its elements has an odd number of positive divisors.

Return the total number of special subarrays in nums.

https://codezym.com/question/262-count-special-subarrays

---------------------------------------------------------

16. Maximum Length Subsequence Substring

You are given two strings, x and y. Return the longest string that is both a subsequence of x and a contiguous substring of y.

A subsequence is formed by deleting zero or more characters without changing the order of the remaining characters. A substring consists of consecutive characters.

If multiple valid strings have the maximum length, return the lexicographically smallest one. If no non-empty valid string exists, return an empty string.

https://codezym.com/question/263-max-length-subseq-substring

---------------------------------------------------------

17. IPO Share Allocation With Bids

You are given a collection of bids for shares in an IPO and the total number of shares available. Allocate the shares according to bid price and submission time, then return the user IDs of bidders who receive no shares.

https://codezym.com/question/264-ipo-share-allocation-with-bids

---------------------------------------------------------

18. Purchase Maximum Number of Consecutive Products

You are given a list of product prices sorted in non-decreasing order and a list of buying queries. For each query, determine the maximum number of consecutive products that can be purchased without exceeding the given budget.

https://codezym.com/question/265-purchase-max-consecutive-products

---------------------------------------------------------

19. Complete Weekly Work Hours

A worker's daily hours for one week are represented by a seven-character string workHours. Each position corresponds to one day and contains either a digit from 0 to 9 or the character #.

Replace every # with a digit from 0 to 9 so that the sum of all seven digits is exactly requiredHours. Return all completed strings that satisfy this condition.

https://codezym.com/question/267-complete-weekly-work-hours

---------------------------------------------------------

Thanks for reading.

Wish you the best of luck for your interview prep.


r/LowLevelDesign • • Jul 03 '26

Uber DS & Algo Interview Round Questions Asked in 2026

25 Upvotes

DS & Algo questions for this list have been picked from Uber interview experiences shared on forums/blogs etc in 2026. Use this list for final preparation of Uber interviews.

BPS (Business Problem Solving Round) will have a coding question (mostly hard) and may be 15 minutes of system design discussion. Phone screen also has DS & Algo questions.

For frontend roles, apart from DSA, you may be asked to create typescript components. Those are not included in below list.

DSA interview questions asked in Uber are more difficult than Amazon, Microsoft, Meta.

DS & Algo questions are asked for machine learning engineer role as well.

---------------------------------------------------------

PS:
You can see company-wise interview questions list on r/LowLevelDesign

Complete DS & Algo Questions List: https://codezym.com/lld/uber-dsa

Low Level Design Questions List: https://codezym.com/lld/uber

I also take LLD mock interviews: https://topmate.io/prashant_priyadarshi

----------------------------------------------------

Below is list of questions that you can practice directly from leetcode (Free Ones):

Maximum Number of Events That Can Be Attended

https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/

Minimum Number of Refueling Stops

https://leetcode.com/problems/minimum-number-of-refueling-stops/description/

Longest Path With Different Adjacent Characters

https://leetcode.com/problems/longest-path-with-different-adjacent-characters/description/

Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/description/

Minimum Difference in Sums After Removal of Elements

https://leetcode.com/problems/minimum-difference-in-sums-after-removal-of-elements

Sliding Window Maximum

https://leetcode.com/problems/sliding-window-maximum/description/

Count the Number of Infection Sequences

https://leetcode.com/problems/count-the-number-of-infection-sequences/description/

Find the Closest Palindrome

https://leetcode.com/problems/find-the-closest-palindrome/

Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/description/

Exam Room

https://leetcode.com/problems/exam-room/description/

Minimum Edge Reversals So Every Node Is Reachable

https://leetcode.com/problems/minimum-edge-reversals-so-every-node-is-reachable/description/

LRU Cache

https://leetcode.com/problems/lru-cache/description/

Shortest Palindrome

https://leetcode.com/problems/shortest-palindrome/description/

Final Prices With a Special Discount in a Shop

https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/description/

Water and Jug Problem

https://leetcode.com/problems/water-and-jug-problem/description/

First Unique Number

https://leetcode.com/problems/first-unique-number/description/

Cheapest Flights Within K Stops

https://leetcode.com/problems/cheapest-flights-within-k-stops/description/

Maximum Points You Can Obtain From Cards

https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/description/

---------------------------------------------------------

Below is list of more Uber DS & Algo round interview questions. These also include follow up questions that were asked during interview round.

---------------------------------------------------------

1. Find Vertical Line Rectangle Intersection Points

Given n infinite vertical lines on an XY plane and m axis-aligned rectangles, find the total number of intersection points made by the lines and rectangles.

https://codezym.com/question/216-vertical-line-rectangle-intersection-points

---------------------------------------------------------

2. Check If Array Can Converge To Same Value

You are given a list of digits where every value is from 0 to 9. For each index, you may perform exactly one of these choices: add 1, subtract 1 or keep the value unchanged.
The digits are circular, so 9 + 1 = 0 and 0 - 1 = 9. Determine whether all elements can become the same digit after applying at most one such operation to each element.
If convergence is possible, return the final digit. If more than one final digit is possible, return the smallest such digit. If convergence is not possible, return -1.

https://codezym.com/question/217-array-converge-to-same-value

---------------------------------------------------------

3. Longest Itinerary Route in a Directed Graph

You are given a list of allowed itineraries between cities. Each itinerary represents a directed route from one city to another city.

Design an algorithm to find the longest route that can be formed using the given itineraries. A route may start from any city and must follow only the given directed itineraries.

https://codezym.com/question/210-longest-itinerary-route

---------------------------------------------------------

4. Earliest Timestamp When All Riders Are Connected

You are given a list of riders and a chronological list of Uber Share events. Each shared-ride event connects two riders. Two riders are connected if they have directly or indirectly shared rides through other riders.

Return the earliest timestamp when all riders become part of one connected shared-ride network. If all riders never become connected, return -1.

https://codezym.com/question/211-earliest-timestamp-riders-connected

---------------------------------------------------------

5. Maximize XOR Score After Adding X

You are given a list of integers and an integer x. You may perform one operation at most once: choose any set of indices and add x to every chosen element.

After the operation, the score is the sum of XOR values of every pair of adjacent elements. Return the maximum possible score.

https://codezym.com/question/213-maximize-xor-score-after-adding-x

---------------------------------------------------------

6. Count Distinct Islands In Grid

You are given a non-empty grid containing only 0 and 1.

Each 1 represents land, and each 0 represents water.

An island is a connected group of land cells. Two land cells are connected if they share a side horizontally or vertically.

You may assume that all four outer edges of the grid are surrounded by water.

Your task is to count how many distinct island shapes exist in the grid.

https://codezym.com/question/190-count-distinct-islands-grid

---------------------------------------------------------

7. Minimum Cost Binary Search Tree From Words

You are given a list of distinct words and a corresponding list of positive costs. Construct a binary search tree using all words such that its inorder traversal gives the words in lexicographical order.

If a word is placed at level L, where the root is at level 0, its contribution to the total cost is (L + 1) * cost. Return the minimum possible total cost among all valid binary search trees.

https://codezym.com/question/214-minimum-cost-binary-search-tree-from-words

---------------------------------------------------------

8. Design Employee Management System

Design an employee-manager system with exactly one CEO. The CEO has no manager. Every other employee has exactly one direct manager.

The system must support adding employees, getting an employee's manager, changing an employee's manager, and checking whether an employee works directly or indirectly under a manager.

https://codezym.com/question/215-design-employee-management-system

---------------------------------------------------------

9. Minimum Cabs With Wait Period for Scheduled Bookings

You are given a list of scheduled cab bookings. Each booking has a start time and an end time. A cab can handle multiple bookings, but after completing one booking it must wait for a fixed wait period before starting another booking.
Find the minimum number of cabs required to complete all bookings.

https://codezym.com/question/218-min-cabs-with-wait-period

---------------------------------------------------------

10. Biological Hazards: Valid Chemical Pair Intervals

You are given n chemicals labeled from 1 to n. Some pairs of chemicals are dangerous and cannot appear together in the same contiguous interval.
The lists poisonous and allergic describe forbidden pairs. For every index i, chemicals poisonous.get(i) and allergic.get(i) cannot coexist.
Count how many contiguous intervals [L, R] are valid such that the interval does not contain both chemicals from any forbidden pair.

https://codezym.com/question/219-valid-chemical-pair-intervals

---------------------------------------------------------

11. Design Vote Share Display for Voting System

Design a voting system for a multiple-choice question with exactly 4 options. When a user clicks one option, that option receives one vote. After every vote, the system should return the updated vote percentage for all options.
The percentage of each option also represents how much color fill should be shown for that option in the UI. For example, if an option has 40% votes, then 40% of that option row should be filled with color.

https://codezym.com/question/220-design-mcq-voting-system

---------------------------------------------------------

12. Validate Organization Reporting Structure

You are given a reporting structure of people in an organization. Each entry is a string in the format "employee,manager", meaning the employee directly reports to the manager.
Determine whether the reporting structure forms one valid organization.

https://codezym.com/question/221-validate-organization-reporting-structure

---------------------------------------------------------

13. Maximum Comfortable Riders in a Car

You are given n riders and one car with unlimited space. Each rider has a comfort range for how many other riders must be present in the car.
A rider will ride only if the number of other riders in the car is within their comfort range. Return the maximum number of riders that can ride together in the car.

https://codezym.com/question/223-max-comfortable-riders-in-car

---------------------------------------------------------

14. Find Robots in Location Map by Nearest Blockers

You are given a robot location map and a query describing required distances from a robot to the nearest blocker. Find all robots whose nearest blocker distances exactly match the query.

https://codezym.com/question/225-robots-by-nearest-blockers

---------------------------------------------------------

15. First One Time Visitor in Stream of Customer Visits

You are given a stream of customer visits. Each visit contains one positive integer customerId. A customer is a one-time visitor if they have appeared exactly once in the stream so far.
Design a data structure that records customer visits and returns the earliest customer who has visited exactly once.

https://codezym.com/question/226-one-time-visitor-in-customer-visits-stream

---------------------------------------------------------

16. Minimum Changes Circular Rock Paper Scissors

Engineers are sitting around a circular table and each engineer chooses one option from Rock, Paper, and Scissors. The choices are represented by the characters 'R', 'P', and 'S'.
Two neighboring engineers tie if they choose the same option. You may change any engineer's choice to either of the other two options. Return the minimum number of engineers whose choices must be changed so that no two adjacent engineers have the same choice.

https://codezym.com/question/228-minimum-changes-circular-rock-paper-scissors

---------------------------------------------------------

17. Alien Language Letter Order

A new alien language uses lowercase Latin letters, but the order of the letters is not known.

You are given a list of non-empty dictionary words. The words are already sorted in lexicographical order according to the rules of this alien language.

Your task is to derive the lexicographically smallest valid ordering of letters in the alien language.

https://codezym.com/question/182-alien-language-letter-order

---------------------------------------------------------

18. Microservice Restart Cycles

There are n microservices numbered from 0 to n - 1. Each microservice may depend on other microservices. A service can start only after all services it depends on have already started.
A dependency is considered satisfied if it started in any previous cycle or earlier in the current cycle.
Return the number of cycles needed to start all services using this process.

https://codezym.com/question/229-microservice-restart-cycles

---------------------------------------------------------

19. Sorted Order of Squares

Given a list of integers sorted in non-decreasing order, return the original values arranged by the increasing order of their squares. If two values have the same square, the value that appears earlier in the input list should appear earlier in the output.

https://codezym.com/question/230-sorted-order-of-squares

---------------------------------------------------------

20. Minimum Time To Burn Tree

You are given an undirected tree with n nodes numbered from 0 to n - 1. The fire can start from any node, and you may choose the starting node to minimize the total burning time. In each time unit, fire spreads from every burning node to all of its adjacent nodes. Return the minimum time required to burn the entire tree.

https://codezym.com/question/232-minimum-time-to-burn-tree

---------------------------------------------------------

Thanks for reading.

Wish you the best of luck for your interview prep.

Uber DS & Algo Interview Round Questions Asked in 2026

r/LowLevelDesign • • Jun 30 '26 Bravo

Amazon Low Level Design Interview Questions asked in 2026

35 Upvotes

I am listing the top low level design questions that were asked during Amazon low level design interview rounds in 2026. I have built this list from recent interview experiences of candidates shared on blog/forums etc.

Also, we will see how we can solve them using commonly asked design patterns.

I am keeping the most frequent questions first. Feel free to use this list for final preparation of your Amazon interviews.

---------------------------------------------------------

PS:
You can see companywise interview questions list on r/LowLevelDesign

All LLD Questions List: https://codezym.com/lld/amazon

All DSA Questions List: https://codezym.com/lld/amazon-dsa

I also take LLD mock interviews: https://topmate.io/prashant_priyadarshi

----------------------------------------------------

1. Design Pizza Pricing System

You will have to initialize a new pizza, adding toppings (corn, onion etc) to it and calculate final price of pizza.

This is a fairly simple problem. But some interviewers may expect you to implement decorator design pattern. In my view that just complicates the solution without adding any benefit.

Your interviewer may add business rules as a follow up like these

cheese burst cannot be added on small pizza or

You get 30% discount on corn price when you take more than 2 servings and so on..

Practice Link: https://codezym.com/question/18

Follow up with more business rules: https://codezym.com/question/19

-----------------------------------

2. Design Unix “find” Command for File Search

Unix find command searches for files.

There can be different search criteria like search by file size, search by extension, or search by substring in file name.

For example:

list all files which are less than 2 MB in size

or

list all files whose extension is .pdf.

You can use Strategy Design Pattern to implement the different search criteria.

A follow-up is generally asked to combine queries like Boolean predicates AND, OR, etc.

For example:

list all files which are greater than 2 MB in size AND their extension is ".jpg".

You can use Specification Design Pattern to combine the result of search queries.

Practice Link: https://codezym.com/question/14

Follow up with combining queries: https://codezym.com/question/15

--------------------------------------

3. Design a Parking Lot

This is THE most common LLD interview question.

You must do this question if you are preparing for any LLD interview.

A parking lot can have multiple floors.

Its core features will be:

park and unpark vehicles

search parked vehicles by vehicle number

count number of free spots on a given floor for a given vehicle type

Your entities will be ParkingLot class, which will contain a list of ParkingFloor objects.

ParkingFloor will contain a 2-D array of ParkingSpot objects arranged in rows and columns.

There can be multiple parking strategies, so we should use Strategy Design Pattern to solve this question.

Practice Link: https://codezym.com/question/7

Follow up with multi-threaded environment: https://codezym.com/question/1

--------------------------------------

4. Design LRU Cache With Time Constraint

Design an LRUCacheWithTimeConstraint class that implements an LRU cache with a fixed capacity and a time constraint.

Practice Link: https://codezym.com/question/165

--------------------------------------

5. Design WhatsApp Read Receipts

Design a WhatsAppReadReceipts feature.

Assume WhatsApp is already built.

The observer system that receives message sent, delivered, and read events is also already built.

Your task is only to design the read receipt feature that tracks and returns the correct tick status for each message.

A message can show one gray tick, two gray ticks, or two blue ticks depending on whether the message was sent, delivered, or read.

The feature must support direct conversations and group conversations.

Practice Link: https://codezym.com/question/168

--------------------------------------

6. Design Backup System for a File Storage Service

You are asked to design a backup system for a file storage service.

The system stores files, supports reading and writing files, and can create backups of the current file system state.

A backup can be one of three types:

FULL

DIFFERENTIAL

LOG

A FULL backup stores the complete current state of all existing files.

A DIFFERENTIAL backup stores only the final file changes made since the latest full backup.

A LOG backup stores the ordered write operations performed after the latest backup pointer.

Practice Link: https://codezym.com/question/172

--------------------------------------

7. Design Digital Wellbeing System to Track App Screen Usage

You need to design a DigitalWellbeingSystem that keeps track of screen usage for different applications.

The system receives usage records for apps.

Each usage record contains an app name, a day number, and the amount of screen time used on that day.

The system should allow querying usage statistics for applications.

Practice Link: https://codezym.com/question/178

--------------------------------------

8. Design Locker Management System for Warehouse Packages

In a warehouse for any e-commerce website like Amazon, packages are kept in lockers.

Your goal is to add new lockers of different sizes, assign packages to those lockers, and later free the lockers.

Practice Link: https://codezym.com/question/16

--------------------------------------

9. Design Chess Game

Chess game is all about creating different pieces and implementing their moves.

Different pieces like king, queen, knight, etc., have different moves like straight move for rook, diagonal move for bishop, 2+1 move for knight, etc.

The core functionality is to check whether a piece can move to a destination row and column from its current row and column.

We use Factory Design Pattern, Chess Piece Factory, to create different chess piece objects like king, queen, pawn, etc.

Strategy Design Pattern may be used to implement different moves like straight move, diagonal move, etc.

Practice Link: https://codezym.com/question/8

--------------------------------------

10. Design Expense Sharing App Like Splitwise

Splitwise is used to manage group expenses.

It basically does two things:

supports adding group expenses, i.e. who paid how much in an expenditure

tracks how much each person owes or is owed after group expenses are split evenly among participants

Practice Link: https://codezym.com/question/12

--------------------------------------

11. Design a Restaurant Food Ordering System Like Zomato, Swiggy, DoorDash

Users can search for restaurants using food item name, order food, and rate their orders.

When searching for food, they also have the option to view the restaurant list sorted by different parameters like restaurants with highest average rating first.

These view classes with lists of restaurants sorted by average rating will need to be updated whenever an order is rated by a user, so that they can update their lists.

Hence, this is an ideal use case of Observer Design Pattern.

Practice Link: https://codezym.com/question/5

--------------------------------------

12. Design Stock Broker Platform Like Zerodha, Groww

This system manages all company stocks and their prices.

Users can place orders to either buy or sell stocks.

Users can also view their account balance and the stocks they hold.

One case you need to take care of is closing the relevant open orders when stock price changes.

Practice Link: https://codezym.com/question/20

--------------------------------------

13. Design a Movie Ticket Booking System Like BookMyShow

In this question, core functionalities will include adding new cinema halls and new shows in those cinema halls.

Users can also book and cancel tickets.

Users should be able to list all cinemas in a city which are displaying a particular movie.

They should also be able to fetch the list of all shows in a cinema hall which are displaying a particular movie.

Classes implementing the last two search features need to be updated whenever a new show gets added, so that they can update their respective lists.

We use Observer Design Pattern to send new show added updates to the search movie/show classes.

Practice Link: https://codezym.com/question/10

--------------------------------------

14. Design a Simple Elevator System

A lift in an elevator system can be in one of three states:

Moving Up

Moving Down

Idle

In each state, it will behave differently while taking decisions like whether to stop on a floor, whether to add a new request or not, etc.

Use State Design Pattern to implement different states of lift.

Problem Statement: https://codezym.com/question/11

--------------------------------------

DSA Based Design Questions

These questions can be asked in either DS & Algo or Low-Level Design rounds depending on the interviewer.

Don’t skip them.

--------------------------------------

Design File System

https://codezym.com/question/11166

https://codezym.com/question/10588

--------------------------------------

Design Log Storage System

https://codezym.com/question/10635

--------------------------------------

Design LRU / LFU Cache

https://leetcode.com/problems/lru-cache/description/

https://leetcode.com/problems/lfu-cache/description/

--------------------------------------

Design Snake Game

https://codezym.com/question/10353

--------------------------------------

Design Hit Counter

https://codezym.com/question/10362

Multi-Threaded Version: https://codezym.com/question/6

--------------------------------------

Design Tic Tac Toe

https://codezym.com/question/10348

--------------------------------------

Design Google Search Autocomplete

https://codezym.com/question/10642

--------------------------------------

Design Excel Sum Formula

https://codezym.com/question/10631

--------------------------------------

Thanks for reading. Please upvote this post for better reach.

Wish you the best of luck for interviews.

--------------------------------------


r/LowLevelDesign • • Jun 28 '26

Uber Low Level Design and Depth in Specialization Round Interview Questions asked in 2026

14 Upvotes

LLD questions for this list have been picked from Uber interview experiences posted on forums/blogs etc in 2026.

Uber has a depth in specialization / depth specific coding round in which they ask LLD questions many times.

Code is required, not only class diagrams. You will need to implement 2–3 most important functions.

Sometimes questions similar to low level design like Design a voting system to display vote share are also asked in screening round. Or there can even be a separate LLD round.

---------------------------------------------------------

Complete list of Uber Low Level Design Questions:

https://codezym.com/lld/uber

If you are looking for Uber DS and Algo round questions, then you can find them here:

https://codezym.com/lld/uber-dsa

---------------------------------------------------------

1. Design a Single-Queue Publish Subscribe System

Design an in-memory publish/subscribe system with exactly one global FIFO (first in first out) queue.

Multiple publishers can publish messages to this queue. Many subscribers can subscribe to the same queue.

When a message is appended, all subscribers are notified, and each subscriber consumes at its own pace.

A subscriber can consume only those messages which were sent while it was subscribed.

This question requires the use of Observer pattern (Queue Manager = Subject, Subscribers = Observers).

https://codezym.com/question/33-design-single-queue-publish-subscribe-system

---------------------------------------------------------

2. Design a File System (cd with '*')

Design and implement an in-memory unix filesystem shell that supports three commands:

- mkdir &lt;path&gt;,

- pwd, and

- cd &lt;path&gt; (with a special wildcard segment *).

https://codezym.com/question/30-design-file-system-cd-with-star

---------------------------------------------------------

3. Design Parking Lot - Simple Version

Design a parking lot system that supports parking and removing vehicles. The parking lot has multiple floors. Each floor has a list of parking spots.

Floors are numbered from 0. Spots on each floor are also numbered from 0 from left to right. Initially, all parking spots are empty.

The parking lot should always assign the lowest available valid spot. A lower floor is preferred first. If multiple valid spots are available on the same floor, the spot with the lower index should be assigned first.

https://codezym.com/question/208-design-parking-lot-simple

---------------------------------------------------------

4. Design Website Customer Visit Tracking Service

Design a customer visit tracking service for a website that receives millions of visits every day. Each customer has a unique identifier that remains the same across all their visits.

A customer is a one-time visitor if they have visited exactly once so far. A customer is a recurrent visitor if they have visited more than once.

The service should record customer visits, return a customer's latest login timestamp, and return the first customer who is still a one-time visitor.

https://codezym.com/question/209-design-website-customer-visit-tracker

---------------------------------------------------------

5. Design expense sharing app like SplitWise

Design a lightweight expense-sharing system that tracks how much each person owes or is owed after group expenses are split evenly among participants. The system maintains net balances and exposes operations to add users, record expenses, and list simplified debtor-to-creditor balances.

https://codezym.com/question/12-design-splitwise-expense-sharing-app

---------------------------------------------------------

6. Design MCQ Voting System to Display Vote Share

Design a voting system for a multiple-choice question with exactly 4 options. When a user clicks one option, that option receives one vote. After every vote, the system should return the updated vote percentage for all options.

The percentage of each option also represents how much color fill should be shown for that option in the UI. For example, if an option has 40% votes, then 40% of that option row should be filled with color.

https://codezym.com/question/220-design-mcq-voting-system

---------------------------------------------------------

7. Design Uber Eats Ads Schedule Dashboard

You are designing an Uber Eats ads dashboard where an advertiser can choose when an ad should run during a week.

The dashboard has 7 days, from Monday to Sunday. Each day is divided into 6 fixed time slots of 4 hours each. A selected slot means the ad will be displayed during that slot for that day.

Clicking a slot toggles it. If the slot was not selected, it becomes selected. If it was already selected, it becomes unselected.

The dashboard stores the full weekly schedule together. Switching between days should not require fetching separate data for that day.

https://codezym.com/question/222-uber-eats-ads-schedule-dashboard

---------------------------------------------------------

8. Design Uber Eats Pricing Calculator

Design an Uber Eats pricing calculator for food orders. Each food item has a price based on its size, and customers may add toppings. The final price can be affected by BOGO offers, surge pricing, coupon discounts, and an extra Uber One member discount.

All prices are represented in cents. Return the final payable amount as an integer number of cents.

https://codezym.com/question/224-uber-eats-pricing-calculator

---------------------------------------------------------

9. Design Rate Limit Circuit Breaker

Design a circuit breaker that protects a service when too many requests arrive in a short time. This circuit breaker opens based on the number of requests, not the number of failed requests.

The breaker has three states: CLOSED, OPEN, and HALF_OPEN. Requests are accepted only when the current state allows them.

https://codezym.com/question/227-rate-limit-circuit-breaker

---------------------------------------------------------

10. Design Key Value Store With O(1) Insert, Delete, Get First

Design a key-value store that supports insertion, lookup, deletion, and access to the first and last active entries in constant time.

Active entries are maintained in insertion order. Updating an existing key changes only its value and does not change its position.

https://codezym.com/question/212-key-value-store-o1-insert-delete-get-first

---------------------------------------------------------

11. Design a Meeting room reservation System

Design a simple Meeting room reservation System for a fixed list of conference rooms. You will be given the room identifiers up front, and you must support booking and canceling meetings while ensuring no two meetings overlap in the same room.

https://codezym.com/question/29-design-meeting-room-reservation-system

---------------------------------------------------------

12. Design a Movie ticket booking system like BookMyShow

Write code for low level design of a movie ticket booking system like BookMyShow.

System has cinemas located in different cities. Each cinema will have multiple screens, and users can book one or more seats for a given movie show.

System should be able to add new cinemas and movie shows in those cinemas.

Users should be able to list all cinema's in their city which are displaying a particular movie.

For a given cinema, users should also be able to list all shows which are displaying a particular movie.

https://codezym.com/question/10-design-movie-ticket-booking-system

---------------------------------------------------------

13. Design a Leaderboard for Fantasy Teams

Build an in-memory leaderboard for a fantasy-sports style app. Each user creates exactly one team made up of one or more players. As a live match progresses, players receive positive or negative points. A user’s score is the sum of the current scores of all players on that user’s team. You must support querying the Top-K users ranked by score.

https://codezym.com/question/31-design-leaderboard-fantasy-teams

---------------------------------------------------------

14. Design a Train Platform Management System

Design a system that manages assignment of trains to platforms in a railway station and supports time-based queries, with a clean, extensible object-oriented design.

https://codezym.com/question/32-design-train-platform-management-system

---------------------------------------------------------

Thanks for reading. Please upvote to give this article better reach

Wish you the best of luck for your interview prep.


r/LowLevelDesign • • Jun 11 '26

Kotak Mahindra SDE2 interview coming up. Guide me

Thumbnail reddit.com
2 Upvotes