Swiggy Coding Round Questions with Solutions
Last updated 2026-11-19
Swiggy runs a three-sided marketplace of customers, restaurants and riders, and the problems that come up in reports from its interviews tend to look like that business: assign riders, group orders, find the nearest kitchen, settle a shared bill. The eleven tasks here follow those themes, with a mix of algorithm questions and one small class-design exercise.
All of them are original practice problems and not a record of what any candidate was asked. Pair this page with Swiggy interview questions for the technical and HR side, and the low-level design interview guide before the design round.
Algorithm round versus machine-coding round
Accounts of Swiggy interviews describe an algorithmic conversation where you talk through the approach, code it and dry-run it, and a separate design-oriented session where a working, extensible program matters more than a clever trick. The first rewards pattern recognition: heaps for allocation, BFS for grids, monotonic stacks for next-greater questions. The second rewards decomposition into small classes and clear names.
For the algorithm problems below, practise saying the complexity before you write code. For the discount-rules problem, practise listing the requirements you will not build, so that the interviewer sees a deliberate scope.
Marketplace ideas worth knowing
- Allocation is usually a heap problem: the next free rider or the nearest restaurant is a priority queue question.
- Geography is usually a grid or a hash by cell. Learn both, because the follow-up asks what changes when the map is huge.
- Fairness and cost show up as greedy choices. Be ready to defend why the greedy choice is safe.
Hiring status
This site carries no sourced hiring statement for Swiggy. Open roles are on the company's careers site at careers.swiggy.com. The rounds described here come from candidate-reported accounts and may no longer match.
Swiggy Coding Round Questions with Solutions: questions with worked answers
1 How many riders are needed to cover a list of delivery time windows?
mediumSort the windows by start. Keep a min-heap of the end times of busy riders. When a new window starts at or after the earliest end, that rider is free, so reuse them; otherwise add a rider. The heap size at the end is the answer. O(n log n) time, O(n) space. Common mistakes: using strictly-less when one window may start exactly as another ends, and counting the maximum overlap by scanning all pairs.
pythonimport heapq def riders_needed(windows): busy = [] for start, end in sorted(windows): if busy and busy[0] <= start: heapq.heapreplace(busy, end) else: heapq.heappush(busy, end) return len(busy)javaimport java.util.*; class Riders { static int needed(int[][] w) { Arrays.sort(w, (a, b) -> Integer.compare(a[0], b[0])); PriorityQueue<Integer> busy = new PriorityQueue<>(); for (int[] x : w) { if (!busy.isEmpty() && busy.peek() <= x[0]) busy.poll(); busy.add(x[1]); } return busy.size(); } }2 Group orders into batches by pickup location using a coarse grid.
easyDivide the plane into square cells of a chosen side and hash each order by its cell coordinates. Orders in the same cell are batch candidates. One pass, O(n) time and space. Use floor division so negative coordinates land in the right cell. Common mistakes: integer truncation toward zero for negatives, and forgetting that two orders just across a cell boundary are close; a real system also checks the eight neighbouring cells.
pythonfrom collections import defaultdict def batch_by_cell(orders, side): cells = defaultdict(list) for oid, x, y in orders: cells[(x // side, y // side)].append(oid) return sorted(sorted(v) for v in cells.values())javaimport java.util.*; class Batch { static Collection<List<Integer>> byCell(int[][] orders, int side) { Map<String, List<Integer>> cells = new TreeMap<>(); for (int[] o : orders) { String key = Math.floorDiv(o[1], side) + "," + Math.floorDiv(o[2], side); cells.computeIfAbsent(key, k -> new ArrayList<>()).add(o[0]); } return cells.values(); } }3 Return the k restaurants closest to a customer.
mediumKeep a max-heap of size k keyed by squared distance, so the farthest of the current best sits on top and is dropped when a nearer one arrives. Squared distance avoids square roots and keeps integers exact. O(n log k) time, O(k) space. Common mistakes: sorting everything for a small k, and using a min-heap, which keeps the wrong end.
pythonimport heapq def nearest(restaurants, ux, uy, k): heap = [] for name, x, y in restaurants: d = (x - ux) ** 2 + (y - uy) ** 2 heapq.heappush(heap, (-d, name)) if len(heap) > k: heapq.heappop(heap) return [name for _, name in sorted(heap, reverse=True)]javaimport java.util.*; class Nearest { static List<Integer> closest(int[][] pts, int ux, int uy, int k) { PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Long.compare(b[0], a[0])); for (int i = 0; i < pts.length; i++) { int dx = pts[i][0] - ux, dy = pts[i][1] - uy; heap.add(new int[]{dx * dx + dy * dy, i}); if (heap.size() > k) heap.poll(); } LinkedList<Integer> out = new LinkedList<>(); while (!heap.isEmpty()) out.addFirst(heap.poll()[1]); return out; } }4 A rider can finish one order per time slot, and each order has a deadline slot and a tip. Maximise the total tip.
hardSort orders by deadline. Walk through them, pushing each tip into a min-heap. If the heap holds more orders than the current deadline allows slots for, drop the smallest tip. The heap sum is the best total. O(n log n) time, O(n) space. Common mistakes: sorting by tip alone and placing orders greedily into the latest free slot with an O(n^2) scan, and forgetting that a dropped order may not be the one just added.
pythonimport heapq def best_tips(orders): kept = [] for deadline, tip in sorted(orders): heapq.heappush(kept, tip) if len(kept) > deadline: heapq.heappop(kept) return sum(kept)javaimport java.util.*; class Tips { static long best(int[][] orders) { Arrays.sort(orders, (a, b) -> Integer.compare(a[0], b[0])); PriorityQueue<Integer> kept = new PriorityQueue<>(); for (int[] o : orders) { kept.add(o[1]); if (kept.size() > o[0]) kept.poll(); } long sum = 0; for (int t : kept) sum += t; return sum; } }5 Find the fewest steps for a rider to cross a city grid where some cells are blocked.
mediumBreadth-first search from the start, moving in four directions and marking cells visited when they are enqueued. The first time the target is dequeued, its distance is the shortest. O(rows*cols) time and space. Common mistakes: marking visited on dequeue, which lets a cell enter the queue many times, and not handling a blocked start or target.
pythonfrom collections import deque def shortest(grid, start, goal): if grid[start[0]][start[1]] or grid[goal[0]][goal[1]]: return -1 rows, cols = len(grid), len(grid[0]) seen = {start} queue = deque([(start, 0)]) while queue: (r, c), d = queue.popleft() if (r, c) == goal: return d for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and not grid[nr][nc] and (nr, nc) not in seen: seen.add((nr, nc)) queue.append(((nr, nc), d + 1)) return -1javaimport java.util.*; class Grid { static int shortest(int[][] g, int sr, int sc, int tr, int tc) { if (g[sr][sc] == 1 || g[tr][tc] == 1) return -1; int R = g.length, C = g[0].length; boolean[][] seen = new boolean[R][C]; ArrayDeque<int[]> q = new ArrayDeque<>(); q.add(new int[]{sr, sc, 0}); seen[sr][sc] = true; int[] dr = {1, -1, 0, 0}, dc = {0, 0, 1, -1}; while (!q.isEmpty()) { int[] cur = q.poll(); if (cur[0] == tr && cur[1] == tc) return cur[2]; for (int k = 0; k < 4; k++) { int nr = cur[0] + dr[k], nc = cur[1] + dc[k]; if (nr >= 0 && nr < R && nc >= 0 && nc < C && g[nr][nc] == 0 && !seen[nr][nc]) { seen[nr][nc] = true; q.add(new int[]{nr, nc, cur[2] + 1}); } } } return -1; } }6 For each hour, how many hours until order demand next rises above it?
mediumA monotonic stack of indices whose demand has not yet been beaten. When a new hour has higher demand than the hour on top, pop it and record the gap. Whatever remains at the end gets zero. Each index is pushed and popped once, so O(n) time, O(n) space. Common mistakes: pushing values instead of indices, which loses the distance, and using greater-or-equal when the problem says strictly higher.
pythondef hours_to_rise(demand): out = [0] * len(demand) stack = [] for i, v in enumerate(demand): while stack and demand[stack[-1]] < v: j = stack.pop() out[j] = i - j stack.append(i) return outjavaimport java.util.*; class Demand { static int[] hoursToRise(int[] d) { int[] out = new int[d.length]; Deque<Integer> st = new ArrayDeque<>(); for (int i = 0; i < d.length; i++) { while (!st.isEmpty() && d[st.peek()] < d[i]) { int j = st.pop(); out[j] = i - j; } st.push(i); } return out; } }7 Count the ways to hit a free-delivery threshold exactly using add-on items at given prices.
mediumThis is the combinations form of coin change. Let ways[a] be the number of unordered baskets summing to a. Loop over items in the outer loop and amounts in the inner loop, adding ways[a - price]. Putting items outside counts each basket once. O(items * target) time, O(target) space. Common mistakes: swapping the loops, which counts orderings as distinct baskets, and not seeding ways[0] with 1.
pythondef basket_ways(prices, target): ways = [0] * (target + 1) ways[0] = 1 for p in prices: for a in range(p, target + 1): ways[a] += ways[a - p] return ways[target]javaclass Baskets { static long ways(int[] prices, int target) { long[] ways = new long[target + 1]; ways[0] = 1; for (int p : prices) for (int a = p; a <= target; a++) ways[a] += ways[a - p]; return ways[target]; } }8 Build restaurant-name autocomplete that returns up to three alphabetical matches for a prefix.
mediumInsert every name into a trie whose children are kept in sorted order. To answer a prefix, walk down to its node, then run a depth-first traversal that visits children alphabetically and stops after three words. Insert is O(L), a query is O(L + output size explored). Common mistakes: forgetting the end-of-word flag so that a name that is itself a prefix is skipped, and collecting all matches before cutting to three.
pythonclass Autocomplete: def __init__(self, names): self.root = {} for n in names: node = self.root for ch in n: node = node.setdefault(ch, {}) node['$'] = True def suggest(self, prefix, limit=3): node = self.root for ch in prefix: if ch not in node: return [] node = node[ch] out = [] def walk(cur, path): if len(out) >= limit: return if '$' in cur: out.append(prefix + path) for ch in sorted(k for k in cur if k != '$'): walk(cur[ch], path + ch) walk(node, '') return outjavaimport java.util.*; class Autocomplete { static class Node { TreeMap<Character, Node> kids = new TreeMap<>(); boolean end; } private final Node root = new Node(); void add(String s) { Node n = root; for (char c : s.toCharArray()) n = n.kids.computeIfAbsent(c, k -> new Node()); n.end = true; } List<String> suggest(String prefix, int limit) { Node n = root; for (char c : prefix.toCharArray()) { n = n.kids.get(c); if (n == null) return new ArrayList<>(); } List<String> out = new ArrayList<>(); walk(n, new StringBuilder(prefix), out, limit); return out; } private void walk(Node n, StringBuilder sb, List<String> out, int limit) { if (out.size() >= limit) return; if (n.end) out.add(sb.toString()); for (Map.Entry<Character, Node> e : n.kids.entrySet()) { sb.append(e.getKey()); walk(e.getValue(), sb, out, limit); sb.deleteCharAt(sb.length() - 1); } } }9 Find the longest stretch of minutes in which a rider was active, allowing at most k idle minutes inside it.
mediumSlide a window over the 0/1 activity array and count idle minutes (zeros) inside. When the count exceeds k, advance the left edge until it is back to k. Track the widest window. O(n) time, O(1) space. Common mistakes: resetting the window to empty when the budget is exceeded, and using a nested loop.
pythondef longest_active(minutes, k): best = idle = left = 0 for right, m in enumerate(minutes): if m == 0: idle += 1 while idle > k: if minutes[left] == 0: idle -= 1 left += 1 best = max(best, right - left + 1) return bestjavaclass Active { static int longest(int[] m, int k) { int best = 0, idle = 0, left = 0; for (int r = 0; r < m.length; r++) { if (m[r] == 0) idle++; while (idle > k) { if (m[left] == 0) idle--; left++; } best = Math.max(best, r - left + 1); } return best; } }10 Settle a group's shared expenses using at most n-1 payments.
hardCompute each person's net balance: paid minus owed. Put creditors in a max-heap and debtors in another. Repeatedly match the largest debtor with the largest creditor, transfer the smaller of the two amounts, and push back whoever still has a balance. Every transfer clears at least one person, so there are at most n-1 transfers. O(n log n). Common mistakes: claiming it gives the true minimum number of payments (that is NP-hard in general), and floating-point balances.
pythonimport heapq def settle(net): pos = [(-v, p) for p, v in net.items() if v > 0] neg = [(v, p) for p, v in net.items() if v < 0] heapq.heapify(pos) heapq.heapify(neg) moves = [] while pos and neg: credit, c = heapq.heappop(pos) debt, d = heapq.heappop(neg) credit = -credit debt = -debt pay = min(credit, debt) moves.append((d, c, pay)) if credit > pay: heapq.heappush(pos, (-(credit - pay), c)) if debt > pay: heapq.heappush(neg, (-(debt - pay), d)) return movesjavaimport java.util.*; class Settle { static List<String> run(Map<String, Long> net) { PriorityQueue<Map.Entry<String, Long>> cred = new PriorityQueue<>((a, b) -> Long.compare(b.getValue(), a.getValue())); PriorityQueue<Map.Entry<String, Long>> debt = new PriorityQueue<>((a, b) -> Long.compare(a.getValue(), b.getValue())); for (Map.Entry<String, Long> e : net.entrySet()) { if (e.getValue() > 0) cred.add(new AbstractMap.SimpleEntry<>(e)); else if (e.getValue() < 0) debt.add(new AbstractMap.SimpleEntry<>(e)); } List<String> moves = new ArrayList<>(); while (!cred.isEmpty() && !debt.isEmpty()) { Map.Entry<String, Long> c = cred.poll(), d = debt.poll(); long pay = Math.min(c.getValue(), -d.getValue()); moves.add(d.getKey() + "->" + c.getKey() + ":" + pay); if (c.getValue() > pay) { c.setValue(c.getValue() - pay); cred.add(c); } if (-d.getValue() > pay) { d.setValue(d.getValue() + pay); debt.add(d); } } return moves; } }11 Machine-coding exercise: apply the best of several coupon rules to a cart.
mediumModel each rule behind one small interface that takes a cart total and returns a discount. A flat rule has a minimum spend, a percentage rule has a cap. The cart asks every rule and keeps the largest discount, so adding a rule means adding a class and nothing else. Each rule is O(1), so the cart is O(rules). Common mistakes: one big if-else on coupon names, letting a discount exceed the total, and mixing rupees and percentages in one field.
pythonclass Flat: def __init__(self, off, min_spend): self.off, self.min_spend = off, min_spend def discount(self, total): return self.off if total >= self.min_spend else 0 class Percent: def __init__(self, pct, cap): self.pct, self.cap = pct, cap def discount(self, total): return min(total * self.pct // 100, self.cap) def payable(total, rules): best = max((r.discount(total) for r in rules), default=0) return total - min(best, total)javaimport java.util.*; interface Rule { long discount(long total); } class Flat implements Rule { private final long off, min; Flat(long off, long min) { this.off = off; this.min = min; } public long discount(long total) { return total >= min ? off : 0; } } class Percent implements Rule { private final long pct, cap; Percent(long pct, long cap) { this.pct = pct; this.cap = cap; } public long discount(long total) { return Math.min(total * pct / 100, cap); } } class Cart { static long payable(long total, List<Rule> rules) { long best = 0; for (Rule r : rules) best = Math.max(best, r.discount(total)); return total - Math.min(best, total); } }
Frequently asked questions
What topics should I prioritise for a Swiggy coding round?
Reports point to heaps, graphs and grids, intervals, hashing and dynamic programming, along with one design-style task. Focus on writing correct code for medium problems at a steady pace, then add the design exercise.
Is the machine-coding round tested on a platform with test cases?
Candidate accounts vary. Some describe building a small system and demoing it, others describe an automated check. Plan for both by running your own tests on a few edge cases before submitting.
Why is the settle-up answer not a true minimum?
Finding the minimum number of payments reduces to a partitioning problem that is NP-hard in general. The heap approach gives a valid settlement with at most n-1 payments, which is what most interviews accept if you state the limitation.
How should I split my practice time?
Spend most of it on timed algorithm problems and reserve a few sessions for building a small multi-class program in under ninety minutes without help.
Where do I check for Swiggy openings?
On the company's careers page at careers.swiggy.com. The process notes here are candidate-reported and not an official statement.
Sources
Related guides
More in Company Interview Questions
- Swiggy Interview Questions and Answers
- Synopsys Coding Round Questions with Solutions
- Synopsys Interview Questions and Answers for India R&D Software Roles
- Target Coding Round Questions
- Target Interview Questions with Answers
- TCS Coding Round Questions with Solutions
- TCS Interview Questions for Freshers
- Tech Mahindra Coding Round Questions with Solutions
- Tech Mahindra Interview Questions for Freshers
- Texas Instruments Coding Round Questions with Solutions
- Texas Instruments Interview Questions and Answers for India Embedded Roles
- Thoughtworks Coding Round Questions