Myntra Previous Year Coding Questions
Myntra is India's leading fashion e-commerce platform (Flipkart/Walmart group), serving 50M+ active users from its Bangalore headquarters. Engineering interviews are known for strong DSA fundamentals with a particular emphasis on graphs (BFS/DFS on grids, Union-Find), backtracking (Word Search, Combination Sum), and tree problems. The Machine Coding round typically involves a fashion-domain design: a Recommendation Engine, Shopping Cart, or Inventory system. The HLD round is product-aware — interviewers expect candidates to know how a Search & Catalog system, Flash Sale architecture, or Order Management system would work in the context of a fashion e-commerce platform. Personalization and ranking algorithms often come up as follow-up discussions.
Hiring Process
Step 1: Resume Screening Myntra looks for backend/full-stack experience, strong DSA fundamentals, and some exposure to high-scale systems. Candidates from Flipkart, Amazon, or other e-commerce companies get a slight edge due to domain overlap.
Step 2: Online Assessment (HackerEarth) Duration: 60–90 minutes. 2–3 coding problems (Easy to Hard). OA problems often involve arrays, strings, or moderate graph/DP. SQL problem appears occasionally.
Step 3: DSA Live Coding Round 1 60 minutes. 2 LeetCode Medium problems. Interviewers expect clean, correct code with edge cases handled and complexity discussed.
Step 4: DSA Live Coding Round 2 60 minutes. A harder problem — typically graphs, backtracking with pruning, or advanced DP. Candidates are expected to arrive at the optimal solution within the session.
Step 5: Machine Coding / LLD Round 90 minutes. Build a working system from a product requirement. Common: Fashion Recommendation Engine, Shopping Cart with coupons, Inventory Management. Evaluated on SOLID principles, extensibility, and code quality.
Step 6: System Design / HLD Round (SDE-2+) 60–90 minutes. Myntra-specific systems: Search and Catalog, Flash Sale (Big Billion Days), Order Management, Personalisation Engine. Interviewers probe caching strategies, database choices, and how to handle traffic spikes.
Step 7: Hiring Manager / Bar Raiser Round Behavioural and architectural depth. Past project discussion, product thinking, and scalability trade-offs.
Tips: Graphs and backtracking are Myntra's most-tested DSA topics — practice Word Search II (Trie + backtracking), Pacific Atlantic Water Flow, Accounts Merge (Union-Find), and Rotting Oranges. For LLD, prepare a Shopping Cart with discount/coupon logic. For HLD, know how to design a Search & Catalog system using Elasticsearch and how a Flash Sale architecture differs from normal e-commerce (inventory reservation, oversell prevention, traffic shaping).
Preparation Resources
Part 1 — OA Questions
1. Next Greater Element II Medium
Given a circular integer array, find the next greater number for every element. For circular wrapping, search through the array twice.
Input: nums = [1,2,1]
Output: [2,-1,2]
Input: nums = [1,2,3,4,3]
Output: [2,3,4,-1,4]
Approach: Monotonic decreasing stack. Iterate the array twice (indices 0 to 2n-1, using i%n). For each element, pop all stack elements smaller than it — they found their next greater. Push the current index modulo n.
Complexity: Time O(n) · Space O(n)
Follow-up: Next Greater Element I (LC #496) — subset query version using a hash map.
2. Count Palindromic Substrings Medium
Given a string s, return the number of palindromic substrings.
Input: s = "abc"
Output: 3
Explanation: "a", "b", "c"
Input: s = "aaa"
Output: 6
Explanation: "a","a","a","aa","aa","aaa"
Approach: For each centre (n odd + n-1 even centres), expand while characters match and count each expansion.
Complexity: Time O(n²) · Space O(1)
Follow-up: Manacher's algorithm counts all in O(n). How does the palindrome radius array work?
3. Largest Number Medium
Given a list of non-negative integers, arrange them to form the largest number.
Input: nums = [10,2]
Output: "210"
Input: nums = [3,30,34,5,9]
Output: "9534330"
Approach: Custom comparator: for two strings a and b, compare a+b vs b+a as strings. Sort in descending order. Handle edge case where all digits are 0 → return "0".
Complexity: Time O(n log n * k) where k = avg digit length · Space O(n)
Follow-up: Why is the custom comparator transitive (required for a valid sort)?
4. Bulls and Cows Medium
Given a secret number and a guess, return the hint in "xAyB" format — A = correct digit in correct position (bulls), B = correct digit in wrong position (cows).
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Approach: One pass for bulls. Second pass using frequency arrays for cows: for each non-bull position, cow count += min(secretFreq[d], guessFreq[d]) per digit.
Complexity: Time O(n) · Space O(10)
Follow-up: Minimax Wordle strategy — how many guesses are needed with optimal play?
5. Rotate List Medium
Rotate a linked list to the right by k places.
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Input: head = [0,1,2], k = 4
Output: [2,0,1]
Approach: Find length n. Effective rotation = k % n. Connect the tail to the head (make circular). Move to the (n - k%n - 1)th node, set it as the new tail, and the next node as the new head.
Complexity: Time O(n) · Space O(1)
Follow-up: Rotate an array right by k (LC #189) — three-reversal trick.
6. Minimum Cost for Tickets Medium
You travel on specific days of the year (1–365). Passes cost costs[0] for 1 day, costs[1] for 7 days, costs[2] for 30 days. Find the minimum cost to travel every travel day.
Input: days = [1,4,6,7,8,20], costs = [2,7,15]
Output: 11
Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
Output: 17
Approach: dp[i] = minimum cost to cover all travel days up to day i. For non-travel days, dp[i] = dp[i-1]. For travel days, dp[i] = min of (dp[i-1]+costs[0], dp[max(0,i-7)]+costs[1], dp[max(0,i-30)]+costs[2]).
Complexity: Time O(365) · Space O(365)
Follow-up: What if passes come in 1-day, 3-day, 7-day, and 30-day variants?
Part 2 — Phone Screen Questions
7. Container With Most Water Medium
Given heights of n vertical lines, find two that together with the x-axis form a container holding the most water.
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Input: height = [1,1]
Output: 1
Approach: Two pointers at both ends. At each step, move the pointer with the shorter height inward (moving the taller one can never increase the area). Track maximum area.
Complexity: Time O(n) · Space O(1)
Follow-up: Prove why moving the shorter-height pointer is always the optimal greedy choice.
8. Combination Sum Medium
Find all combinations of candidates that sum to target. The same number can be chosen unlimited times.
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Approach: Backtracking. Sort candidates. At each step, try each candidate from the current index onward. Prune when remaining < 0. When remaining == 0, record the combination.
Complexity: Time O(n^(T/M)) where T=target, M=min candidate · Space O(T/M)
Follow-up: Combination Sum II with duplicates (LC #40), Combination Sum III with exactly k numbers (LC #216).
9. Letter Combinations of a Phone Number Medium
Given a string of digits 2–9, return all possible letter combinations using the phone keypad mapping.
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Input: digits = ""
Output: []
Approach: Backtracking. For each digit, iterate its mapped letters and recurse with the next digit. When the combination length equals digits length, add to results.
Complexity: Time O(4^n * n) · Space O(n)
Follow-up: BFS (queue-based) iterative approach — when is BFS preferred over DFS for this problem?
10. Pacific Atlantic Water Flow Medium
Water flows from any cell to adjacent cells with equal or lower height. Find all cells from which water can flow to both the Pacific (top/left border) and Atlantic (bottom/right border).
Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Approach: Reverse BFS — start from ocean borders and flow uphill (to equal or higher cells). BFS from Pacific borders into a pacific-reachable set. BFS from Atlantic borders into an atlantic-reachable set. Return the intersection.
Complexity: Time O(m*n) · Space O(m*n)
Follow-up: What changes if water can only flow strictly downhill (no equal height)?
11. Target Sum Medium
Assign + or − to each number so the expression evaluates to target. Count the number of ways.
Input: nums = [1,1,1,1,1], target = 3
Output: 5
Input: nums = [1], target = 1
Output: 1
Approach: DP with a sum-frequency map. Start with {0: 1}. For each number, create a new map: for each (sum, count) pair, add to (sum+num) and (sum-num). Return the count at target.
Complexity: Time O(n * totalSum) · Space O(totalSum)
Follow-up: Reduces to subset-sum partition: find a subset with sum = (totalSum + target) / 2.
12. Wiggle Subsequence Medium
A wiggle sequence alternates between rises and falls. Find the length of the longest wiggle subsequence.
Input: nums = [1,7,4,9,2,5]
Output: 6
Input: nums = [1,17,5,10,13,15,10,5,16,8]
Output: 7
Approach: Greedy. Track the last direction (up or down) and the current length. At each step, if the direction changes, increment length and update direction.
Complexity: Time O(n) · Space O(1)
Follow-up: Wiggle Sort II (LC #324) — rearrange the array into wiggle order (harder, requires partial sort).
13. Combination Sum IV Medium
Count the number of ordered combinations (permutations of selections) from nums that sum to target.
Input: nums = [1,2,3], target = 4
Output: 7
Explanation: (1,1,1,1),(1,1,2),(1,2,1),(1,3),(2,1,1),(2,2),(3,1)
Approach: dp[i] = number of combinations summing to i. For each amount, sum dp[i - num] for all valid nums. Order matters here — iterate amount in outer loop, nums in inner loop (unlike 0/1 knapsack).
Complexity: Time O(target * n) · Space O(target)
Follow-up: This counts ordered arrangements (permutations); Coin Change II counts unordered (combinations) — explain the loop order difference.
Part 3 — Onsite Questions
14. Word Search II Hard
Given an m×n board and a list of words, find all words that can be formed by a path of adjacent (horizontal/vertical) cells without reusing cells.
Input: board=[["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]]
words=["oath","pea","eat","rain"]
Output: ["eat","oath"]
Approach: Build a Trie from all words. DFS from each cell. At each step, check if the current character exists in the current Trie node. If a word end is reached, add to results. Mark cells as visited (temporarily) to avoid reuse. Prune: delete leaf Trie nodes after finding a word to avoid duplicate searches.
Complexity: Time O(m*n*4*3^(L-1)) where L=max word length · Space O(total chars in words)
Follow-up: Why is Trie-based backtracking faster than running Word Search I per word?
15. Accounts Merge Medium
Merge accounts that share at least one email. Each account has a name and list of emails. Output merged accounts sorted by email.
Input: [["John","a@m","b@m"],["John","c@m"],["Mary","b@m"]]
Output: [["John","a@m","b@m","c@m"],["Mary","b@m"]]
Wait — John and Mary share b@m so merge all.
Approach: Union-Find on emails. Map each email to an account index. For each account, union all its emails with the first email. Group emails by their root representative. Collect, sort, and prepend the account name.
Complexity: Time O(n * k * α) · Space O(n * k)
Follow-up: Graph DFS approach — treat emails as nodes, shared emails create edges between accounts.
16. Number of Provinces (Friend Circles) Medium
Given an n×n adjacency matrix isConnected, find the number of connected components (provinces).
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
Approach: Union-Find — union all pairs where isConnected[i][j]==1. Count distinct roots. Or DFS: for each unvisited node, run DFS and mark all reachable as visited; increment province count.
Complexity: Time O(n²) · Space O(n)
Follow-up: Graph Valid Tree (LC #261) — same connected-components idea plus cycle detection.
17. Binary Tree Maximum Path Sum Hard
A path in a binary tree is a sequence of nodes where each pair is connected. Find the path with the maximum sum (the path need not pass through the root).
Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: 15→20→7
Input: root = [1,2,3]
Output: 6
Approach: DFS returning the max gain from each node (max of left or right subtree gain, clamped to 0 if negative). At each node, the potential path through it = node.val + leftGain + rightGain. Update global max. Return node.val + max(leftGain, rightGain) to the parent.
Complexity: Time O(n) · Space O(h)
Follow-up: Path Sum III (LC #437) — count paths summing to target (uses prefix sums in DFS).
18. Populating Next Right Pointers Medium
Fill the next pointer of each node in a perfect binary tree to point to its next right node.
Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Approach: O(1) space — level traversal using existing next pointers. For each level, iterate nodes and set their children's next pointers using the parent's next pointer to reach the adjacent subtree.
Complexity: Time O(n) · Space O(1)
Follow-up: LC #117 — same for non-perfect binary trees (use a dummy head technique per level).
19. Longest Consecutive Sequence Medium
Find the length of the longest consecutive integer sequence in an unsorted array. Must run in O(n).
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: [1,2,3,4]
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
Approach: Hash set. Only start counting from sequence starts (num-1 not in set). Expand the sequence rightward and count its length.
Complexity: Time O(n) · Space O(n)
Follow-up: Longest Consecutive Sequence in a Binary Tree (GFG) — DFS variant.
20. Surrounded Regions Medium
Flip all 'O' regions that are completely surrounded by 'X' to 'X'. Border-connected 'O' cells must not be flipped.
Input: [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
Output:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
Approach: DFS/BFS from all border 'O' cells, marking them safe (temporarily as 'S'). Then scan the board: 'O' → 'X' (surrounded), 'S' → 'O' (restore safe).
Complexity: Time O(m*n) · Space O(m*n)
Follow-up: Number of Enclaves (LC #1020) — count cells that cannot reach the border.
21. Rotting Oranges Medium
Fresh oranges adjacent to rotten ones rot every minute. Find the minimum minutes for all oranges to rot, or -1 if impossible.
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Approach: Multi-source BFS starting from all initially rotten oranges simultaneously. Track fresh orange count. Each BFS level = 1 minute. Return the time at which the last fresh orange rots, or -1 if any remain.
Complexity: Time O(m*n) · Space O(m*n)
Follow-up: 01 Matrix (LC #542) — same multi-source BFS from all 0-cells to find distance from each cell to nearest 0.
22. 01 Matrix Medium
Given a binary matrix, find the distance of each cell to the nearest 0.
Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]
Approach: Multi-source BFS from all 0-cells simultaneously. Initialise distance[cell] = 0 for all 0-cells, infinity for 1-cells. BFS spreads distances level by level.
Complexity: Time O(m*n) · Space O(m*n)
Follow-up: DP solution — two passes (top-left then bottom-right) achieves O(1) extra space.
23. Kth Smallest Element in a Sorted Matrix Medium
Find the kth smallest element in an n×n matrix where each row and column is sorted.
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Approach: Binary search on value. lo=matrix[0][0], hi=matrix[n-1][n-1]. For each mid, count elements ≤ mid using the staircase walk (from top-right). If count < k, move lo up; else move hi down.
Complexity: Time O(n log(max-min)) · Space O(1)
Follow-up: Min-heap approach is O(k log n) — when is it faster than binary search?
24. Validate Binary Search Tree Medium
Determine if a binary tree is a valid BST.
Input: root = [2,1,3]
Output: true
Input: root = [5,1,4,null,null,3,6]
Output: false
Approach: DFS with min/max bounds. Each node must be strictly within (min, max). Left child: (min, node.val). Right child: (node.val, max).
Complexity: Time O(n) · Space O(h)
Follow-up: Why does comparing only with the immediate parent fail for this problem?
25. BST Iterator Medium
Implement an iterator over a BST with next() returning the next smallest value and hasNext() returning whether there is a next element.
BSTIterator(root=[7,3,15,null,null,9,20])
next()→3, next()→7, hasNext()→true, next()→9, hasNext()→true, next()→15, next()→20
Approach: Explicit stack simulating inorder traversal. Constructor pushes all left nodes. next() pops the top, then pushes the right child's left spine.
Complexity: Time O(1) amortised · Space O(h)
Follow-up: Implement a reverse iterator (descending order — right-then-left traversal).
26. Path Sum III Medium
Count paths in a binary tree where the path sum equals targetSum. The path doesn't need to start or end at the root.
Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
Output: 3
Approach: DFS with a running prefix sum and a frequency map. At each node, check how many prefix sums equal (currentSum - target) — those are valid paths ending here. Add currentSum to the map, recurse, then remove it (backtrack).
Complexity: Time O(n) · Space O(n)
Follow-up: Same pattern as "Subarray Sum Equals K" (LC #560) — prefix sum hashing applied to trees.
27. Word Search Medium
Given a grid of characters and a word, return true if the word exists as a path of adjacent cells (no cell reused).
Input: board=[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word="ABCCED"
Output: true
Input: word="SEE"
Output: true
Input: word="ABCB"
Output: false
Approach: DFS from each starting cell. Mark cells as visited (temporarily '#') to prevent reuse. Explore all 4 directions. Restore cell character on backtrack.
Complexity: Time O(m*n*4^L) where L=word length · Space O(L)
Follow-up: Optimise by checking character frequency — if the board doesn't have enough of any required character, return false immediately.
28. Diameter of Binary Tree Easy
Find the length of the longest path between any two nodes in a binary tree (the path may not pass through root).
Input: root = [1,2,3,4,5]
Output: 3
Explanation: [4,2,1,3] or [5,2,1,3]
Approach: DFS returning height. At each node, candidate diameter = leftHeight + rightHeight. Update global max. Return 1 + max(leftHeight, rightHeight).
Complexity: Time O(n) · Space O(h)
Follow-up: Longest Zigzag Path in a Binary Tree (LC #1372).
29. Longest String Chain Medium
Given a list of words, find the longest chain where each word is a predecessor of the next (formed by adding one letter anywhere). Myntra frames this as a product category hierarchy.
Input: words = ["a","b","ba","bca","bda","bdca"]
Output: 4
Explanation: "a" → "ba" → "bda" → "bdca"
Approach: Sort words by length. dp[word] = longest chain ending at word. For each word, try removing each character — if the result is in dp, dp[word] = max(dp[word], dp[predecessor]+1).
Complexity: Time O(n * L²) where L = max word length · Space O(n)
Follow-up: Return the actual chain of words, not just its length.
30. Maximum XOR of Two Numbers Medium
Find the maximum XOR of any two elements in an array.
Input: nums = [3,10,5,25,2,8]
Output: 28
Explanation: 5 XOR 25 = 28.
Approach: Build a binary Trie from all numbers (MSB first). For each number, greedily traverse the Trie choosing the opposite bit at each step to maximise XOR.
Complexity: Time O(n * 32) · Space O(n * 32)
Follow-up: Maximum XOR With an Element From Array (LC #1707) — offline queries with sorted Trie inserts.
31. Minimum Domino Rotations Medium
Given two arrays tops and bottoms representing domino values, find the minimum rotations to make all tops or all bottoms the same value.
Input: tops=[2,1,2,4,2,2], bottoms=[5,2,6,2,3,2]
Output: 2
Input: tops=[3,5,1,2,3], bottoms=[3,6,3,3,4]
Output: -1
Approach: The target value must be tops[0] or bottoms[0]. For each candidate value, count rotations needed to make all tops or all bottoms that value. If any position has neither tops[i] nor bottoms[i] equal to the candidate, it's impossible.
Complexity: Time O(n) · Space O(1)
Follow-up: What if you can rotate any domino (not just to make all equal) — most constrained assignment problem.
32. Shortest Subarray with Sum at Least K Hard
Find the length of the shortest subarray with sum ≥ k. Array may contain negative numbers.
Input: nums = [2,-1,2], k = 3
Output: 3
Input: nums = [1,2], k = 4
Output: -1
Approach: Prefix sum array. Monotonic deque of indices where prefix sums are increasing. For each i, pop from front while prefix[i] - prefix[deque.front()] >= k (record the window length). Pop from back while prefix[deque.back()] >= prefix[i].
Complexity: Time O(n) · Space O(n)
Follow-up: Why doesn't the standard sliding window work when negatives are present?
33. Coin Change 2 Medium
Count the number of combinations (not permutations) that make up a given amount using coin denominations.
Input: amount = 5, coins = [1,2,5]
Output: 4
Explanation: 5=5, 5=2+2+1, 5=2+1+1+1, 5=1+1+1+1+1
Input: amount = 3, coins = [2]
Output: 0
Approach: dp[i] = number of combinations summing to i. Iterate coins in outer loop and amounts in inner loop (this ensures each coin is counted once per combination). dp[0]=1, dp[i] += dp[i-coin].
Complexity: Time O(amount * n) · Space O(amount)
Follow-up: Why does iterating amounts first (like Combination Sum IV) give permutations instead of combinations?
34. Design Add and Search Words Medium
Design a data structure supporting addWord(word) and search(word) where search supports '.' as a wildcard matching any single character.
WordDictionary wd
wd.addWord("bad"), wd.addWord("dad"), wd.addWord("mad")
wd.search("pad")→false, wd.search("bad")→true, wd.search(".ad")→true, wd.search("b..")→true
Approach: Trie where addWord inserts normally. search does DFS — at '.' try all 26 children recursively; at a regular character descend only the matching child.
Complexity: O(L) add · O(26^L) search worst case with many wildcards · Space O(total chars)
Follow-up: Magic Dictionary (LC #676) — search with exactly one character changed.
35. Maximum Width Ramp Medium
Find the maximum width ramp (i, j) where i < j and nums[i] <= nums[j]. Width = j - i.
Input: nums = [6,0,8,2,1,5]
Output: 4
Explanation: (1,5): nums[1]=0 <= nums[5]=5, width=4.
Input: nums = [9,8,1,0,1,9,4,0,4,1]
Output: 7
Approach: Build a decreasing-prefix stack (indices with decreasing values from left). Scan right to left — for each j, pop from the stack while nums[stack.top()] <= nums[j], recording max width.
Complexity: Time O(n) · Space O(n)
Follow-up: Why does scanning right-to-left guarantee finding the widest ramp for each stack element?
36. Wiggle Sort II Medium
Rearrange an array in-place so that nums[0] < nums[1] > nums[2] < nums[3]... (strict inequality).
Input: nums = [1,5,1,1,6,4]
Output: [1,6,1,5,1,4]
Input: nums = [1,3,2,2,3,1]
Output: [2,3,1,3,1,2]
Approach: Find the median (QuickSelect). Use 3-way partition (Dutch National Flag) around the median. Map indices so that all smaller elements fill even positions and larger elements fill odd positions (reverse-order interleaving to avoid adjacent equal elements).
Complexity: Time O(n) · Space O(1)
Follow-up: Why does simple sort + interleave fail for inputs with many duplicate medians?
37. Longest Turbulent Subarray Medium
A turbulent subarray alternates between strict increases and decreases. Find the length of the longest such subarray.
Input: arr = [9,4,2,10,7,8,8,1,9]
Output: 5
Explanation: [4,2,10,7,8]
Input: arr = [4,8,12,16]
Output: 2
Approach: Sliding window. Track the window start anchor. For each pair (i-1, i), check if the comparison sign flips from the previous pair. If not (or equal), reset anchor to i-1 (or i if equal). Track max window.
Complexity: Time O(n) · Space O(1)
Follow-up: Wiggle Subsequence (LC #376) — not required to be contiguous.
38. Design Fashion Recommendation Engine (LLD) Medium
Design Myntra's fashion recommendation engine. Given a user's browsing history, purchase history, and style preferences, suggest a ranked list of products. The engine must support adding new recommendation strategies without modifying existing code.
Engine.recommend(userId, context) → [Product]
Engine.addStrategy(strategy: RecommendationStrategy)
Engine.updateUserProfile(userId, event: BrowseEvent | PurchaseEvent)
Approach: Classes: UserProfile (browsedItems, purchasedItems, preferredCategories, preferredBrands), Product (id, category, brand, tags, price), RecommendationStrategy (interface: recommend(UserProfile) → List
39. Design Shopping Cart with Discounts (LLD) Medium
Design a Shopping Cart that supports adding/removing items, applying coupons (flat, percentage, BOGO), and checking out. Discounts can stack with each other or be mutually exclusive based on configuration.
Cart.addItem(productId, qty)
Cart.removeItem(productId)
Cart.applyCoupon(couponCode)
Cart.getTotal() → {subtotal, discount, finalAmount}
Cart.checkout() → Order
Approach: Classes: Cart (items: Map<Product,Qty>, appliedCoupons), CartItem (product, quantity, basePrice), Coupon (code, discountStrategy, eligibilityRules, stackable), DiscountStrategy (interface: compute(cartItems)→discountAmount). Strategies: FlatDiscount, PercentageDiscount, BuyOneGetOne. getTotal applies all compatible coupons: if stackable=false only the best coupon applies; if stackable=true all apply sequentially. PricingEngine computes subtotal and applies discounts in priority order. Key Design Principles: Strategy for discount types, Chain of Responsibility for eligibility, immutable CartItem prices to prevent tampering Follow-up: How do you handle a BOGO offer when the cart has an odd number of qualifying items?
40. Design Inventory Management System (LLD) Medium
Design Myntra's inventory system. Each SKU (product + size + colour) has a stock count at each warehouse. Support reserving stock for an order, releasing reservations (on cancellation), and fulfilling (on dispatch).
Inventory.reserve(skuId, warehouseId, qty, orderId) → success/failure
Inventory.release(orderId)
Inventory.fulfill(orderId)
Inventory.getAvailableStock(skuId) → qty
Approach: Classes: SKU (id, productId, size, colour), Warehouse (id, location), InventoryRecord (sku, warehouse, totalQty, reservedQty), Reservation (orderId, sku, warehouse, qty, status). reserve checks availableQty = totalQty - reservedQty ≥ qty, then atomically increments reservedQty. release decrements reservedQty. fulfill decrements both totalQty and reservedQty. Use optimistic locking (version column) for concurrent updates. Key Design Principles: Atomic reserve/release with optimistic locking, separation of physical vs. available stock, idempotent operations using orderId Follow-up: How do you handle multi-warehouse fulfillment when a single warehouse doesn't have sufficient stock?
41. Design Myntra Search and Catalog System (HLD) Hard
Design Myntra's product search and catalog system. Users search by keyword, filter by brand/size/price/colour, and sort by relevance, price, or popularity. Catalog has 10M+ products updated by thousands of brands daily.
Functional: search(query, filters, sort, page), getProduct(productId), updateCatalog(brandId, products)
Non-functional: <200ms search latency, 10M products, 5K writes/min from brands, personalised ranking
Approach: Write path: Brand portal → Catalog Service → MySQL (product master) → Kafka change event → Indexer Service → Elasticsearch. Elasticsearch stores all searchable fields (name, brand, tags, category) plus filterable fields (price, size, colour). Search path: Query → Search Service → Elasticsearch (BM25 relevance + filters) → Personalisation Re-ranker (uses user's style profile to re-rank top 100 results) → response. Image search: CNN embedding stored in a vector DB (Faiss), nearest-neighbour lookup returns similar products. Out-of-stock items deprioritised in ranking but still indexed. Key Concepts: Elasticsearch for full-text + faceted search, Kafka for async catalog indexing, personalisation re-ranking, vector similarity for visual search Follow-up: How do you handle a brand updating 50,000 products simultaneously without degrading search latency?
42. Design Flash Sale System (HLD) Hard
Design Myntra's End of Reason Sale (EORS) / Big Billion Days equivalent — a flash sale with limited inventory at discounted prices, handling 100× normal traffic. Must prevent overselling.
Functional: addToCart(userId, skuId), checkout(cartId), getSaleItems(filters)
Non-functional: 50M concurrent users, prevent oversell, <500ms add-to-cart, graceful degradation
Approach: Pre-sale: warm all sale item data into Redis. Inventory counter per SKU stored in Redis (DECR command is atomic — prevents oversell). add-to-cart: Redis DECR on inventory; if < 0 INCR back and reject; else create a cart reservation with 15-min TTL. Expired reservations automatically release inventory via Redis TTL + Lua script. Traffic shaping: virtual waiting room (queue) for first 10 minutes — users get a token to enter; token validated before add-to-cart. Database writes only happen at checkout (async via Kafka), not at add-to-cart. CDN caches product pages; only inventory check hits backend. Auto-scaling: pre-scale to 10× before sale starts. Key Concepts: Redis atomic DECR for oversell prevention, virtual waiting room, reservation TTL, async DB writes, CDN for product pages Follow-up: How do you handle the case where 1M users all click "add to cart" for a 100-unit SKU at the exact sale start time?
43. Design Order Management System (HLD) Hard
Design Myntra's order management system (OMS) that handles order placement, payment, warehouse picking, shipping, and delivery tracking.
Functional: placeOrder(cart, paymentMethod), trackOrder(orderId), cancelOrder(orderId), returnOrder(orderId)
Non-functional: 500K orders/day, exactly-once order placement, real-time status updates
Approach: Order lifecycle as a state machine: CREATED → PAYMENT_PENDING → CONFIRMED → WAREHOUSE_ASSIGNED → PACKED → SHIPPED → DELIVERED (with CANCELLED and RETURNED as terminal states). Each state transition is an event on Kafka. Order Service persists state to MySQL and publishes events. Downstream services consume events: Payment Service, Warehouse Management System (WMS), Logistics Service (Delhivery/Ekart API). Idempotency: order has a unique clientOrderId to prevent duplicate placement. Cancellation: if not yet PACKED, release inventory immediately and trigger refund. Return: creates a reverse-logistics pickup request. Real-time tracking: WebSocket connection updated by Kafka events from the logistics partner. Key Concepts: Order state machine, Kafka event-driven architecture, Saga pattern for cross-service transactions, idempotency, WebSocket for tracking Follow-up: How do you handle a payment success but order creation failure (partial failure in the Saga)?
44. Count Complete Tree Nodes Medium
Count nodes in a complete binary tree faster than O(n).
Input: root = [1,2,3,4,5,6]
Output: 6
Approach: Compare left-most and right-most depth. If equal, the tree is a perfect binary tree → 2^height - 1 nodes. Otherwise recurse on both subtrees. Each recursion reduces the problem by half.
Complexity: Time O(log²n) · Space O(log n)
Follow-up: Why is this O(log²n) and not O(n)?
45. Kth Smallest in BST Easy
Return the kth smallest value in a BST.
Input: root = [3,1,4,null,2], k = 1
Output: 1
Approach: Iterative inorder traversal using a stack. Pop the kth node and return its value — no need to traverse the whole tree.
Complexity: Time O(h+k) · Space O(h)
Follow-up: If the BST is modified frequently and kth-smallest is queried often, augment each node with its left-subtree size for O(h) query.
46. Number of Islands — Counting Distinct Components Medium
Myntra asks this to test graph traversal on grids — interviewers specifically expect candidates to recognise the grid as an adjacency structure.
Input: grid=[["1","1","0","0"],["1","1","0","0"],["0","0","1","0"],["0","0","0","1"]]
Output: 3
Approach: DFS/BFS from each unvisited '1', marking all connected cells as visited. Count how many times you start a new DFS.
Complexity: Time O(m*n) · Space O(m*n)
Follow-up: Max Area of Island (LC #695), Number of Distinct Islands (LC #694 — shape-aware).
47. Stone Game IV Hard
Two players take turns removing a perfect square number of stones from a pile of n. The player who removes the last stone wins. Can the first player win?
Input: n = 1
Output: true
Input: n = 7
Output: false
Input: n = 17
Output: false
Approach: dp[i] = true if the current player wins with i stones. dp[0] = false (no stones = lose). For each i, try all perfect squares k² ≤ i: if dp[i - k²] == false, dp[i] = true (opponent loses after this move).
Complexity: Time O(n * sqrt(n)) · Space O(n)
Follow-up: Stone Game V (LC #1563) and Stone Game VI (LC #1686) use different rules — same DP framework.
48. Subarray Sum Equals K Medium
Count the total number of continuous subarrays whose sum equals k.
Input: nums = [1,1,1], k = 2
Output: 2
Input: nums = [1,2,3], k = 3
Output: 2
Approach: Prefix sum with a hash map. For each prefix sum s, count += map[s - k]. Then add s to the map. Initialise map with {0: 1}.
Complexity: Time O(n) · Space O(n)
Follow-up: Continuous Subarray Sum divisible by k (LC #523) — same idea using modular prefix sums.
49. Design Personalisation Engine (HLD) Hard
Design Myntra's homepage personalisation engine that shows each user a customised feed of products, brands, and editorial content based on their style profile, browsing history, and purchase patterns.
Functional: getPersonalisedFeed(userId, page) → [FeedItem], recordEvent(userId, event)
Non-functional: <200ms feed latency, 50M DAU, real-time event ingestion, cold-start for new users
Approach: Online path: User opens app → Feed Service checks Redis for pre-computed feed for userId (TTL 5 min) → returns cached feed. Offline path: every hour, a Recommendation Job reads the Feature Store (user embeddings, item embeddings from collaborative filtering), computes top-1000 items per user, writes to Redis. Real-time event path: user browse/purchase events → Kafka → Feature Update Service → updates user embedding in the Feature Store incrementally. Cold start (new user): use demographic/device signals + trending items. A/B testing: Feed Service routes % of traffic to experimental recommendation models via a feature flag. Editorial content (banners, collections) is blended in by a Content Mixer at a fixed ratio. Key Concepts: Pre-computed recommendations in Redis, collaborative filtering embeddings, real-time feature updates via Kafka, cold-start fallback, A/B testing via feature flags Follow-up: How do you prevent the "filter bubble" where users only see more of what they already like?
50. Minimum Number of Arrows to Burst Balloons Medium
Balloons are represented by intervals [start, end]. An arrow shot at x bursts all balloons with start ≤ x ≤ end. Find the minimum number of arrows.
Input: points = [[10,16],[2,8],[1,6],[7,12]]
Output: 2
Input: points = [[1,2],[3,4],[5,6],[7,8]]
Output: 4
Approach: Sort by end coordinate. Shoot the first arrow at the earliest end. All balloons with start ≤ that end are burst. Move to the next unbursted balloon and repeat.
Complexity: Time O(n log n) · Space O(1)
Follow-up: Non-Overlapping Intervals (LC #435) — same greedy, different framing. Prove they're equivalent.
Preparation Tips
Myntra's DSA rounds focus heavily on graph traversal on grids (Rotting Oranges, Pacific Atlantic Water Flow, 01 Matrix, Surrounded Regions) and backtracking with pruning (Word Search II, Combination Sum, N-Queens). These two clusters account for the majority of rejections. For LLD, prepare a Shopping Cart with discount logic and an Inventory system with atomic reservation. For HLD, the Flash Sale architecture (Redis atomic DECR, virtual waiting room, reservation TTL) is Myntra's most asked design problem given their EORS sale — know it cold. The Personalisation Engine is a strong differentiator for SDE-2 roles.
Join Telegram group to get the latest Myntra OA questions and connect with candidates currently in the Myntra interview process.