Autocoder

Meesho Coding Round Questions with Solutions

Last updated 2026-11-19

Meesho connects small resellers, mostly outside the big metros, with suppliers, and a large share of its orders are cash on delivery. Candidate write-ups mention an online test of about three medium-to-hard DSA problems in roughly 90 minutes, followed by a machine-coding round. Problems that fit that world involve thin margins, wide pincode coverage, referral networks and orders that can fail at the doorstep.

The ten exercises here use those themes. They are practice problems written for this page, not recalled questions. Read Meesho interview questions for design and HR preparation, and the DSA round guide for pacing a timed paper.

Splitting 90 minutes across three problems

Read all three statements before writing anything and rank them by how sure you are of the approach. Finish the most certain one cleanly, then the second. For the last, aim for the best partial solution that passes the sample, since many judge platforms award marks per test case; confirm that rule on your own platform before relying on it.

Medium-to-hard in this setting usually means a familiar pattern with a twist: a monotonic stack, prefix sums with hashing, a greedy over sorted intervals or a small state machine. Problems 1, 3 and 8 below are the best drill for spotting such twists quickly.

Hiring status

Sourced items are gathered at Meesho hiring, and current roles sit on the careers page at meesho.io/jobs. The round structure above is candidate-reported and could change.

Meesho Coding Round Questions with Solutions: questions with worked answers

  1. 1

    Maximum resale profit from a price list when you must wait one day after every sale.

    hard

    Track three running values per day: the best balance while holding stock, the best balance having just sold, and the best balance resting with nothing held. Holding comes from either keeping stock or buying out of rest; selling comes from holding plus today's price; resting inherits yesterday's sold or rest. Answer is the larger of sold and rest at the end. O(n) time, O(1) space. Letting a buy happen straight after a sale ignores the cooldown and overstates profit.

    python
    def max_profit_cooldown(prices):
        hold, sold, rest = float('-inf'), 0, 0
        for p in prices:
            prev_sold = sold
            sold = hold + p
            hold = max(hold, rest - p)
            rest = max(rest, prev_sold)
        return max(sold, rest)
    java
    static int maxProfitCooldown(int[] prices) {
        int hold = Integer.MIN_VALUE / 2, sold = 0, rest = 0;
        for (int p : prices) {
            int prevSold = sold;
            sold = hold + p;
            hold = Math.max(hold, rest - p);
            rest = Math.max(rest, prevSold);
        }
        return Math.max(sold, rest);
    }
  2. 2

    Fewest delivery hubs needed so that every pincode range contains at least one hub.

    medium

    Sort the ranges by their right end. Place a hub at the end of the first range, then skip every range that starts at or before that hub, since it is already covered; the first range that starts after it needs a new hub at its own end. One sort plus one pass, O(n log n). Sorting by the left end is the common error, because a long early range then forces poor hub placement. Be clear whether ranges are inclusive at both ends.

    python
    def min_hubs(ranges):
        hubs, last = 0, float('-inf')
        for start, end in sorted(ranges, key=lambda r: r[1]):
            if start > last:
                hubs += 1
                last = end
        return hubs
    java
    import java.util.*;
    
    static int minHubs(int[][] ranges) {
        int[][] r = ranges.clone();
        Arrays.sort(r, (a, b) -> Integer.compare(a[1], b[1]));
        int hubs = 0;
        long last = Long.MIN_VALUE;
        for (int[] x : r) {
            if (x[0] > last) { hubs++; last = x[1]; }
        }
        return hubs;
    }
  3. 3

    Count the contiguous stretches of daily payouts whose total is divisible by k.

    medium

    Take running sums modulo k. Two prefixes with the same remainder bracket a stretch whose sum is divisible by k, so before counting each new prefix, add the number of earlier prefixes with that remainder and then record it. Seed the map with remainder zero seen once for the empty prefix. O(n) time and O(k) space. In Java, the remainder of a negative sum is negative, so normalise with ((s % k) + k) % k or the counts split across two keys.

    python
    from collections import Counter
    
    def count_divisible(a, k):
        seen = Counter({0: 1})
        s = total = 0
        for x in a:
            s = (s + x) % k
            total += seen[s]
            seen[s] += 1
        return total
    java
    import java.util.*;
    
    static int countDivisible(int[] a, int k) {
        Map<Integer, Integer> seen = new HashMap<>();
        seen.put(0, 1);
        int s = 0, total = 0;
        for (int x : a) {
            s = ((s + x) % k + k) % k;
            total += seen.getOrDefault(s, 0);
            seen.merge(s, 1, Integer::sum);
        }
        return total;
    }
  4. 4

    Does a target price exist in a matrix whose rows and columns are both sorted ascending?

    medium

    Begin in the top-right corner. If the cell equals the target you are done; if it is larger, no cell below it in that column can help, so move left; if smaller, nothing to its left in that row can help, so move down. Each step discards a row or column, giving O(rows + cols) time and O(1) space. Binary-searching each row works at O(rows x log cols) but ignores the column order. Starting at top-left gives no clear direction to move.

    python
    def find_price(matrix, target):
        if not matrix or not matrix[0]:
            return False
        r, c = 0, len(matrix[0]) - 1
        while r < len(matrix) and c >= 0:
            v = matrix[r][c]
            if v == target:
                return True
            if v > target:
                c -= 1
            else:
                r += 1
        return False
    java
    static boolean findPrice(int[][] m, int target) {
        if (m.length == 0 || m[0].length == 0) return false;
        int r = 0, c = m[0].length - 1;
        while (r < m.length && c >= 0) {
            if (m[r][c] == target) return true;
            if (m[r][c] > target) c--; else r++;
        }
        return false;
    }
  5. 5

    Find the product that accounts for more than half of all page views, in constant extra space.

    easy

    Use the Boyer-Moore voting idea: keep a candidate and a counter, adopting a new candidate whenever the counter is zero, then add one for a match and subtract one otherwise. A true majority survives all the cancellations. Because the survivor is only a candidate when no majority exists, confirm it with a second counting pass. O(n) time, O(1) space. Returning the candidate without verification is the usual bug on inputs with no majority.

    python
    def majority_product(views):
        cand, cnt = None, 0
        for x in views:
            if cnt == 0:
                cand = x
            cnt += 1 if x == cand else -1
        return cand if views.count(cand) > len(views) // 2 else None
    java
    static Integer majorityProduct(int[] views) {
        int cand = 0, cnt = 0;
        for (int x : views) {
            if (cnt == 0) cand = x;
            cnt += (x == cand) ? 1 : -1;
        }
        int occ = 0;
        for (int x : views) if (x == cand) occ++;
        return occ > views.length / 2 ? cand : null;
    }
  6. 6

    Count the separate referral groups in a network given as an adjacency matrix.

    medium

    Each group is a connected component. Loop over resellers; whenever you meet one not yet visited, increase the group count and flood through everyone reachable from them with an explicit stack, marking each as seen. Every node and matrix cell is examined once, so O(n squared) for a dense matrix. A recursive DFS risks stack overflow on a long chain of referrals, which is why an explicit stack is shown. Forgetting to treat the matrix as symmetric is rarely a problem, but check that the diagonal does not affect your count.

    python
    def referral_groups(m):
        n = len(m)
        seen = [False] * n
        groups = 0
        for i in range(n):
            if seen[i]:
                continue
            groups += 1
            seen[i] = True
            stack = [i]
            while stack:
                u = stack.pop()
                for v in range(n):
                    if m[u][v] and not seen[v]:
                        seen[v] = True
                        stack.append(v)
        return groups
    java
    import java.util.*;
    
    static int referralGroups(int[][] m) {
        int n = m.length, groups = 0;
        boolean[] seen = new boolean[n];
        for (int i = 0; i < n; i++) {
            if (seen[i]) continue;
            groups++;
            seen[i] = true;
            ArrayDeque<Integer> stack = new ArrayDeque<>();
            stack.push(i);
            while (!stack.isEmpty()) {
                int u = stack.pop();
                for (int v = 0; v < n; v++)
                    if (m[u][v] == 1 && !seen[v]) { seen[v] = true; stack.push(v); }
            }
        }
        return groups;
    }
  7. 7

    Machine coding: a shopping cart whose best coupon is applied at checkout.

    medium

    Store each SKU with a price in paise and a quantity. Model every coupon as a small function that receives the cart and returns a discount in paise: a percentage above a minimum spend, or one free unit for every few bought. At checkout take the largest single discount rather than stacking, and clamp the total at zero. Adding a coupon type then needs no change to the cart. Mistakes include holding prices as floats, and putting coupon logic inside the cart so every new offer edits existing code.

    python
    class Cart:
        def __init__(self, rules=()):
            self.items, self.rules = {}, list(rules)
    
        def add(self, sku, price, qty=1):
            _, have = self.items.get(sku, (price, 0))
            self.items[sku] = (price, have + qty)
    
        def subtotal(self):
            return sum(p * q for p, q in self.items.values())
    
        def total(self):
            best = max((rule(self) for rule in self.rules), default=0)
            return max(0, self.subtotal() - best)
    
    def percent_off(pct, min_spend):
        return lambda c: c.subtotal() * pct // 100 if c.subtotal() >= min_spend else 0
    
    def every_nth_free(sku, n):
        def rule(c):
            price, qty = c.items.get(sku, (0, 0))
            return (qty // n) * price
        return rule
    java
    import java.util.*;
    
    interface Rule { long discount(Cart c); }
    
    class Cart {
        final Map<String, long[]> items = new HashMap<>();      // sku -> {price, qty}
        private final List<Rule> rules;
        Cart(Rule... rules) { this.rules = Arrays.asList(rules); }
        void add(String sku, long price, long qty) {
            items.computeIfAbsent(sku, k -> new long[]{price, 0})[1] += qty;
        }
        long subtotal() {
            long s = 0;
            for (long[] it : items.values()) s += it[0] * it[1];
            return s;
        }
        long total() {
            long best = 0;
            for (Rule r : rules) best = Math.max(best, r.discount(this));
            return Math.max(0, subtotal() - best);
        }
        static Rule percentOff(int pct, long minSpend) {
            return c -> c.subtotal() >= minSpend ? c.subtotal() * pct / 100 : 0;
        }
        static Rule everyNthFree(String sku, int n) {
            return c -> {
                long[] it = c.items.get(sku);
                return it == null ? 0 : (it[1] / n) * it[0];
            };
        }
    }
  8. 8

    Largest block of consecutive days that all had at least a given minimum sales figure, scored as days times that minimum.

    hard

    This is the largest rectangle in a histogram. Keep a stack of bars with increasing heights, each with the leftmost index it can extend to. When a shorter bar arrives, pop taller ones and compute height times width back to their start, then push the new bar with that start index. A sentinel zero at the end flushes the stack. Each bar is pushed and popped once, so O(n). Trying every pair of boundaries is O(n squared) and times out on large inputs.

    python
    def largest_block(sales):
        stack, best = [], 0                      # (start index, height)
        for i, x in enumerate(sales + [0]):
            start = i
            while stack and stack[-1][1] >= x:
                s, h = stack.pop()
                best = max(best, h * (i - s))
                start = s
            stack.append((start, x))
        return best
    java
    import java.util.*;
    
    static int largestBlock(int[] sales) {
        int n = sales.length, best = 0;
        ArrayDeque<int[]> stack = new ArrayDeque<>();      // {start, height}
        for (int i = 0; i <= n; i++) {
            int x = i < n ? sales[i] : 0, start = i;
            while (!stack.isEmpty() && stack.peek()[1] >= x) {
                int[] t = stack.pop();
                best = Math.max(best, t[1] * (i - t[0]));
                start = t[0];
            }
            stack.push(new int[]{start, x});
        }
        return best;
    }
  9. 9

    Longest run of identical variant labels you can create by changing at most k characters.

    medium

    Slide a window and keep the count of each letter and the highest count of any one letter seen inside it. A window is valid while its length minus that highest count is at most k, since the rest are the characters to change. Move the left edge only when invalid. The recorded maximum count never needs lowering when the window shrinks, because only a bigger count can improve the answer. O(n) time, O(26) space. Rebuilding the maximum from scratch after every shrink works but is slower.

    python
    from collections import Counter
    
    def longest_after_replace(s, k):
        cnt, left, best, top = Counter(), 0, 0, 0
        for right, ch in enumerate(s):
            cnt[ch] += 1
            top = max(top, cnt[ch])
            while right - left + 1 - top > k:
                cnt[s[left]] -= 1
                left += 1
            best = max(best, right - left + 1)
        return best
    java
    static int longestAfterReplace(String s, int k) {
        int[] cnt = new int[26];
        int left = 0, best = 0, top = 0;
        for (int right = 0; right < s.length(); right++) {
            top = Math.max(top, ++cnt[s.charAt(right) - 'A']);
            while (right - left + 1 - top > k) cnt[s.charAt(left++) - 'A']--;
            best = Math.max(best, right - left + 1);
        }
        return best;
    }
  10. 10

    Machine coding: an order status tracker for cash-on-delivery parcels with legal transitions and a retry limit.

    medium

    Write the allowed transitions as a table from each state to the set of states it may reach, and route every change through one method that rejects anything else. Delivery can fail and be retried, so count out-for-delivery attempts and refuse a fourth. Keep a history list for support staff. Each move is O(1). Spreading if-statements across callers is the common design flaw, since the rules then can't be read or tested in one place. Raise a clear error for an illegal move rather than ignoring it.

    python
    ALLOWED = {
        'PLACED': {'CONFIRMED', 'CANCELLED'},
        'CONFIRMED': {'SHIPPED', 'CANCELLED'},
        'SHIPPED': {'OUT_FOR_DELIVERY'},
        'OUT_FOR_DELIVERY': {'DELIVERED', 'FAILED'},
        'FAILED': {'OUT_FOR_DELIVERY', 'RETURNED'},
        'DELIVERED': set(), 'RETURNED': set(), 'CANCELLED': set(),
    }
    
    class Order:
        MAX_ATTEMPTS = 3
    
        def __init__(self):
            self.state, self.attempts, self.history = 'PLACED', 0, ['PLACED']
    
        def move(self, new):
            if new not in ALLOWED[self.state]:
                raise ValueError(f'{self.state} -> {new} not allowed')
            if new == 'OUT_FOR_DELIVERY':
                if self.attempts == self.MAX_ATTEMPTS:
                    raise ValueError('retry limit reached')
                self.attempts += 1
            self.state = new
            self.history.append(new)
    java
    import java.util.*;
    
    class Order {
        private static final Map<String, Set<String>> ALLOWED = Map.of(
            "PLACED", Set.of("CONFIRMED", "CANCELLED"),
            "CONFIRMED", Set.of("SHIPPED", "CANCELLED"),
            "SHIPPED", Set.of("OUT_FOR_DELIVERY"),
            "OUT_FOR_DELIVERY", Set.of("DELIVERED", "FAILED"),
            "FAILED", Set.of("OUT_FOR_DELIVERY", "RETURNED"),
            "DELIVERED", Set.of(), "RETURNED", Set.of(), "CANCELLED", Set.of());
        private static final int MAX_ATTEMPTS = 3;
        private String state = "PLACED";
        private int attempts = 0;
        private final List<String> history = new ArrayList<>(List.of("PLACED"));
        void move(String next) {
            if (!ALLOWED.get(state).contains(next))
                throw new IllegalStateException(state + " -> " + next + " not allowed");
            if (next.equals("OUT_FOR_DELIVERY")) {
                if (attempts == MAX_ATTEMPTS) throw new IllegalStateException("retry limit reached");
                attempts++;
            }
            state = next;
            history.add(next);
        }
    }

Frequently asked questions

Is partial credit available in the Meesho online test?

Many judge platforms score per test case, but this varies by test. Read the instructions on your own platform, and if partial scoring is unclear, aim to fully solve two problems rather than rely on it.

Which patterns should I drill most for this style of paper?

Monotonic stack, prefix sums with a hash map, sliding windows and greedy over sorted intervals. Each appears in these ten problems in a different disguise.

How do I prepare for the machine-coding round in a week?

Build the cart and the order tracker above from scratch twice, timing yourself at about ninety minutes. Focus on readable class boundaries and a short demo driver that proves the flows work.

Are floats ever acceptable for prices in a coding test?

Avoid them. Use integer paise, convert only for display, and say so aloud. It signals that you understand why rounding errors matter in commerce.

Sources

Related guides

More in Company Interview Questions

See all in this section