Autocoder

Flipkart Coding Round Questions with Solutions

Last updated 2026-11-19

Flipkart is a marketplace with warehouses, delivery fleets, a search box and flash-sale days, which gives its problems a recognisable backbone: stock that must not oversell, parcels moving through a network, and a catalogue that has to be ranked and searched quickly. The early-careers GRiD route is listed as a proctored coding test, and candidate write-ups describe later interviews that combine DSA with a machine-coding build.

The ten practice problems below follow a parcel from shelf to doorstep: reserving stock, walking a warehouse floor, suggesting search terms, pricing bundles, packing cartons, routing through hubs and balancing truck loads. They are original exercises, not past papers. Pair them with Flipkart interview questions and the DSA round guide.

How a Flipkart-style round tends to unfold

Listings for the GRiD challenge describe a roughly 90-minute proctored coding assessment. In the interviews that follow, reports say the first correct answer is usually a starting point: expect a push for a better complexity, then questions about edge cases, then a dry run on your own code.

For the machine-coding round the habit to build is vertical slicing. Get one flow working end to end, such as reserve then confirm, before polishing class hierarchies. Problem 1 below is sized to practise exactly that in about forty minutes. More structure advice sits in low level design interview questions.

Hiring status

Current openings and sourced news are collected at Flipkart hiring; apply through the company's own careers site. Round formats described here are candidate-reported and can change between cycles.

