Autocoder

Delhivery Coding Round Questions

Last updated 2026-11-19

Logistics turns neatly into algorithm problems: shortest routes between hubs, merging delivery windows, packing parcels into vehicles, picking the nearest depots, counting late shipments in SQL. This page gives eleven practice problems in that style with worked solutions in Python, Java and SQL, plus complexity and the mistakes that lose marks.

They are practice problems in the style of logistics topics, not a copy of any test. Pair them with Delhivery interview questions and the DSA coding round guide.

Languages herePython, Java, SQL
ThemesGraphs, greedy, intervals, heaps, DP, SQL
LevelEasy to hard

Turning logistics wording into patterns

Hubs and roads are a graph, vehicle capacity is a knapsack or bin-packing variant, delivery windows are intervals, and "the k nearest" is a heap. Name the pattern first, then check the constraints: are weights non-negative, is the graph directed, can there be ties?

Hiring status

We hold no sourced facts about Delhivery's tests, drives, openings or cutoffs, so none are stated. Use the company's own careers site for current information.

Delhivery Coding Round Questions: questions with worked answers

  1. 1

    Find the first duplicate shipment id in a list of scans.

    easy

    Scan once with a set; the first id already in the set is the answer. O(n) time, O(n) space. If space is limited and values are in range 1..n, you can mark visited indexes by negating values, but that modifies the input. Mistake: returning the duplicate with the smallest value rather than the first to repeat, which is a different problem.

    python
    def first_duplicate(ids):
        seen = set()
        for x in ids:
            if x in seen:
                return x
            seen.add(x)
        return None
  2. 2

    Minimum cost to travel from hub A to hub B (Dijkstra with a path).

    medium

    Use a min-heap on (distance, node), record each node's parent when you improve a distance, and rebuild the path backwards. O((V + E) log V). Mistake: relaxing edges without skipping stale heap entries wastes time but remains correct; the actual bug is applying Dijkstra to graphs with negative edges.

    python
    import heapq
    
    def route(adj, src, dst):
        dist = {src: 0}
        parent = {}
        h = [(0, src)]
        while h:
            d, u = heapq.heappop(h)
            if d > dist.get(u, float('inf')):
                continue
            if u == dst:
                break
            for v, w in adj.get(u, []):
                nd = d + w
                if nd < dist.get(v, float('inf')):
                    dist[v] = nd
                    parent[v] = u
                    heapq.heappush(h, (nd, v))
        if dst not in dist:
            return None, []
        path, cur = [dst], dst
        while cur != src:
            cur = parent[cur]
            path.append(cur)
        return dist[dst], path[::-1]
  3. 3

    Merge delivery time windows and report free slots.

    medium

    Sort windows by start and merge overlapping ones; the gaps between consecutive merged windows are the free slots. O(n log n). Mistake: forgetting to take the maximum end when merging, or treating windows that touch as a gap of zero length.

    python
    def free_slots(windows, day_start, day_end):
        windows.sort()
        merged = []
        for s, e in windows:
            if merged and s <= merged[-1][1]:
                merged[-1][1] = max(merged[-1][1], e)
            else:
                merged.append([s, e])
        free, cur = [], day_start
        for s, e in merged:
            if s > cur:
                free.append((cur, s))
            cur = max(cur, e)
        if cur < day_end:
            free.append((cur, day_end))
        return free
  4. 4

    Minimum number of trucks of capacity C needed, if each truck carries at most two parcels (two-pointer greedy).

    medium

    Sort weights, then pair the heaviest remaining with the lightest if they fit together; otherwise the heaviest goes alone. This is optimal for the two-per-truck case and the same idea solves "boats to save people". O(n log n) time, O(1) extra space. Mistake: pairing greedily from the front without sorting, or assuming it generalises to three or more parcels per truck, where the problem becomes bin packing and is NP-hard.

    python
    def trucks(weights, cap):
        weights.sort()
        i, j, n = 0, len(weights) - 1, 0
        while i <= j:
            if weights[i] + weights[j] <= cap:
                i += 1
            j -= 1
            n += 1
        return n
    
    print(trucks([3, 2, 2, 1], 3))  # 3
  5. 5

    K nearest depots to a point, using a heap (Java).

    medium

    Use a max-heap of size k keyed by squared distance; push each depot and pop the farthest when the size exceeds k. O(n log k). Use long for squared distances because coordinates in the millions overflow int. Mistake: using Math.sqrt and comparing doubles when squares are enough.

    java
    import java.util.*;
    
    public class Depots {
        public static List<int[]> nearest(int[][] depots, int x, int y, int k) {
            PriorityQueue<int[]> pq = new PriorityQueue<>(
                (a, b) -> Long.compare(dist(b, x, y), dist(a, x, y)));
            for (int[] d : depots) {
                pq.add(d);
                if (pq.size() > k) pq.poll();
            }
            return new ArrayList<>(pq);
        }
        static long dist(int[] p, int x, int y) {
            long dx = p[0] - x, dy = p[1] - y;
            return dx * dx + dy * dy;
        }
    }
  6. 6

    Rotting parcels: multi-source BFS. In a grid, damaged parcels (2) spread damage to adjacent good parcels (1) each minute. How many minutes until none are good, or -1?

    medium

    Start the BFS queue with all damaged cells at once, process level by level, and count levels. If any good cell remains at the end, return -1. O(rows * cols). Mistake: running a separate BFS from each damaged cell, which is far slower, and returning the level count including the empty last level (off by one).

    python
    from collections import deque
    
    def minutes(g):
        R, C = len(g), len(g[0])
        q = deque((r, c) for r in range(R) for c in range(C) if g[r][c] == 2)
        good = sum(row.count(1) for row in g)
        t = 0
        while q and good:
            for _ in range(len(q)):
                r, c = q.popleft()
                for nr, nc in ((r+1,c),(r-1,c),(r,c+1),(r,c-1)):
                    if 0 <= nr < R and 0 <= nc < C and g[nr][nc] == 1:
                        g[nr][nc] = 2
                        good -= 1
                        q.append((nr, nc))
            t += 1
        return t if good == 0 else -1
  7. 7

    Maximum parcels a vehicle can carry without exceeding a weight limit (0/1 knapsack by value).

    medium

    DP over capacity: dp[w] is the best value using total weight at most w. Iterate items, and for each iterate w downward from capacity to the item weight so each item is used once. O(n * W) time, O(W) space. Mistake: iterating w upward, which allows an item to be used repeatedly (unbounded knapsack).

    python
    def knapsack(weights, values, cap):
        dp = [0] * (cap + 1)
        for wt, val in zip(weights, values):
            for w in range(cap, wt - 1, -1):
                dp[w] = max(dp[w], dp[w - wt] + val)
        return dp[cap]
  8. 8

    SQL: shipments delivered later than the promised date, per city, as a percentage.

    medium

    Use conditional aggregation: count late deliveries and divide by total delivered, casting to avoid integer division. Group by city. Mistake: integer division giving 0, and including undelivered shipments in the denominator.

    sql
    SELECT city,
           100.0 * SUM(CASE WHEN delivered_at > promised_at THEN 1 ELSE 0 END) / COUNT(*) AS pct_late
    FROM shipments
    WHERE status = 'DELIVERED'
    GROUP BY city
    ORDER BY pct_late DESC;
  9. 9

    SQL: the latest scan for each shipment.

    medium

    Rank scans per shipment by time descending and keep rank 1. ROW_NUMBER guarantees one row even on identical timestamps. The alternative, joining to MAX(ts) per shipment, returns duplicates on ties. Mistake: grouping by shipment and selecting non-aggregated columns, which is invalid or arbitrary depending on the database.

    sql
    SELECT shipment_id, hub_id, event_type, ts
    FROM (
      SELECT s.*, ROW_NUMBER() OVER (PARTITION BY shipment_id ORDER BY ts DESC) AS rn
      FROM scans s
    ) x
    WHERE rn = 1;
  10. 10

    Travelling salesman for a small set of stops (up to 15): shortest tour visiting each once.

    hard

    Held-Karp dynamic programming over subsets: dp[mask][i] is the least cost to visit the set mask ending at i. Transition from every j in mask. O(2^n * n^2) time, O(2^n * n) space, fine for n up to roughly 15-18. For larger inputs use heuristics. Mistake: brute-forcing n! permutations, which is infeasible beyond about 10 stops.

    python
    def tsp(dist):
        n = len(dist)
        INF = float('inf')
        dp = [[INF] * n for _ in range(1 << n)]
        dp[1][0] = 0
        for mask in range(1 << n):
            for i in range(n):
                if dp[mask][i] == INF or not mask & (1 << i):
                    continue
                for j in range(n):
                    if not mask & (1 << j):
                        nm = mask | (1 << j)
                        dp[nm][j] = min(dp[nm][j], dp[mask][i] + dist[i][j])
        full = (1 << n) - 1
        return min(dp[full][i] + dist[i][0] for i in range(1, n)) if n > 1 else 0
  11. 11

    Detect whether a delivery network is strongly connected (every hub reaches every hub).

    hard

    Run a BFS or DFS from any node on the graph, then again on the reversed graph; the network is strongly connected if both reach all nodes. O(V + E). Mistake: checking connectivity only on the undirected version, which accepts one-way networks where a hub cannot be reached back.

    python
    def strongly_connected(n, edges):
        fwd = [[] for _ in range(n)]
        rev = [[] for _ in range(n)]
        for u, v in edges:
            fwd[u].append(v)
            rev[v].append(u)
        def reach(adj):
            seen = {0}
            st = [0]
            while st:
                u = st.pop()
                for v in adj[u]:
                    if v not in seen:
                        seen.add(v)
                        st.append(v)
            return len(seen) == n
        return reach(fwd) and reach(rev)

Frequently asked questions

Which algorithms are most useful for Delhivery-style problems?

Dijkstra and BFS, interval merging, heaps for k nearest, greedy pairing, knapsack-style DP and SQL window functions.

Do I need to know travelling salesman?

You are unlikely to be asked for an exact large-scale solution, but knowing that the problem is NP-hard and having a small bitmask solution plus a nearest-neighbour heuristic prepares you for follow-ups.

Is SQL part of the coding round?

It is plausible for data-heavy roles, so practise joins, grouping and ranking.

Are these actual Delhivery test questions?

No, they are practice problems written in the style of logistics topics.

Which language should I use?

Use the language you code fastest in; Python is concise, and Java is fine if you know PriorityQueue and HashMap well.

Related guides

More in Company Interview Questions

See all in this section