Swiggy Previous Year Coding Questions

Swiggy India hires software engineers through a rigorous 4–6 round process at its Bangalore headquarters. The process is distinct from many other product companies in one key way — graphs are the most tested topic, and Swiggy rebrands classic algorithmic problems into food-delivery and logistics contexts (such as "Maximum Swiggy Genie" which is Job Scheduling DP). A dedicated Machine Coding round evaluates LLD and object-oriented design. For SDE2 and above, a High Level Design round covering Swiggy's core systems (catalog, order dispatch, real-time tracking) is standard. Backend teams using Go sometimes require solutions in Golang and ask about goroutines and channels.


Hiring Process

Step 1: Resume Screening Swiggy screens for relevant backend/full-stack experience, strong DSA fundamentals, and system design exposure. Tier-1 college candidates and experienced engineers from product companies are prioritised.

Step 2: Online Assessment (HackerRank) Duration: 60–90 minutes. Contains 2–3 coding questions (Easy to Hard) and optionally 1 SQL problem. SDE-1 OA focuses on medium DSA. SDE-2 OA includes at least one hard problem, often job-scheduling or graph-based. No partial scoring — a correct solution is required.

Step 3: DSA Live Coding Round 1 60 minutes, 2 LeetCode Medium problems on Intervue or CoderPad. Candidates are expected to think aloud and produce clean, working code with edge case handling. Interviewers explicitly look for recognition of graph structure in grid problems.

Step 4: DSA Live Coding Round 2 (SDE-2+) 60 minutes. A harder DSA problem combining multiple topics (DP + graphs, or design + data structures). Often accompanied by complexity analysis discussion and follow-up variations.

Step 5: Machine Coding / LLD Round 75–120 minutes. Candidates implement a working system from a product requirement description. Graded on SOLID principles, modularity, naming, and extensibility — not just correctness. Common problems include Splitwise, Cab Booking, and Snake and Ladder.

Step 6: System Design / HLD Round (SDE-2+) 60–90 minutes covering Swiggy's actual domain systems. Interviewers expect discussion of Kafka for async events, Redis for caching, WebSockets for real-time tracking, and distributed transaction patterns. Instamart-specific design questions also appear.

Step 7: Bar Raiser / Hiring Manager Round Behavioural and architectural depth. Candidates discuss past projects, architecture trade-offs, and demonstrate product thinking. For SDE-2, expect to walk from a PRD to a TRD.

Tips: Graphs are the single most important topic — practice BFS on grids, Dijkstra, topological sort, and Union-Find. The Machine Coding round is equally weighted with DSA — prepare a working implementation of Splitwise and a Cab Booking system before your interview. For HLD, know Kafka and Redis deeply since they appear in nearly every Swiggy design discussion.


Preparation Resources

Part 1 — OA Questions

1. Maximum Profit in Job Scheduling (Swiggy Genie) Hard

OADP · Interval SchedulingLeetCode: #1235

Swiggy's OA frames this as "Maximum Swiggy Genie": a delivery agent has arrays of pickup times, drop times, and tips. The agent can handle one delivery at a time. Maximize the total tip earned.

Input: startTime=[0,2,9,10,11,12], endTime=[5,9,11,11,14,17], profit=[1,2,3,2,2,1]
Output: 6
Explanation: Take jobs [0→5] (tip 1) + [9→11] (tip 3) + [11→14] (tip 2) = 6.

Input: startTime=[1,2,3,3], endTime=[3,4,5,6], profit=[50,10,40,70]
Output: 120

Approach: Sort jobs by end time. Use DP where dp[i] = max profit considering first i jobs. For each job i, binary search for the last job that ends before job i starts (no overlap). dp[i] = max(dp[i-1], profit[i] + dp[last_non_overlap]). Use binary search for O(n log n) total. Complexity: Time O(n log n) · Space O(n) Follow-up: What if the agent can handle at most k deliveries simultaneously?


2. Minimum Size Subarray Sum Medium

OASliding Window · ArraysLeetCode: #209

Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is greater than or equal to target. Return 0 if no such subarray exists.

Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: Subarray [4,3] has the minimal length of 2.

Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0

Approach: Sliding window. Expand the right pointer and add to the running sum. Whenever the sum meets or exceeds target, record the window length and shrink from the left. Keep track of the minimum window size seen. Complexity: Time O(n) · Space O(1) Follow-up: What if the array contains negative numbers? (Sliding window breaks — use deque or segment tree.)


3. Sqrt(x) — Binary Search Easy

OABinary Search · MathLeetCode: #69

Given a non-negative integer x, return the integer square root of x (floor). The OA variant asks for the Nth root of a number M using binary search on a real-number domain.

Input: x = 8
Output: 2
Explanation: floor(sqrt(8)) = 2.