Flipkart Coding Round Questions with Solutions: questions with worked answers

  1. 1

    Machine coding: a flash-sale inventory that reserves stock for a short time before payment.

    hard

    Keep stock per SKU, a table of active holds, and a min-heap of hold expiry times. A reserve call first releases every hold whose expiry has passed, then checks stock, decrements it and issues a hold id. Confirming removes the hold so its stock is never returned. Each call is O(log h) for h live holds. The typical failure is overselling: checking stock and decrementing in separate steps without a lock, so in real code guard the whole reserve with one mutex per SKU.

    python
    import heapq
    
    class Inventory:
        def __init__(self, stock):
            self.stock, self.holds, self.expiry, self.nxt = dict(stock), {}, [], 1
    
        def _expire(self, now):
            while self.expiry and self.expiry[0][0] <= now:
                _, hid = heapq.heappop(self.expiry)
                hold = self.holds.pop(hid, None)
                if hold:
                    self.stock[hold[0]] += hold[1]
    
        def reserve(self, sku, qty, now, ttl):
            self._expire(now)
            if self.stock.get(sku, 0) < qty:
                return None
            self.stock[sku] -= qty
            hid, self.nxt = self.nxt, self.nxt + 1
            self.holds[hid] = (sku, qty)
            heapq.heappush(self.expiry, (now + ttl, hid))
            return hid
    
        def confirm(self, hid, now):
            self._expire(now)
            return self.holds.pop(hid, None) is not None
    
        def available(self, sku, now):
            self._expire(now)
            return self.stock.get(sku, 0)
    java
    import java.util.*;
    
    class Inventory {
        private final Map<String, Integer> stock;
        private final Map<Integer, Object[]> holds = new HashMap<>();   // {sku, qty}
        private final PriorityQueue<long[]> expiry = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));
        private int next = 1;
        Inventory(Map<String, Integer> s) { stock = new HashMap<>(s); }
        private void expire(long now) {
            while (!expiry.isEmpty() && expiry.peek()[0] <= now) {
                Object[] h = holds.remove((int) expiry.poll()[1]);
                if (h != null) stock.merge((String) h[0], (Integer) h[1], Integer::sum);
            }
        }
        synchronized Integer reserve(String sku, int qty, long now, long ttl) {
            expire(now);
            if (stock.getOrDefault(sku, 0) < qty) return null;
            stock.merge(sku, -qty, Integer::sum);
            int id = next++;
            holds.put(id, new Object[]{sku, qty});
            expiry.add(new long[]{now + ttl, id});
            return id;
        }
        synchronized boolean confirm(int id, long now) {
            expire(now);
            return holds.remove(id) != null;
        }
    }
  2. 2

    Fewest steps for a picker to walk from the warehouse door to a shelf, avoiding racks.

    medium

    Treat the floor as a grid where 1 is a rack and 0 is walkable. Breadth-first search from the door explores cells in order of distance, so the first time you reach the shelf you have the minimum. Mark cells visited when you enqueue them, not when you dequeue, or the queue fills with duplicates. O(rows x cols) time and space. Return -1 when the shelf is walled off, and check that the start itself is not a rack.

    python
    from collections import deque
    
    def shortest_walk(grid, src, dst):
        R, C = len(grid), len(grid[0])
        if grid[src[0]][src[1]] or grid[dst[0]][dst[1]]:
            return -1
        seen = {tuple(src)}
        q = deque([(src[0], src[1], 0)])
        while q:
            r, c, d = q.popleft()
            if (r, c) == tuple(dst):
                return d
            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nr, nc = r + dr, c + dc
                if 0 <= nr < R and 0 <= nc < C and not grid[nr][nc] and (nr, nc) not in seen:
                    seen.add((nr, nc))
                    q.append((nr, nc, d + 1))
        return -1
    java
    import java.util.*;
    
    static int shortestWalk(int[][] grid, int[] src, int[] dst) {
        int R = grid.length, C = grid[0].length;
        if (grid[src[0]][src[1]] == 1 || grid[dst[0]][dst[1]] == 1) return -1;
        boolean[][] seen = new boolean[R][C];
        ArrayDeque<int[]> q = new ArrayDeque<>();
        q.add(new int[]{src[0], src[1], 0});
        seen[src[0]][src[1]] = true;
        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        while (!q.isEmpty()) {
            int[] cur = q.poll();
            if (cur[0] == dst[0] && cur[1] == dst[1]) return cur[2];
            for (int[] d : dirs) {
                int nr = cur[0] + d[0], nc = cur[1] + d[1];
                if (nr >= 0 && nr < R && nc >= 0 && nc < C && grid[nr][nc] == 0 && !seen[nr][nc]) {
                    seen[nr][nc] = true;
                    q.add(new int[]{nr, nc, cur[2] + 1});
                }
            }
        }
        return -1;
    }
  3. 3

    Search-box suggestions: return the three most popular catalogue terms for a typed prefix.

    hard

    Build a trie and let every node remember the best three terms that pass through it, ordered by popularity and then alphabetically. Insertion appends the term to each node on its path, re-sorts that tiny list and trims it to three. A query walks the prefix and returns the stored list directly. Insert is O(L x 3 log 3), query O(L), where L is the prefix length. Searching the whole subtree at query time is the slow version that gets challenged in follow-ups.

    python
    class Node:
        def __init__(self):
            self.kids, self.top = {}, []
    
    class Suggest:
        def __init__(self):
            self.root, self.freq = Node(), {}
    
        def add(self, term, count):
            self.freq[term] = count
            node = self.root
            for ch in term:
                node = node.kids.setdefault(ch, Node())
                node.top.append(term)
                node.top.sort(key=lambda t: (-self.freq[t], t))
                del node.top[3:]
    
        def suggest(self, prefix):
            node = self.root
            for ch in prefix:
                node = node.kids.get(ch)
                if node is None:
                    return []
            return list(node.top)
    java
    import java.util.*;
    
    class Suggest {
        private static class Node {
            Map<Character, Node> kids = new HashMap<>();
            List<String> top = new ArrayList<>();
        }
        private final Node root = new Node();
        private final Map<String, Integer> freq = new HashMap<>();
        void add(String term, int count) {
            freq.put(term, count);
            Node n = root;
            for (char c : term.toCharArray()) {
                n = n.kids.computeIfAbsent(c, x -> new Node());
                n.top.add(term);
                n.top.sort((a, b) -> {
                    int byCount = Integer.compare(freq.get(b), freq.get(a));
                    return byCount != 0 ? byCount : a.compareTo(b);
                });
                if (n.top.size() > 3) n.top.remove(3);
            }
        }
        List<String> suggest(String prefix) {
            Node n = root;
            for (char c : prefix.toCharArray()) {
                n = n.kids.get(c);
                if (n == null) return List.of();
            }
            return n.top;
        }
    }
  4. 4

    Cheapest way to buy exactly n units when the store sells fixed-size packs at set prices.

    medium

    This is unbounded knapsack with exact fill. Let dp[i] be the lowest price for i units, with dp[0] = 0. For each i try every pack no larger than i and take the minimum of dp[i - size] + price. Cost O(n x packs). Return -1 if dp[n] was never reached. Greedy by best price per unit fails: with packs of 1, 3 and 5 units, 6 units is cheaper as 5 plus 1 than as 3 plus 3 when the five-pack is heavily discounted.

    python
    def min_cost(n, packs):                 # packs: (size, price)
        INF = float('inf')
        dp = [0] + [INF] * n
        for i in range(1, n + 1):
            for size, price in packs:
                if size <= i and dp[i - size] + price < dp[i]:
                    dp[i] = dp[i - size] + price
        return -1 if dp[n] == INF else dp[n]
    java
    static int minCost(int n, int[][] packs) {            // {size, price}
        int INF = Integer.MAX_VALUE / 2;
        int[] dp = new int[n + 1];
        java.util.Arrays.fill(dp, INF);
        dp[0] = 0;
        for (int i = 1; i <= n; i++)
            for (int[] p : packs)
                if (p[0] <= i && dp[i - p[0]] + p[1] < dp[i]) dp[i] = dp[i - p[0]] + p[1];
        return dp[n] >= INF ? -1 : dp[n];
    }
  5. 5

    Pack parcels into the fewest cartons when each carton holds at most two parcels and a weight limit.

    medium

    Sort the weights, then pair the heaviest remaining parcel with the lightest. If they fit together, both go in one carton; otherwise the heavy one travels alone. Either way the heavy parcel uses a carton, so advance the right pointer every round and the left pointer only on a successful pairing. O(n log n) for sorting, linear after. Pairing the two lightest first looks natural but strands heavy parcels and uses more cartons.

    python
    def min_cartons(weights, limit):
        w = sorted(weights)
        i, j, cartons = 0, len(w) - 1, 0
        while i <= j:
            if w[i] + w[j] <= limit:
                i += 1
            j -= 1
            cartons += 1
        return cartons
    java
    static int minCartons(int[] weights, int limit) {
        int[] w = weights.clone();
        java.util.Arrays.sort(w);
        int i = 0, j = w.length - 1, cartons = 0;
        while (i <= j) {
            if (w[i] + w[j] <= limit) i++;
            j--;
            cartons++;
        }
        return cartons;
    }
  6. 6

    Cheapest shipping price from one hub to another using at most K intermediate hubs.

    hard

    Run Bellman-Ford for K+1 rounds, but relax each round against a copy of the previous round's distances so one round adds exactly one leg. After the rounds, read the destination's distance. Time O((K+1) x E), space O(V). Plain Dijkstra can return a cheaper route that uses too many legs, and relaxing in place lets a single round chain several edges, which silently breaks the hop limit.

    python
    def cheapest(n, edges, src, dst, k):
        INF = float('inf')
        dist = [INF] * n
        dist[src] = 0
        for _ in range(k + 1):
            nxt = dist[:]
            for u, v, w in edges:
                if dist[u] + w < nxt[v]:
                    nxt[v] = dist[u] + w
            dist = nxt
        return -1 if dist[dst] == INF else dist[dst]
    java
    static int cheapest(int n, int[][] edges, int src, int dst, int k) {
        int INF = Integer.MAX_VALUE / 2;
        int[] dist = new int[n];
        java.util.Arrays.fill(dist, INF);
        dist[src] = 0;
        for (int round = 0; round <= k; round++) {
            int[] nxt = dist.clone();
            for (int[] e : edges)
                if (dist[e[0]] + e[2] < nxt[e[1]]) nxt[e[1]] = dist[e[0]] + e[2];
            dist = nxt;
        }
        return dist[dst] >= INF ? -1 : dist[dst];
    }
  7. 7

    Find the smallest positive order number missing from a batch, in O(n) time and O(1) extra space.

    hard

    Use the array as its own hash table. For every value v between 1 and n, swap it to index v-1, repeating until the slot already holds the right value or the value is out of range. A final scan returns the first index i whose value is not i+1, or n+1 if all are in place. Each swap fixes one element for good, so O(n). Writing a[i], a[a[i]-1] = a[a[i]-1], a[i] in Python scrambles because the right side's index is evaluated after the first assignment, so use a temporary index.

    python
    def first_missing(a):
        n = len(a)
        for i in range(n):
            while 1 <= a[i] <= n and a[a[i] - 1] != a[i]:
                j = a[i] - 1
                a[i], a[j] = a[j], a[i]
        for i in range(n):
            if a[i] != i + 1:
                return i + 1
        return n + 1
    java
    static int firstMissing(int[] a) {
        int n = a.length;
        for (int i = 0; i < n; i++) {
            while (a[i] >= 1 && a[i] <= n && a[a[i] - 1] != a[i]) {
                int j = a[i] - 1;
                int t = a[i]; a[i] = a[j]; a[j] = t;
            }
        }
        for (int i = 0; i < n; i++) if (a[i] != i + 1) return i + 1;
        return n + 1;
    }
  8. 8

    Split a line of parcels into k consecutive truck loads so the heaviest load is as light as possible.

    hard

    Binary search the answer. The smallest feasible cap is the heaviest single parcel and the largest is the total. For a candidate cap, greedily fill a truck until the next parcel would exceed it and count the trucks used; if the count is at most k the cap is feasible, so search lower. O(n log(sum)) time, O(1) space. Starting the lower bound at 0 or 1 wastes iterations and can accept a cap that cannot carry the heaviest parcel.

    python
    def min_max_load(weights, k):
        def trucks(cap):
            count, cur = 1, 0
            for x in weights:
                if cur + x > cap:
                    count, cur = count + 1, 0
                cur += x
            return count
        lo, hi = max(weights), sum(weights)
        while lo < hi:
            mid = (lo + hi) // 2
            if trucks(mid) <= k:
                hi = mid
            else:
                lo = mid + 1
        return lo
    java
    static int minMaxLoad(int[] w, int k) {
        int lo = 0, hi = 0;
        for (int x : w) { lo = Math.max(lo, x); hi += x; }
        while (lo < hi) {
            int mid = (lo + hi) / 2, trucks = 1, cur = 0;
            for (int x : w) {
                if (cur + x > mid) { trucks++; cur = 0; }
                cur += x;
            }
            if (trucks <= k) hi = mid; else lo = mid + 1;
        }
        return lo;
    }
  9. 9

    Fewest relay jumps to reach the last hub when each hub lets you jump up to a given distance.

    medium

    Sweep once while tracking two numbers: the end of the range reachable with the current number of jumps, and the farthest index reachable with one more. When the sweep reaches the current end, a jump must be taken, so increment the counter and extend the end to the farthest point. O(n) time, O(1) space. A full DP over every start is O(n squared) and unnecessary. Assume the last hub is reachable, or add a check that far never stalls behind i.

    python
    def min_hops(reach):
        hops = end = far = 0
        for i in range(len(reach) - 1):
            far = max(far, i + reach[i])
            if i == end:
                hops += 1
                end = far
        return hops
    java
    static int minHops(int[] reach) {
        int hops = 0, end = 0, far = 0;
        for (int i = 0; i < reach.length - 1; i++) {
            far = Math.max(far, i + reach[i]);
            if (i == end) { hops++; end = far; }
        }
        return hops;
    }
  10. 10

    Rank search results by rating, then lower price, keeping the original order for exact ties.

    easy

    Build a composite sort key: negative rating so higher comes first, then price ascending. Both Python's sorted and Java's List.sort on objects are stable, so items with identical keys keep their incoming relevance order without an extra index column. O(n log n). Sorting twice in the wrong order, price last, destroys the rating grouping; if you must sort in passes, sort by the least important key first.

    python
    def rank_results(items):               # (sku, rating, price)
        return sorted(items, key=lambda it: (-it[1], it[2]))
    java
    import java.util.*;
    
    record Item(String sku, double rating, int price) {}
    
    static void rankResults(List<Item> items) {
        items.sort(Comparator.comparingDouble((Item it) -> -it.rating()).thenComparingInt(Item::price));
    }

Frequently asked questions

Is the Flipkart GRiD test the same as the interview coding rounds?

No. GRiD is listed as a proctored online challenge for early careers, while the later rounds are interviews where you talk through your solution live. Prepare for both styles.

How much object-oriented design should go into a machine-coding answer?

Enough that a new rule, such as another reservation policy, fits without editing existing methods. Two or three focused classes with a short driver usually beat a deep hierarchy.

What is the quickest way to improve at graph problems like the hub routing one?

Redraw the graph on paper for each practice problem and trace your algorithm's state after every step. Most graph bugs are visible in that trace before you run any code.

Can I use a built-in sort or heap in the test?

Usually yes, since the languages offered ship them. State the complexity of the library call you rely on, and write your own only if the question explicitly forbids built-ins.

Sources

Related guides

More in Company Interview Questions

See all in this section