Input: x = 4
Output: 2

Approach: Binary search in [1, x]. At mid, if midmid == x return mid. If midmid < x, the answer is at least mid so move left to mid+1. If mid*mid > x, move right to mid-1. Return right pointer at the end. **Complexity: Time O(log x) · Space O(1) Follow-up: Nth root: binary search in [1.0, M] on floating point, checking mid^N vs M with a tolerance of 1e-6.


4. Unique Number of BSTs Medium

OADynamic Programming · TreesLeetCode: &#35;96

Given an integer n, return the number of structurally unique BSTs which have exactly n nodes of unique values 1 to n.

Input: n = 3
Output: 5

Input: n = 1
Output: 1

Approach: dp[i] = number of unique BSTs with i nodes. For each root r from 1 to i, left subtree has r-1 nodes and right subtree has i-r nodes. dp[i] = sum of dp[r-1]dp[i-r] for r from 1 to i. This is the nth Catalan number. *Complexity: Time O(n²) · Space O(n) Follow-up: Generate all structurally unique BSTs (LeetCode &#35;95).


5. Best Time to Buy and Sell Stock Easy

OAArrays · GreedyLeetCode: &#35;121

Given an array prices where prices[i] is the price of a stock on day i, return the maximum profit from a single buy-sell transaction.

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price 1), sell on day 5 (price 6).

Input: prices = [7,6,4,3,1]
Output: 0

Approach: Track the minimum price seen so far and the maximum profit. At each day, update maxProfit = max(maxProfit, currentPrice - minPrice), then update minPrice if needed. Complexity: Time O(n) · Space O(1) Follow-up: At most k transactions allowed (LeetCode &#35;188).


6. Robot Return to Origin Easy

OASimulation · MathLeetCode: &#35;657

A robot starts at position (0,0). Given a string moves containing 'U', 'D', 'L', 'R', return true if the robot returns to the origin after completing all moves.

Input: moves = "UD"
Output: true

Input: moves = "LL"
Output: false

Approach: Count U vs D and L vs R. The robot returns to origin only if UD and LR. Complexity: Time O(n) · Space O(1) Follow-up: What if the robot must stay within a bounded grid — return false if it steps outside?


Part 2 — Phone Screen Questions

7. Longest Valid Parentheses Hard

Phone ScreenStack · DP · StringLeetCode: &#35;32

Given a string containing just '(' and ')', return the length of the longest valid (well-formed) parentheses substring.

Input: s = "(()"
Output: 2
Explanation: The longest valid is "()".

Input: s = ")()())"
Output: 4
Explanation: "()()" is the longest valid.

Approach: Stack storing indices. Push -1 as a base. For '(' push index. For ')' pop the top. If the stack is empty, push current index as the new base. Otherwise the current valid length is currentIndex - stack.top(). Track the maximum. Complexity: Time O(n) · Space O(n) Follow-up: Two-pass O(1) space solution using left and right counters.


8. Gas Station Medium

Phone ScreenGreedy · ArraysLeetCode: &#35;134

There are n gas stations in a circle. The gas array gives fuel available and the cost array gives fuel needed to reach the next station. Find the unique starting station to complete the circuit.

Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output: 3

Input: gas = [2,3,4], cost = [3,4,3]
Output: -1

Approach: If total gas < total cost, return -1. Otherwise iterate tracking running tank. When the tank goes negative, reset to 0 and set the next station as the candidate start. The final candidate is the answer. Complexity: Time O(n) · Space O(1) Follow-up: Prove why the solution is unique when total gas >= total cost.


9. Search in Rotated Sorted Array Medium

Phone ScreenBinary SearchLeetCode: &#35;33

Given an integer array that was sorted in ascending order and then rotated at an unknown pivot, search for target in O(log n) time.

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

Approach: Binary search. At each step, one half is always sorted. Determine which half is sorted by comparing nums[left] with nums[mid]. Check if the target falls in the sorted half. If yes, recurse there; otherwise recurse in the other half. Complexity: Time O(log n) · Space O(1) Follow-up: Handle duplicates (LeetCode &#35;81) — what worst-case does this create?


10. Valid Parenthesis String Medium

Phone ScreenGreedy · StackLeetCode: &#35;678

Given a string s containing only '(', ')', and '' where '' can be '(', ')', or empty, return true if the string is valid.

Input: s = "()"
Output: true

Input: s = "(*)"
Output: true

Input: s = "(*))"
Output: true

Approach: Track a range [minOpen, maxOpen] representing the minimum and maximum possible open bracket count. For '(' increment both. For ')' decrement both. For '' decrement min and increment max. If maxOpen goes negative, return false. Clamp minOpen at 0. If minOpen is 0 at the end, return true. *Complexity: Time O(n) · Space O(1) Follow-up: Why does the DP approach have O(n³) time but the greedy achieves O(n)?


11. Cheapest Flights Within K Stops Medium

Phone ScreenGraphs · DPLeetCode: &#35;787

Given n cities, flights as directed weighted edges, source src, destination dst, and k stops, find the cheapest price from src to dst with at most k intermediate stops.

Input: n=4, flights=[[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src=0, dst=3, k=1
Output: 700
Explanation: 0→1→3 = 700 (1 stop).

Approach: Bellman-Ford with k+1 relaxation passes. Keep a prices array initialised to infinity except src=0. Each pass updates prices using the previous pass's values (use a copy to avoid using same-pass updates). Return prices[dst] after k+1 passes. Complexity: Time O(k*E) · Space O(n) Follow-up: Modified Dijkstra with state (node, stops_remaining) also works — when would you prefer it?


12. Subarray Sums Divisible by K Medium

Phone ScreenPrefix Sum · HashingLeetCode: &#35;974

Given an integer array nums and an integer k, return the number of non-empty subarrays with a sum divisible by k.

Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7

Input: nums = [5], k = 9
Output: 0

Approach: Use a prefix sum modulo k. Store the frequency of each remainder in a map. For each position, compute prefixSum % k (handle negative remainders by adding k). The count of subarrays ending here with sum divisible by k equals the frequency of the same remainder seen before. Complexity: Time O(n) · Space O(k) Follow-up: Why must you handle negative remainders by adding k?


13. Find First and Last Position in Sorted Array Medium

Phone ScreenBinary SearchLeetCode: &#35;34

Given an array sorted in ascending order, find the starting and ending position of a given target value in O(log n) time. The Swiggy interview variant asks for the frequency of a number in a sorted array in O(log n).

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Approach: Two binary searches. First finds the leftmost position (bias toward left when mid equals target). Second finds the rightmost position (bias toward right). Frequency = rightPos - leftPos + 1. Complexity: Time O(log n) · Space O(1) Follow-up: Use this to implement a count operation for any value in a sorted array without scanning linearly.


Part 3 — Onsite Questions

14. Number of Islands Medium

OnsiteGraph · BFS/DFSLeetCode: &#35;200

Given a 2D binary grid of '1' (land) and '0' (water), return the number of islands. Swiggy interviewers specifically look for candidates who immediately recognise grid problems as graph problems.

Input:
grid = [["1","1","0","0","0"],
        ["1","1","0","0","0"],
        ["0","0","1","0","0"],
        ["0","0","0","1","1"]]
Output: 3

Approach: For each unvisited '1', increment island count and BFS/DFS to mark all connected '1' cells as visited. Continue scanning. Complexity: Time O(m*n) · Space O(m*n) Follow-up: Max Area of Island (LeetCode &#35;695). Also: what if the grid wraps around (toroidal)?


15. Lowest Common Ancestor of a Binary Tree Medium

OnsiteTrees · DFSLeetCode: &#35;236

Given the root of a binary tree and two nodes p and q, find their Lowest Common Ancestor (the deepest node that is an ancestor of both).

Input: root = [3,5,1,6,2,0,8], p = 5, q = 1
Output: 3

Input: root = [3,5,1,6,2,0,8], p = 5, q = 4
Output: 5

Approach: DFS returning a node. If the current node is p or q, return it. Recurse into both subtrees. If both return non-null, the current node is the LCA. If only one returns non-null, bubble that up. Complexity: Time O(n) · Space O(h) Follow-up: LCA of a BST exploits ordering (LeetCode &#35;235). LCA with parent pointers uses a visited set.


16. Search a 2D Matrix II Medium

OnsiteMatrix · Binary SearchLeetCode: &#35;240

Given an m x n matrix where each row is sorted left to right and each column is sorted top to bottom, search for a target value.

Input: matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16],[10,13,14,17]], target = 5
Output: true

Input: target = 20
Output: false

Approach: Start from the top-right corner. If the current element equals target, return true. If it is greater, move left. If it is smaller, move down. This eliminates one row or column at each step. Complexity: Time O(m+n) · Space O(1) Follow-up: How does this compare to the fully sorted matrix variant (LeetCode &#35;74)?


17. Implement Trie (Prefix Tree) Medium

OnsiteTrie · DesignLeetCode: &#35;208

Implement a Trie with insert(word), search(word), and startsWith(prefix) methods.

Trie trie = new Trie();
trie.insert("apple");
trie.search("apple")    → true
trie.search("app")      → false
trie.startsWith("app")  → true
trie.insert("app");
trie.search("app")      → true

Approach: Each TrieNode has a children map (or array of 26) and an isEnd flag. insert follows or creates nodes for each character. search traverses and checks isEnd at the last character. startsWith traverses and returns true if all characters exist. Complexity: Time O(L) per operation where L = word length · Space O(total characters) Follow-up: Design an autocomplete system using a Trie with frequency counts (LeetCode &#35;642).


18. LRU Cache Medium

OnsiteDesign · Linked ListLeetCode: &#35;146

Design a data structure with O(1) get and put, evicting the least recently used item when capacity is exceeded.

LRUCache(2)
put(1,1), put(2,2)
get(1)    → 1
put(3,3)  → evicts key 2
get(2)    → -1

Approach: Doubly linked list (head=most recent, tail=least recent) + hash map (key→node). On get, move node to head. On put, add at head; if over capacity remove from tail and delete map entry. Complexity: Time O(1) · Space O(capacity) Follow-up: Swiggy interviewers specifically ask how this relates to a restaurant catalog cache — discuss TTL and cache invalidation on menu updates.


19. Edit Distance Hard

OnsiteDynamic Programming · StringsLeetCode: &#35;72

Return the minimum number of operations (insert, delete, replace) to convert word1 to word2.

Input: word1 = "horse", word2 = "ros"
Output: 3

Input: word1 = "intention", word2 = "execution"
Output: 5

Approach: dp[i][j] = min ops for word1[0..i-1] → word2[0..j-1]. If chars match, dp[i][j] = dp[i-1][j-1]. Otherwise 1 + min(dp[i-1][j] delete, dp[i][j-1] insert, dp[i-1][j-1] replace). Space-optimise to O(min(m,n)). Complexity: Time O(m*n) · Space O(min(m,n)) Follow-up: How can edit distance power a fuzzy restaurant name search?


20. Longest Palindromic Substring Medium

OnsiteDP · Expand Around CentreLeetCode: &#35;5

Given a string s, return the longest palindromic substring.

Input: s = "babad"
Output: "bab"

Input: s = "cbbd"
Output: "bb"

Approach: For each centre (n odd + n-1 even centres), expand outward while characters match. Track the start index and length of the longest palindrome found. Complexity: Time O(n²) · Space O(1) Follow-up: Manacher's algorithm achieves O(n). Explain the motivation behind the preprocessing step.


21. Unique Paths II Medium

OnsiteDynamic Programming · GridLeetCode: &#35;63

A robot can only move right or down on an m x n grid. Some cells contain obstacles (1). Count the unique paths from top-left to bottom-right.

Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 2

Approach: DP in-place. Set dp[0][0] = 1 if no obstacle. Fill first row and column — 0 if an obstacle is encountered (and all subsequent cells in that line). For remaining cells: dp[i][j] = (obstacle ? 0 : dp[i-1][j] + dp[i][j-1]). Complexity: Time O(m*n) · Space O(1) Follow-up: Minimum cost path through a grid (LeetCode &#35;64).


22. Maximum Length of Pair Chain Medium

OnsiteGreedy · DP · IntervalsLeetCode: &#35;646

Given pairs [a, b] where a < b, you can chain pair2 after pair1 if pair1[1] < pair2[0]. Return the length of the longest chain.

Input: pairs = [[1,2],[2,3],[3,4]]
Output: 2
Explanation: [1,2] → [3,4].

Input: pairs = [[1,2],[7,8],[4,5]]
Output: 3

Approach: Sort pairs by end value. Greedily select the pair with the earliest end that starts after the last selected pair's end. This is the interval scheduling maximisation problem. Complexity: Time O(n log n) · Space O(1) Follow-up: This is equivalent to Longest Increasing Subsequence on a different representation — show the equivalence.


23. Construct Binary Tree from Preorder and Inorder Medium

OnsiteTrees · RecursionLeetCode: &#35;105

Given preorder and inorder traversal arrays of a binary tree with unique values, reconstruct the tree.

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]

Approach: The first element of preorder is always the root. Find this root in the inorder array — everything to its left is the left subtree and everything to its right is the right subtree. Recurse with the corresponding preorder and inorder slices. Use a hash map of inorder indices for O(1) lookup. Complexity: Time O(n) · Space O(n) Follow-up: Postorder + inorder variant (LeetCode &#35;106).


24. Vertical Order Traversal of Binary Tree Hard

OnsiteTrees · BFS · SortingLeetCode: &#35;987

Given the root of a binary tree, return the vertical order traversal of its nodes. Nodes in the same position are sorted by value. (Also asked as "Top View of Binary Tree" in GFG format.)

Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]

Approach: BFS with each node carrying its (col, row) coordinates. Group nodes by column into a map. Within each column, sort by (row, value). Collect results from the leftmost to rightmost column. Complexity: Time O(n log n) · Space O(n) Follow-up: Top View only requires the first node encountered in BFS at each column — why?


25. Network Delay Time Medium

OnsiteGraphs · DijkstraLeetCode: &#35;743

Given a network of n nodes, directed weighted edges, and a source node k, find how long it takes for all nodes to receive a signal. Return -1 if not all nodes can be reached.

Input: times=[[2,1,1],[2,3,1],[3,4,1]], n=4, k=2
Output: 2

Approach: Dijkstra's algorithm from k. Use a min-heap of (distance, node). Relax edges greedily. After processing all reachable nodes, the answer is the maximum distance in the dist array. If any node is unreachable (distance = infinity), return -1. Complexity: Time O(E log V) · Space O(V+E) Follow-up: How does this relate to Swiggy's delivery routing — minimising the last-mile delay across all delivery agents?


26. Satisfiability of Equality Equations Medium

OnsiteUnion-Find · GraphsLeetCode: &#35;990

Given equations like "a==b" and "b!=c", determine if they can all be satisfied simultaneously.

Input: equations = ["a==b","b!=c","c==a"]
Output: false

Input: equations = ["c==c","b==d","x!=z"]
Output: true

Approach: Union-Find. First pass: process all "==" equations by unioning the two variables. Second pass: for each "!=" equation, check if the two variables share the same root. If they do, return false. Otherwise return true. Complexity: Time O(n · α(n)) · Space O(1) (only 26 possible variables) Follow-up: The Flexible Strings OA variant uses the same Union-Find pattern — connecting characters under replacement rules.


27. Partition Array Into Two Arrays to Minimise Sum Difference Hard

OnsiteDP · Meet in the MiddleLeetCode: &#35;2035

Given an integer array nums of even length 2n, partition it into two arrays of length n each to minimise the absolute difference of their sums.

Input: nums = [3,9,7,3]
Output: 2
Explanation: Partition into [3,9] and [7,3] → |12-10| = 2.

Approach: Meet-in-the-middle. Split nums into two halves. For each half, enumerate all subsets and their sums grouped by subset size. For each subset of size k from the left half, binary search in the right half's size-(n-k) sums to find the best complement. The target is totalSum/2. Complexity: Time O(2^(n/2) · n) · Space O(2^(n/2)) Follow-up: Why does standard DP fail here for large n? What is the crossover point where meet-in-the-middle beats DP?


28. Merge Intervals Medium

OnsiteSorting · IntervalsLeetCode: &#35;56

Given an array of intervals, merge all overlapping intervals and return the result.

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]

Approach: Sort by start. Iterate and extend the last result interval if it overlaps with the current one, otherwise append. Complexity: Time O(n log n) · Space O(n) Follow-up: Insert interval into a sorted non-overlapping list (LeetCode &#35;57).


29. Course Schedule Medium

OnsiteGraphs · Topological SortLeetCode: &#35;207

Given numCourses and a list of prerequisite pairs, determine if you can finish all courses (no cycle in the dependency graph).

Input: numCourses = 2, prerequisites = [[1,0]]
Output: true

Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false

Approach: Kahn's algorithm — compute in-degrees, start with 0-in-degree nodes, process and reduce neighbours' in-degrees. If processed count equals numCourses, no cycle. Complexity: Time O(V+E) · Space O(V+E) Follow-up: Return the actual order (LeetCode &#35;210).


30. Jump Game Medium

OnsiteGreedyLeetCode: &#35;55

Given an integer array where each element is the max jump from that position, return true if you can reach the last index.

Input: nums = [2,3,1,1,4]
Output: true

Input: nums = [3,2,1,0,4]
Output: false

Approach: Track maxReach. At each index i, if i > maxReach return false. Update maxReach = max(maxReach, i + nums[i]). Complexity: Time O(n) · Space O(1) Follow-up: Minimum number of jumps (LeetCode &#35;45).


31. Subsets Medium

OnsiteBacktracking · Bit MaskingLeetCode: &#35;78

Given an integer array nums of unique elements, return all possible subsets.

Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Approach: Backtracking — at each index either include or exclude the element. Alternatively, iterate from 0 to 2^n and use bitmask to select elements for each integer's binary representation. Complexity: Time O(n * 2^n) · Space O(n) Follow-up: Subsets with duplicates (LeetCode &#35;90) — sort and skip duplicates at the same recursion level.


32. Word Break Medium

OnsiteDynamic ProgrammingLeetCode: &#35;139

Given a string s and a dictionary wordDict, return true if s can be segmented into a space-separated sequence of dictionary words.

Input: s = "leetcode", wordDict = ["leet","code"]
Output: true

Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false

Approach: dp[i] = true if s[0..i-1] is breakable. For each i, check all j < i where dp[j] is true and s[j..i-1] is in the dictionary (use a hash set). dp[0] = true. Complexity: Time O(n²) · Space O(n) Follow-up: Return all valid sentence segmentations (Word Break II, LeetCode &#35;140).


33. Maximum Subarray Medium

OnsiteDP · GreedyLeetCode: &#35;53

Find the contiguous subarray with the largest sum and return its sum.

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] = 6.

Approach: Kadane's — if adding the next element makes the running sum negative, reset to the current element. Track global max. Complexity: Time O(n) · Space O(1) Follow-up: Return the actual subarray start and end indices.


34. Array Partition — Maximise Minimum Pair Sum Easy

OnsiteGreedy · SortingLeetCode: &#35;561

Given an integer array nums of 2n integers, pair them into n pairs to maximise the sum of the minimums of each pair. The Swiggy OA variant frames this as pairing programmers to minimize total bias.

Input: nums = [1,4,3,2]
Output: 4
Explanation: Pairs (1,2) and (3,4) give min-sum 1+3=4.

Approach: Sort the array. The optimal pairing is always adjacent elements in sorted order. Sum every other element starting from index 0. Complexity: Time O(n log n) · Space O(1) Follow-up: Prove that adjacent pairing in sorted order is always optimal.


35. Min Stack Medium

OnsiteStack · DesignLeetCode: &#35;155

Design a stack supporting push, pop, top, and getMin in O(1).

MinStack ms
push(-2), push(0), push(-3)
getMin() → -3, pop(), top() → 0, getMin() → -2

Approach: Auxiliary min-stack. On push, also push to min stack if value <= current minimum. On pop, also pop from min stack if popped value == min stack top. Complexity: Time O(1) per operation · Space O(n) Follow-up: Encode min into the main stack to avoid extra space — store (value - currentMin) when value < currentMin.


36. Intersection of Two Linked Lists Easy

OnsiteLinked List · Two PointersLeetCode: &#35;160

Given heads of two linked lists, return the node where they intersect or null.

Input: listA = [4,1,8,4,5], listB = [5,6,1,8,4,5]
Output: node 8

Approach: Two pointers. When one reaches its end, redirect to the head of the other list. They meet at the intersection after lenA + lenB steps. Complexity: Time O(m+n) · Space O(1) Follow-up: Detect if a linked list has a cycle and find the cycle entry point (Floyd's, LeetCode &#35;142).


37. Rotate Image Medium

OnsiteMatrixLeetCode: &#35;48

Rotate an n x n matrix 90 degrees clockwise in-place.

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

Approach: Transpose (swap matrix[i][j] with matrix[j][i]), then reverse each row. Complexity: Time O(n²) · Space O(1) Follow-up: Counter-clockwise rotation: reverse each row first, then transpose.


38. Design Splitwise Medium

Onsite · LLDOOP · Design

Design a bill-splitting system. Users can be added to groups. Expenses can be split equally, by percentage, or by exact amounts. The system should show each user's net balance and allow settling debts.

System.addUser("Alice"), addUser("Bob"), addUser("Charlie")
System.addExpense(paidBy="Alice", amount=300, split=EQUAL, users=[Alice,Bob,Charlie])
// Alice is owed 200, Bob owes 100, Charlie owes 100
System.showBalance("Alice") → +200
System.settle("Bob", "Alice", 100)

Approach: Classes: User (id, name, balance), Expense (id, amount, paidBy, splits), Split (user, amount), Group. ExpenseManager maintains a map of userId→userId→netAmount for debts. On addExpense, compute each user's share and update the debt map. settle() reduces the debt. Implement SplitType as enum (EQUAL, PERCENTAGE, EXACT). SOLID: use a SplitStrategy interface for each type. Key Design Principles: Single Responsibility, Open/Closed for new split types, Strategy pattern for splitting Follow-up: Minimise the number of transactions needed to settle all debts in the group (graph simplification problem).


39. Design Cab Booking System Medium

Onsite · LLDOOP · Design

Design a cab booking system where cabs can register with their location, riders can request a ride, the nearest available cab is assigned, and billing is calculated on ride completion.

CabService.registerCab(cabId="C1", location=(0,0))
CabService.bookRide(riderId="R1", pickup=(1,1), drop=(5,5))
→ Assigns nearest available cab, returns rideId
CabService.updateLocation(cabId="C1", location=(2,2))
CabService.endRide(rideId) → Calculates fare, marks cab available

Approach: Classes: Cab (id, location, status: AVAILABLE/ON_RIDE), Rider, Ride (id, cab, rider, pickup, drop, status), CabService. Nearest cab: iterate available cabs and find minimum Euclidean distance (or use a k-d tree for scale). Fare: distance × rate per km. Use Observer pattern — notify rider when cab location updates. Key Design Principles: Strategy for fare calculation, Observer for real-time updates, Factory for ride creation Follow-up: How do you scale cab assignment to 10,000 concurrent requests using a spatial index (geohash + Redis)?


40. Design Snake and Ladder Game Easy

Onsite · LLDOOP · Design

Design a Snake and Ladder game for multiple players. The board has configurable snakes and ladders. Players take turns rolling a dice. Reaching or exceeding 100 wins.

Game.setup(players=["A","B"], snakes={99:5,70:30}, ladders={10:40,20:60})
Game.play() → Turn-by-turn until a player wins
Game.getWinner() → "A"

Approach: Classes: Board (size, snakeMap, ladderMap, getNewPosition(pos)), Player (name, currentPosition), Dice (roll() → random 1-6), Game (board, players, currentPlayer). Each turn: roll dice, compute new position, apply snakes/ladders via Board, check win condition. Board.getNewPosition checks snakeMap then ladderMap. Key Design Principles: Single Responsibility, easy to swap dice (loaded dice for testing), board is decoupled from game loop Follow-up: How do you make the game deterministic for unit testing (dependency injection for Dice)?


41. Design Swiggy Catalog System Hard

Onsite · HLDSystem Design

Design the Swiggy food catalog service that serves restaurant listings, menus, pricing, and availability to millions of users. Restaurants frequently update their menus and mark items as out-of-stock.

Functional: searchRestaurants(city, filters), getMenu(restaurantId), updateItemAvailability(itemId, available)
Non-functional: <100ms search latency, 10M daily active users, menu updates reflected within 30s

Approach: Database schema: Restaurant → Menu → MenuSection → Item → VariantGroup → Variant (with AddOns). Read path: Elasticsearch for restaurant search with geo-filtering; Redis cache for menu data (TTL 30s). Write path: mutations go to MySQL, publish change events to Kafka. A catalog consumer reads Kafka and updates Redis + Elasticsearch. Out-of-stock updates are hot-patched directly into Redis with a short TTL and async-synced to MySQL. Key Concepts: CQRS (separate read/write), eventual consistency for availability, Elasticsearch geo-distance queries, Kafka for async propagation Follow-up: How do you handle pricing inconsistencies when a restaurant updates prices mid-order?


42. Design Real-Time Food Delivery Tracking Hard

Onsite · HLDSystem Design

Design the real-time location tracking system for Swiggy delivery partners. Users should see their delivery partner's live location update on a map every 3–5 seconds during an active order.

Functional: updateLocation(agentId, lat, lng), getAgentLocation(agentId), subscribeToOrder(orderId, userId)
Non-functional: <500ms location update latency, 1M concurrent active deliveries

Approach: Delivery partner app sends GPS updates via HTTP POST every 5s to a Location Update Service. The service writes to Redis (key: agentId → {lat, lng, timestamp}) for latest position and publishes to a Kafka topic partitioned by agentId. A WebSocket server consumes from Kafka and pushes updates to all users subscribed to that order via persistent WebSocket connections. Scale: multiple WebSocket servers behind a load balancer; user subscription mapping stored in Redis. Key Concepts: WebSockets for real-time push, Redis for latest-position lookups, Kafka for fan-out, geohash for proximity Follow-up: How do you handle an agent going offline mid-delivery (no GPS updates for 30s)?


43. Design Coupon and Offers API Medium

Onsite · LLDOOP · Design

Design a coupon/offers API for Swiggy. Coupons can have different discount types (flat, percentage, BOGO), applicability rules (min order value, specific restaurants, first order only), and usage limits (per-user, global).

CouponService.createCoupon(code="SAVE50", type=FLAT, value=50, minOrder=200, usageLimit=1000)
CouponService.applyCoupon(userId, orderId, couponCode) → discountAmount or error
CouponService.validateCoupon(userId, couponCode, orderValue) → isValid, reason

Approach: Classes: Coupon (code, discountStrategy, eligibilityRules, usageTracker), DiscountStrategy (interface with compute(orderValue)), EligibilityRule (interface with isEligible(user, order)). Strategy pattern for discount types. Chain of Responsibility for eligibility rules (min order → user limit → restaurant scope → first-order check). UsageTracker uses Redis atomic INCR with EXPIRE for distributed rate limiting. Key Design Principles: Strategy for discounts, Chain of Responsibility for validation, Redis for atomic usage counting Follow-up: How do you prevent coupon code abuse at high concurrency (race condition on usage count)?


44. Two Sum Easy

OnsiteHashingLeetCode: &#35;1

Given an array of integers and a target, return indices of two numbers that sum to target.

Input: nums = [2,7,11,15], target = 9
Output: [0,1]

Approach: Hash map storing value → index. For each element check if (target - current) is in the map. Complexity: Time O(n) · Space O(n) Follow-up: Three Sum (LeetCode &#35;15) using sort + two pointers.


45. Climbing Stairs Easy

OnsiteDynamic ProgrammingLeetCode: &#35;70

Count the number of ways to climb n stairs taking 1 or 2 steps at a time.

Input: n = 4
Output: 5

Approach: Fibonacci DP. dp[n] = dp[n-1] + dp[n-2]. O(1) space with two variables. Complexity: Time O(n) · Space O(1) Follow-up: Min cost to reach the top (LeetCode &#35;746).


46. Find the Duplicate Number Medium

OnsiteArrays · Floyd's CycleLeetCode: &#35;287

Given an array of n+1 integers where each integer is in [1,n], find the one repeated number without modifying the array and using O(1) extra space.

Input: nums = [1,3,4,2,2]
Output: 2

Approach: Floyd's cycle detection — treat the array as a linked list (nums[i] → next node). Fast/slow pointer finds the cycle. Reset slow to 0, advance both one step at a time — meeting point is the duplicate. Complexity: Time O(n) · Space O(1) Follow-up: What if there could be multiple duplicates?


47. Longest Common Subsequence Medium

OnsiteDynamic ProgrammingLeetCode: &#35;1143

Given two strings, return the length of their longest common subsequence.

Input: text1 = "abcde", text2 = "ace"
Output: 3

Approach: dp[i][j] = LCS of text1[0..i-1] and text2[0..j-1]. If chars match, dp[i][j] = dp[i-1][j-1]+1. Otherwise max of dp[i-1][j] and dp[i][j-1]. Reduce to O(min(m,n)) space with rolling array. Complexity: Time O(m*n) · Space O(min(m,n)) Follow-up: Shortest Common Supersequence (LeetCode &#35;1092).


48. Maximum Product Subarray Medium

OnsiteDynamic ProgrammingLeetCode: &#35;152

Find the contiguous subarray with the largest product.

Input: nums = [2,3,-2,4]
Output: 6

Approach: Track both max and min product ending at each position (negative × negative = positive). curMax = max(nums[i], curMax×nums[i], curMin×nums[i]). Track global max. Complexity: Time O(n) · Space O(1) Follow-up: What if zeros are possible — why do they "reset" the subarray?


49. Kth Largest Element in BST Medium

OnsiteTrees · DFSLeetCode: &#35;230

Given the root of a BST and an integer k, return the kth largest value in the BST.

Input: root = [3,1,4,null,2], k = 1
Output: 4

Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 4

Approach: Reverse inorder traversal (right → root → left) of a BST gives values in descending order. Decrement k at each visit and return the current node when k reaches 0. Complexity: Time O(h+k) · Space O(h) Follow-up: Kth Smallest Element in BST (LeetCode &#35;230 standard variant) — standard inorder.


50. Design Order Dispatch System Hard

Onsite · HLDSystem Design

Design Swiggy's order dispatch system that assigns new food orders to the best available delivery partner in real time. The system must handle 100K orders/minute at peak with p95 latency under 1 second for assignment.

Functional: dispatchOrder(orderId, restaurantId, deliveryAddress), trackAssignment(orderId)
Non-functional: p95 dispatch latency <1s, 100K orders/min, at-most-once delivery assignment

Approach: When an order is confirmed, publish to a Kafka topic partitioned by city/zone. A Dispatch Service consumer reads the event, queries a Delivery Partner Location Service (Redis Sorted Set keyed by geohash) for the nearest available agents within a radius. Scores agents by distance, current load, and ratings. Sends assignment request to the selected agent via FCM push. If the agent doesn't accept within 30s, re-dispatch to the next candidate. Use Redis SET NX for idempotent assignment (prevents double-assignment). Database records the final assignment for audit. Key Concepts: Geospatial indexing with Redis GEOPOS/GEOSEARCH, Kafka for async dispatch, exponential backoff re-dispatch, idempotency with Redis SET NX Follow-up: How do you guarantee at-most-once delivery assignment even if the Dispatch Service crashes mid-flight?


Preparation Tips

Swiggy's DSA focus is heavily graph-oriented — a grid or adjacency list problem appears in nearly every interview loop. After graphs, Dynamic Programming (especially interval scheduling and grid DP) and tree traversals are the most frequent topics. The Machine Coding round is equally important as DSA: prepare a clean, working Splitwise and a Cab Booking system before your interview. For HLD, know your Kafka + Redis patterns cold since every Swiggy design question eventually involves one or both. The Bar Raiser round expects you to reason about product-engineering trade-offs, not just write code.

Join Telegram group to get the latest Swiggy OA questions and connect with candidates currently in the Swiggy interview process.

Useful Resources