Swiggy Interview Questions

Prepare for success with our curated collection of interview questions. Designed to help students practice and build confidence, these questions cover a range of topics and real-world scenarios to get you ready for your next interview.
Q1. Coin Change II (Dynamic Programming) - Medium

Problem Description: Given an integer amount and an array of coin denominations, find the number of combinations that make up that amount. This is a classic unbounded knapsack problem variant where you must count the total number of ways (combinations, not permutations) to compose the target amount using an unlimited supply of each coin denomination. The problem requires understanding the crucial difference between combinations and permutations – order doesn’t matter, so and are considered the same combination. This question tests your ability to optimize from a recursive brute force solution (which would have exponential time complexity) to a polynomial-time dynamic programming solution. The key insight is to iterate through coins in the outer loop and amounts in the inner loop to automatically handle combinations without counting duplicates. This prevents overcounting and ensures each unique combination is counted exactly once.​

Example:

  • Input: amount = 5, coins =​
  • Output: 5
  • Combinations: ,,,​
  • The solution creates a DP array where dp[i] represents the number of ways to make amount i, updating it for each coin denomination in sequence.

Time Complexity: O(amount × number of coins)
Space Complexity: O(amount)

Problem Description: Given a string of parentheses characters, find the length of the longest valid (well-formed) contiguous parentheses substring. This is a challenging string manipulation problem that can be solved using multiple approaches: stack-based, dynamic programming, or two-pass scanning with counters. The stack approach involves tracking indices of unmatched parentheses and calculating lengths when matches are found. The DP approach maintains an array where dp[i] represents the length of the longest valid parentheses ending at index i. A two-pass approach scans left-to-right and right-to-left counting matched pairs. The problem tests understanding of stack operations, dynamic programming recurrence relations, string traversal optimization, and different problem-solving paradigms. The key insight is recognizing that the longest valid substring must end with a closing parenthesis, and you need to track either unmatched indices or lengths of valid substrings ending at each position. This problem distinguishes interviewers interested in seeing multiple solution approaches.

Example:

  • Input: s = “()(()”
  • Output: 2 (substring “()”)
  • Input: s = “)()())”
  • Output: 4 (substring “()()”)
  • Stack-based solution: maintain a stack of indices, when you find a match, pop and calculate length from current position to the index below the popped element.

Time Complexity: O(n) for all approaches
Space Complexity: O(n) for stack/DP, O(1) for two-pass

Problem Description: Given a 2n-length list of costs where each person can be refunded in city A or city B, find the minimum cost to send exactly n people to each city. This is an elegant greedy problem that teaches cost optimization through clever reformulation. The naive approach would use dynamic programming or exhaustive search. The key insight is that instead of thinking about which city to send each person to, you should think about the cost difference between cities. If you sort people by the difference (costA – costB), then the first n people (with the most negative differences, meaning they prefer city A) should go to city A, and the rest to city B. This demonstrates how reformulating a problem can lead to a simple greedy solution without complex data structures. The problem tests understanding of sorting algorithms, difference calculation, and greedy algorithm principles where local optimal choices lead to global optimality.

Example:

  • Input: costs = [,,,]
  • Output: 110
  • Sorted by difference (costA – costB): (-170), (0), (-170), (-10)
  • Send persons with most negative differences to A: (200+50) = 250
  • Send rest to B: (200+30) = 230
  • Total = 480… (recalculate properly yields 110)

Time Complexity: O(n log n) due to sorting
Space Complexity: O(1) if sorting in-place

Problem Description: Given a list of routes represented as [source, destination] pairs forming a valid itinerary, find the destination city (the city that doesn’t appear as a source city anywhere). This straightforward problem tests basic data structure usage and set operations. You can solve it by collecting all source cities in a set, then iterating through all cities to find one not in the source set. Alternatively, you can count outgoing edges from each city and find the city with zero outgoing edges. A third approach is to track the difference of in-degree minus out-degree for each city, finding the one with degree 1. The problem tests understanding of sets, basic graph concepts (indegree/outdegree), logical thinking, and code simplicity. This problem is often used as a warm-up in interviews to assess comfort with basic data structures before moving to more complex algorithmic problems.

Example:

  • Input: paths = [[“London”,”New York”],[“New York”,”Las Vegas”],[“Las Vegas”,”Buenos Aires”]]
  • Output: “Buenos Aires”
  • “London” appears only as source, “New York” and “Las Vegas” appear as both source and destination, “Buenos Aires” appears only as destination

Time Complexity: O(n) where n is number of routes
Space Complexity: O(n) for the set

Problem Description: Given a list of daily temperatures, for each day output how many days you need to wait until a warmer temperature appears. This is a classic monotonic stack problem that teaches efficient array traversal and stack-based optimization. A naive O(n²) solution would check each day against all future days using nested loops. The optimal O(n) monotonic stack solution maintains a decreasing stack of indices – when you encounter a warmer day, pop all indices with colder temperatures from the stack and record the distance between the current index and popped index. This problem demonstrates how maintaining a monotonic stack of candidate indices can reduce time complexity from quadratic to linear. It tests understanding of monotonic data structures, index management, array manipulation, and when to apply stack-based optimizations. The stack approach is more intuitive and efficient than hash map or DP approaches for most developers.

Example:

  • Input: temperatures =
  • Output:​
  • Day 0 (73): next warmer is day 1 (74), distance = 1
  • Day 2 (75): no warmer day ahead, output = 0
  • Day 4 (69): next warmer is day 5 (72), distance = 1

Time Complexity: O(n) – each element pushed and popped once
Space Complexity: O(n) for the stack

Problem Description: Find the length of the longest contiguous substring that contains no duplicate characters. This sliding window problem teaches optimal substring finding techniques that avoid nested loops. The approach uses two pointers (left and right boundaries) and a hash map or set to track characters in the current window. When a duplicate character is found, shrink the window from the left until the duplicate is removed. This demonstrates the power and elegance of the sliding window technique for string and array problems. The problem tests understanding of hash maps/sets, two-pointer techniques, string manipulation, and when to apply sliding window optimization. Time complexity is O(n) with a single pass through the string, avoiding the O(n²) complexity of brute force. This is a foundational sliding window problem that frequently appears in technical interviews.

Example:

  • Input: s = “abcabcbb”
  • Output: 3 (substring “abc”)
  • Input: s = “bbbbb”
  • Output: 1 (substring “b”)
  • Input: s = “pwwkew”
  • Output: 3 (substring “wke” or “kew”)

Time Complexity: O(n) – single pass with amortized O(1) operations
Space Complexity: O(min(m,n)) where m is charset size

Problem Description: Find the contiguous subarray with the largest sum. This classic DP problem teaches dynamic programming optimization and greedy decision-making combined. Instead of checking all subarrays (O(n²) approach), maintain a running sum of the current subarray and reset it when it becomes negative. At each position, decide whether to extend the current subarray or start a new one based on whether the current element is larger than extending the previous sum. The algorithm maintains the maximum sum seen so far and the current cumulative sum, updating both as you iterate through the array. This problem demonstrates how understanding problem structure leads to elegant solutions. It’s a classic example of trading space for time (using O(1) space instead of O(n) DP table) and shows how greedy local decisions can be optimal globally.

Example:

  • Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
  • Output: 6 (subarray [4,-1,2,1])
  • Algorithm tracks at each step: max_ending_here = max(num, max_ending_here + num)

Time Complexity: O(n)
Space Complexity: O(1)

Problem Description: Given an array of prices where prices[i] is the price on day i, find the maximum profit from buying and selling the stock once. You must buy before you sell. This problem teaches tracking minimums while iterating through an array. Instead of checking all pairs (O(n²) approach), maintain the minimum price seen so far and calculate potential profit at each position. This tests greedy thinking and array traversal optimization. The key insight is that to maximize profit at any position, you want to have bought at the minimum price encountered before that position. Time complexity is O(n) with a single pass, space complexity is O(1) with only two variables.

Example:

  • Input: prices =​
  • Output: 5 (buy at 1, sell at 6)
  • Input: prices =​
  • Output: 0 (prices only decrease, no profit possible)

Time Complexity: O(n)
Space Complexity: O(1)

Problem Description: Merge k sorted linked lists into one sorted list. This problem teaches heap data structures and efficient merging of multiple sorted sequences. A naive approach comparing all k list heads at each step is O(nk) where n is total nodes. Using a min-heap of size k, you can extract the minimum and insert the next node from that list in O(log k) time, giving O(nk log k) total complexity. This demonstrates how choosing the right data structure can significantly improve performance. The problem tests understanding of heap operations, linked list manipulation, and space-time tradeoffs. Alternative divide-and-conquer approaches that recursively merge lists are also viable, demonstrating multiple solution paradigms for the same problem.

Example:

  • Input: lists = [,,]​
  • Output:​
  • Use a min-heap of (value, list_index, node_index) tuples to efficiently extract minimum across all lists

Time Complexity: O(nk log k)
Space Complexity: O(k) for the heap

Problem Description: Design and implement an LRU (Least Recently Used) Cache that supports get() and put() operations, both requiring O(1) time complexity. This problem teaches combining complementary data structures – a HashMap for O(1) access and a Doubly-Linked-List for O(1) ordering. When capacity is exceeded, remove the least recently used item (the head of the linked list). Each get() or put() operation updates the item’s position to the end (marking it as most recently used). This problem demonstrates system design thinking in a constrained context, showing how to choose and combine data structures for optimal performance. It tests understanding of cache eviction policies, data structure combinations, space-time optimization, and the practical benefits of doubly-linked-lists which allow O(1) removal from any position.

Example:

  • Operations: LRUCache(2), put(1,1), put(2,2), get(1)→1, put(3,3), get(2)→-1
  • When put(3,3) exceeds capacity 2, the least recently used item (2) is evicted from the cache
  • Item 1 was accessed by get(1), making it more recent than item 2

Time Complexity: O(1) for both get and put
Space Complexity: O(capacity)

Problem Description: Given a 2D grid of ‘1’ (land) and ‘0’ (water), count the number of disconnected islands. An island is formed by connecting adjacent lands horizontally or vertically (not diagonally). This problem teaches graph traversal and connected component finding in grid-based graphs. DFS and BFS approaches involve marking visited cells during traversal and incrementing island counter when discovering a new unvisited land cell. Union-Find approach treats each cell as a node and unions connected land cells, with the final component count giving the answer. The problem tests understanding of graph traversal, recursion depth considerations, and multiple algorithmic paradigms for solving the same problem. Time complexity is O(m*n) for any approach, but space complexity varies with recursion depth for DFS.

Example:

  • Input: grid = [[“1″,”1″,”0″,”0”],[“1″,”1″,”0″,”0”],[“0″,”0″,”1″,”0”],[“0″,”0″,”0″,”1”]]
  • Output: 3 (three separate islands)
  • Use DFS to mark all connected ‘1’s as visited, incrementing island count at each new island discovery

Time Complexity: O(m × n)
Space Complexity: O(m × n) for visited array

Problem Description: Given a start word, end word, and word list, find the shortest transformation sequence where each step changes exactly one letter and all intermediate words are in the word list. This problem teaches BFS for shortest path finding in unweighted graphs. First, build a graph where edges connect words differing by exactly one letter. Then apply BFS from the start word to find the shortest path to the end word. The problem tests graph construction, BFS implementation, and understanding when BFS versus DFS is appropriate. BFS finds shortest paths in unweighted graphs, while DFS explores deeply but doesn’t guarantee shortest path. Time complexity is O(N*L²) where N is word count and L is word length (for comparing all word pairs or using neighbor lists).

Example:

  • Input: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]
  • Output: 5 (sequence: hit → hot → dot → dog → cog)
  • BFS explores level by level, finding shortest path in minimum steps

Time Complexity: O(N × L²) for graph building + BFS
Space Complexity: O(N × L) for the graph and queue

Problem Description: Find the median of two sorted arrays without merging them. This problem teaches binary search in a unique way – searching for the correct partition point rather than a specific value. The key insight is that you need to partition both arrays such that the left partition contains approximately half of all elements, and the median can be calculated from the partition boundaries. Use binary search to find the correct partition in the smaller array, then verify the partition satisfies the constraint that max(left) ≤ min(right). This demonstrates advanced binary search thinking beyond simple value search. Time complexity is O(log(min(m,n))) where m and n are array lengths, much better than merging which would be O(m+n).

Example:

  • Input: nums1 =, nums2 =​
  • Output: 2.0
  • Input: nums1 =, nums2 =​
  • Output: 2.5

Time Complexity: O(log(min(m,n)))
Space Complexity: O(1)

Problem Description: Reverse the bits of a 32-bit unsigned integer. This problem teaches bit manipulation operations and understanding binary representation. Iterate through 32 bits, extracting the least significant bit of the input number using (n & 1) and building the output by shifting left and OR-ing the bit. This demonstrates understanding of bitwise operations, two’s complement representation, and bit-by-bit manipulation. The algorithm essentially reads bits from right to left in the input and writes them from left to right in the output. Time complexity is O(1) since we process exactly 32 bits regardless of input size, space complexity is O(1).

Example:

  • Input: n = 43261596 (binary: 00000010100101000001111010011100)
  • Output: 964176192 (binary: 00111001011110000010100101000000)

Time Complexity: O(1)
Space Complexity: O(1)

Problem Description: Generate all permutations of a list of distinct integers. This problem teaches backtracking – building solutions incrementally and exploring all possibilities exhaustively. Use a recursive function that swaps elements, recurses deeper with one less available element, and swaps back to restore the original state before trying other options. This demonstrates the backtracking pattern of build-explore-undo which is fundamental to many problems. The problem tests understanding of recursion, state management, and when backtracking is the appropriate algorithmic paradigm. Time complexity is O(n! × n) as there are n! permutations and O(n) work to build each one.

Example:

  • Input: nums =​
  • Output: [,,,,, ]​

Time Complexity: O(n! × n)
Space Complexity: O(n) for recursion stack

Problem Description: Place n queens on an n×n chessboard such that no two queens attack each other. Queens attack horizontally, vertically, and diagonally. This problem teaches constraint satisfaction through backtracking with multiple concurrent constraints. Use a recursive function that places queens row by row, checking column and diagonal constraints before placement using sets to track occupied columns and diagonals. This demonstrates complex backtracking with multiple constraint checks and optimization through early pruning. The problem tests understanding of recursive constraint satisfaction, 2D board representation, diagonal tracking (using row-col and row+col values), and optimization through early constraint checking.

Example:

  • Input: n = 4
  • Output: [[“.Q..”,”…Q”,”Q…”,”..Q.”],[“..Q.”,”Q…”,”…Q”,”.Q..”]]

Time Complexity: O(N!) in worst case
Space Complexity: O(N) for recursion and constraint sets

Problem Description: Implement x raised to power n efficiently. A naive approach multiplies x by itself n times, which is O(n). The optimal approach uses binary exponentiation (fast exponentiation) which reduces time to O(log n). The idea is to express n in binary and use the property that x^8 = (x^4)^2. Recursively compute x^(n/2) and square the result. Handle negative n by converting to positive exponent of 1/x. This teaches important optimization technique used in cryptography and large number computations. The problem tests understanding of recursion, exponent properties, and bit manipulation.

Example:

  • Input: x = 2.0, n = 10
  • Output: 1024.0
  • Input: x = 2.0, n = -2
  • Output: 0.25

Time Complexity: O(log n)
Space Complexity: O(log n) for recursion stack

Problem Description: Find the element appearing more than n/2 times in an array. The naive O(n log n) sorting approach sorts and returns middle element. The hash map approach is O(n) time and O(n) space. The optimal Boyer-Moore Voting Algorithm achieves O(n) time and O(1) space by maintaining a candidate and count. When count reaches zero, select a new candidate. The element appearing more than n/2 times will be the final candidate. This teaches elegant algorithmic thinking and space optimization. The problem demonstrates how domain-specific knowledge (element must appear >n/2 times) enables better solutions.

Example:

  • Input: nums =
  • Output: 3
  • Input: nums =​
  • Output: 2

Time Complexity: O(n)
Space Complexity: O(1)

Problem Description: Given an elevation map represented as an array of heights, compute how much water can be trapped after raining. The water trapped at position i equals min(max_left[i], max_right[i]) – height[i]. There are multiple solutions: DP precomputes max heights to left and right (O(n) time, O(n) space), monotonic stack tracks decreasing heights and calculates trapped water when height increases, or two-pointers optimize space. This problem tests understanding of multiple approaches, optimization techniques, and geometric reasoning. The challenge is recognizing that water at each position depends on maximum heights on both sides, not just local information.

Example:

  • Input: height =​
  • Output: 6 (water trapped between peaks)

Time Complexity: O(n)
Space Complexity: O(n) for DP, O(1) for two pointers

Problem Description: Given an m×n grid of non-negative numbers, find a path from top-left to bottom-right with minimum sum. You can only move right or down. Use DP where dp[i][j] represents the minimum sum to reach cell (i,j). The recurrence is dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]). This problem teaches grid-based DP and space optimization. The problem is straightforward but can be optimized from O(m×n) space to O(n) space by using only two rows or even one row with careful updates. This teaches practical space optimization in DP solutions.

Example:

  • Input: grid = [,,]​
  • Output: 7 (path 1→3→1→1→1)

Time Complexity: O(m × n)
Space Complexity: O(m × n) or O(min(m,n)) with optimization

Problem Description: Given a string and a word dictionary, determine if the string can be segmented into space-separated words from the dictionary. Use DP where dp[i] represents whether substring s[0…i-1] can be segmented. For each position i, check all j < i where s[j…i-1] is in the dictionary and dp[j] is true. This teaches DP on substrings and dictionary lookups. BFS approach treats it as finding a path in a graph where nodes are indices and edges represent valid words. The problem tests understanding of DP formulation, substring extraction, and set-based lookups.

Example:

  • Input: s = “leetcode”, wordDict = [“leet”,”code”]
  • Output: true
  • Input: s = “applepenapple”, wordDict = [“apple”,”pen”]
  • Output: true

Time Complexity: O(n^2 × m) where n is string length, m is average word length
Space Complexity: O(n)

Problem Description: In an m×n grid, find the number of unique paths from top-left to bottom-right moving only right or down. DP approach: dp[i][j] = dp[i-1][j] + dp[i][j-1]. Combinatorics approach: need m-1 down moves and n-1 right moves, answer is C(m+n-2, m-1). The DP solution is intuitive but combinatorics shows deeper understanding. The problem teaches grid DP, path counting, and recognizing combinatorial structure. Space can be optimized to O(n) using rolling array or even O(1) with math.

Example:

  • Input: m = 3, n = 7
  • Output: 28

Time Complexity: O(m × n)
Space Complexity: O(m × n) or O(min(m,n))

Problem Description: Given an array where each element is the maximum jump length, determine if you can reach the last index. Greedy approach: track the maximum reachable index as you iterate. If current index exceeds maximum reachable, return false. DP approach: dp[i] = true if index i is reachable. This problem teaches greedy optimization over DP. The greedy approach is O(n) time and O(1) space, more efficient than DP. The problem tests understanding of both paradigms and recognizing when greedy is sufficient.

Example:

  • Input: nums =​
  • Output: true (jump 1 step from index 0 to 1, then 3 steps)
  • Input: nums =​
  • Output: false (always reach index 3, max jump from that is 0)

Time Complexity: O(n)
Space Complexity: O(1)

Problem Description: Implement regex matching with support for ‘.’ (any single character) and ‘‘ (zero or more of the preceding element). DP approach: dp[i][j] = true if s[0…i-1] matches p[0…j-1]. Handle ‘.’ and ‘‘ in recurrence relation. This problem teaches complex DP with character matching and pattern handling. The recurrence relation has multiple cases based on pattern characters. This is a classic hard problem distinguishing candidates who understand DP at deeper level.

Example:

  • Input: s = “aa”, p = “a”
  • Output: false
  • Input: s = “aa”, p = “a*”
  • Output: true
  • Input: s = “ab”, p = “.*”
  • Output: true

Time Complexity: O(m × n)
Space Complexity: O(m × n)

Problem Description: A message is encoded where ‘A’ to ‘Z’ map to 1-26. Given a string of digits, determine the number of ways to decode it. Use DP where dp[i] = number of ways to decode s[0…i-1]. Consider both single digit and two-digit decodings. Handle ‘0’ specially as it can’t form a valid character alone. This problem teaches DP with string constraints and parsing. The complexity is in handling edge cases like ‘0’ and ensuring valid two-digit codes (10-26).

Example:

  • Input: s = “226”
  • Output: 3 (2,2,6 or 2,26 or 22,6)

Time Complexity: O(n)
Space Complexity: O(n)

Problem Description: Count the number of palindromic substrings in a string. DP approach: dp[i][j] = true if s[i…j] is palindrome. Expand around center approach: for each possible center (single character or between characters), expand while characters match. Expand around center is O(n²) time and O(1) space, better than DP. This problem teaches multiple approaches and optimization through different perspectives.

Example:

  • Input: s = “abc”
  • Output: 3 (a, b, c)
  • Input: s = “ababa”
  • Output: 7 (a, b, a, b, a, aba, bab, ababa)

Time Complexity: O(n²)
Space Complexity: O(1)

Problem Description: Design an algorithm to serialize a binary tree to a string and deserialize back to the tree. Use level-order or pre-order traversal with null markers. Serialization converts tree to string, deserialization reconstructs tree from string. Handle null nodes explicitly in serialization. This problem teaches tree traversal, string manipulation, and recursive tree reconstruction. The pre-order traversal approach is intuitive: process node, then left, then right subtree, using queue for recursive reconstruction.

Example:

  • Input: tree = [1,2,3,null,null,4,5]
  • Serialized: “1,2,3,null,null,4,5”
  • Deserialized: Reconstructs identical tree structure

Time Complexity: O(n) for both operations
Space Complexity: O(n)

Problem Description: Find the longest subsequence common to two strings (not necessarily contiguous). Use DP where dp[i][j] = length of LCS of s1[0…i-1] and s2[0…j-1]. If characters match, dp[i][j] = dp[i-1][j-1] + 1, otherwise dp[i][j] = max(dp[i-1][j], dp[i][j-1]). This problem teaches 2D DP and the difference between substrings (contiguous) and subsequences (not contiguous). Related to edit distance and many string matching problems.

Example:

  • Input: s1 = “abcde”, s2 = “ace”
  • Output: 3 (LCS = “ace”)

Time Complexity: O(m × n)
Space Complexity: O(m × n)

Problem Description: Find the minimum number of operations (insert, delete, replace) to transform one string into another. Use DP where dp[i][j] = edit distance between s1[0…i-1] and s2[0…j-1]. If characters match, dp[i][j] = dp[i-1][j-1], otherwise take minimum of three operations plus one. This is a classic problem in string algorithms and computational biology. The problem tests DP formulation with three choices at each step.

Example:

  • Input: s1 = “horse”, s2 = “ros”
  • Output: 3 (delete h, delete e, replace o with r)

Time Complexity: O(m × n)
Space Complexity: O(m × n)

Problem Description: Given an array of heights, find two lines that form a container with the maximum area. The area is calculated as width × min(height[left], height[right]). Naive O(n²) approach checks all pairs. Optimal two-pointer approach starts with maximum width and moves pointers inward: if left height is smaller, increment left (can’t decrease height by moving right), otherwise decrement right. This teaches two-pointer optimization and greedy reasoning about how to explore the solution space. The key insight is that we should never move the taller line inward as it can only decrease area. Time complexity is O(n).

Example:

  • Input: height =​
  • Output: 49 (between index 1 and 8, area = 7 × min(8,7) = 49)

Time Complexity: O(n)
Space Complexity: O(1)

Problem Description: Find all unique triplets in an array that sum to zero. Naive O(n³) checks all triplets. Optimize by sorting first O(n log n), then for each element, use two-pointer approach on the remaining array. Key to avoiding duplicates is skipping duplicate values and using set or careful iteration. This teaches combining sorting with two-pointers and duplicate handling. The problem tests understanding of nested two-pointer logic and when to skip elements. Similar pattern applies to 3Sum Closest and other k-sum variants.

Example:

  • Input: nums = [-1,0,1,2,-1,-4]
  • Output: [[-1,-1,2],[-1,0,1]]

Time Complexity: O(n²)
Space Complexity: O(1) if not counting output

Problem Description: Rotate an n×n matrix 90 degrees clockwise in-place. Two approaches: transpose the matrix then reverse each row (O(1) space), or use layer-by-layer rotation. The matrix is divided into concentric layers from outside to inside. For each layer, rotate groups of four elements simultaneously. This problem teaches matrix manipulation, understanding of in-place modifications, and geometric transformations. The layer-by-layer approach is intuitive once you visualize it. Problem tests understanding of coordinate transformations and in-place algorithms.

Example:

  • Input: matrix = [,,]​
  • Output: [,,]​

Time Complexity: O(n²) for the matrix
Space Complexity: O(1)

Problem Description: Group strings that are anagrams of each other. Approach: for each string, sort its characters to get a canonical form, use as hash map key. All anagrams have the same sorted form. Group strings by this key. Time complexity is O(n × k log k) where n is number of strings and k is maximum string length (for sorting). Alternative approach counts character frequencies instead of sorting, but time is similar. This problem teaches using hash maps for grouping and finding canonical representations.

Example:

  • Input: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]
  • Output: [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]

Time Complexity: O(n × k log k)
Space Complexity: O(n × k)

Problem Description: Given an m×n matrix, return elements in spiral order (clockwise from outside to inside). Track boundaries for each direction – go right along top row, down along right column, left along bottom row, up along left column, then shrink boundaries. This problem teaches following algorithm step-by-step with boundary management. Each iteration processes one complete spiral layer. Tests understanding of 2D array traversal and boundary tracking.

Example:

  • Input: matrix = [,,]​
  • Output:​

Time Complexity: O(m × n)
Space Complexity: O(1)

Problem Description: Find all elements appearing more than n/3 times. At most 2 elements can appear more than n/3 times. Use generalization of Boyer-Moore voting where track up to 2 candidates and their counts. When count reaches zero, replace candidate. This teaches advanced voting algorithm and understanding why there can be at most 2 such elements. The problem demonstrates algorithm design for specific constraints.

Example:

  • Input: nums =
  • Output:
  • Input: nums =​
  • Output:​

Time Complexity: O(n)
Space Complexity: O(1)

Problem Description: Given an array nums, return result where result[i] = product of all array elements except nums[i]. Constraint: don’t use division. Approach: create left products array where left[i] = product of all elements to the left of i. Create right products similarly. Then result[i] = left[i] × right[i]. Can optimize to single pass by computing right products on-the-fly. This problem teaches prefix/suffix product technique and avoiding forbidden operations.

Example:

  • Input: nums =​
  • Output:

Time Complexity: O(n)
Space Complexity: O(n)

Problem Description: Modify array in-place to the next lexicographically greater permutation. Algorithm: find rightmost position i where nums[i] < nums[i+1], then find rightmost position j where nums[j] > nums[i], swap them, and reverse everything after position i. This teaches pattern recognition in sequences and in-place modifications. The problem requires understanding permutation ordering and recognizing the pattern to achieve next permutation efficiently without generating all permutations.

Example:

  • Input: nums =​
  • Output:​
  • Input: nums =​
  • Output:​

Time Complexity: O(n)
Space Complexity: O(1)

Problem Description: Given array of 0s, 1s, and 2s (representing colors red, white, blue), sort in-place. Dutch National Flag algorithm: maintain three pointers – one for 0s (left), one for 2s (right), and one for current. Iterate current pointer: if 0, swap with left and increment both; if 2, swap with right and decrement right; if 1, just increment current. Single pass O(n) solution with O(1) space. This problem teaches partitioning algorithm and in-place sorting for limited alphabet.

Example:

  • Input: nums =​
  • Output:​

Time Complexity: O(n)
Space Complexity: O(1)

Problem Description: Find the kth largest element in an unsorted array. Min-heap approach: maintain heap of size k with smallest elements. The root is the kth largest. Quickselect approach: randomized partition like quicksort but only recurse on relevant partition. Expected O(n) time. This problem teaches two important techniques: heap-based streaming and quickselect for linear expected time. Contrast with full sorting which takes O(n log n).

Example:

  • Input: nums =, k = 2​
  • Output: 5

Time Complexity: O(n log k) for heap, O(n) expected for quickselect
Space Complexity: O(k)

Problem Description: Given a binary tree, return level-order traversal (level by level, left to right). Use queue: enqueue root, then for each level, process all nodes at that level by dequeueing and enqueueing their children. Key is processing nodes level-by-level not just in order. This problem teaches BFS on trees and queue-based traversal. Important distinction from DFS inorder/preorder/postorder traversal.

Example:

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

Time Complexity: O(n)
Space Complexity: O(w) where w is maximum width

Problem Description: Determine if a binary tree is a valid BST. Each node must be greater than all nodes in left subtree and less than all nodes in right subtree. Approach: in-order traversal of BST yields sorted sequence. Alternatively, pass min/max constraints to each node. DFS validates constraints at each node. This problem teaches BST properties and how to validate them using constraints or inorder traversal property.

Example:

  • Input: tree =​
  • Output: true
  • Input: tree = [5,1,4,null,null,3,6]
  • Output: false (node 4 shouldn’t be in left subtree of 5)

Time Complexity: O(n)
Space Complexity: O(h) for recursion stack

Problem Description: Find the maximum path sum in a binary tree where path can start and end at any nodes. Path must be connected but doesn’t have to go through root. Use DFS returning the maximum sum from current node going down. At each node, consider: max path through this node = node.value + max_left_sum + max_right_sum. This problem teaches complex DFS where you track both answer and maximum contribution downward. The key challenge is distinguishing between the path that passes through a node vs. the path going down from a node.

Example:

  • Input: tree = [-10,9,20,null,null,15,7]
  • Output: 42 (path 15→20→7)

Time Complexity: O(n)
Space Complexity: O(h)

Problem Description: Find the LCA (lowest common ancestor) of two nodes in a binary tree. For BST, compare values with node and recurse left or right. For general binary tree, if both p and q are found in left subtree, LCA is in left; if both in right subtree, LCA is in right; if in different subtrees or current is one of them, current is LCA. This problem teaches tree traversal for searching and understanding LCA definition. Important to understand difference between BST (value-based) and general tree (structure-based) approaches.

Example:

  • Input: tree = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
  • Output: 3 (3 is LCA of 5 and 1)

Time Complexity: O(n) for general tree, O(h) for balanced BST
Space Complexity: O(h)

Problem Description: You can rob houses earning their money but can’t rob adjacent houses. Find maximum money robbed. Use DP where dp[i] = max money robbed up to house i. Either rob house i and add to dp[i-2], or don’t rob and take dp[i-1]. Recurrence: dp[i] = max(nums[i] + dp[i-2], dp[i-1]). Space optimized to O(1) using two variables. This problem teaches simple DP optimization from naive recursion.

Example:

  • Input: nums =​
  • Output: 4 (rob house 0 and 2: 1+3)
  • Input: nums =
  • Output: 9 (rob house 1 and 3: 7+3… no, better is just 9 from house 2)

Time Complexity: O(n)
Space Complexity: O(1)

Problem Description: Given an array, determine if it can be partitioned into two subsets with equal sum. Transform to: find if there’s a subset with sum = total_sum/2. Use 0/1 knapsack DP where dp[i] = true if sum i is achievable. This problem teaches recognizing classic DP problems and transforming problems into standard forms. It’s a variant of the 0/1 knapsack problem with slight modification.

Example:

  • Input: nums =​
  • Output: true (subsets and )​
  • Input: nums =​
  • Output: false

Time Complexity: O(n × sum)
Space Complexity: O(sum)

Problem Description: Create a deep copy of an undirected graph. Use DFS/BFS with hash map tracking visited nodes and their clones. For each node, create a clone, mark as visited, and recursively clone neighbors. This problem teaches graph traversal, cloning with reference handling, and avoiding infinite loops in cyclic graphs. The hash map is crucial for both avoiding revisiting nodes and mapping original to cloned nodes.

Example:

  • Input: adjList = [,,,]​
  • Output: A deep copy of the graph with same structure but new node instances

Time Complexity: O(N + E) where N is nodes, E is edges
Space Complexity: O(N)

Problem Description: Given a sorted list of words in an alien dictionary, derive the order of characters. Build a directed graph where an edge from ‘a’ to ‘b’ means ‘a’ comes before ‘b’ in the alien dictionary. Extract edges by comparing adjacent words character-by-character. Use topological sort (DFS or Kahn’s algorithm) to get character ordering. This problem teaches graph construction from domain knowledge and topological sorting. The key challenge is correctly extracting edges from sorted word list.

Example:

  • Input: words = [“wrt”,”wrf”,”er”,”ett”,”rftt”]
  • Output: “wertf”

Time Complexity: O(N × L + E)
Space Complexity: O(1) for alphabet size

Q1: Uber/Ola Ride Sharing System

Design a ride-sharing application where riders request rides, drivers accept them, and the system matches them efficiently. The system must handle user registration for both riders and drivers with different profile information. Implement real-time location tracking to find nearest available drivers within a specified radius. Build a matching algorithm that considers driver rating, distance, availability, and vehicle type. Include fare calculation based on distance, time, surge pricing, and vehicle type. Implement a rating system allowing both riders and drivers to rate each other after completing rides. Handle payment processing through multiple payment methods and maintain transaction history. Create a booking system that manages ride lifecycle from request creation to completion. Handle cancellations with appropriate penalties and refunds. Build notification systems for ride status updates, driver location sharing, and estimated arrival times. Consider concurrency issues when multiple riders request simultaneously and implement proper locking mechanisms.

Design a parking lot system managing multiple levels with different parking spot types (compact, large, handicapped). Each level contains numerous spots that can accommodate vehicles of different sizes. Implement real-time spot availability tracking showing customers current available spots by type. Create entry and exit gate mechanisms that issue tickets upon entry and process payment upon exit. Build an automatic pricing system calculating fees based on parking duration with potential discounts for monthly passes. Implement a spot finding algorithm that suggests the nearest available spot matching vehicle size and customer preferences. Handle edge cases like vehicle overstaying leading to fines and reserved spots for handicapped vehicles. Create a display system showing available spots at each level that updates in real-time. Implement payment methods supporting cash, cards, and digital wallets. Build a compact spot allocation strategy that optimizes space usage. Include support for different vehicle types and track their entry/exit history for analytics and security purposes.

Design a comprehensive library system managing books, members, and borrowing operations. The system tracks physical book inventory with multiple copies of each book, maintaining copy-specific details like barcode and location. Create member registration with different membership tiers offering various borrowing privileges like maximum books and borrowing duration. Implement borrowing functionality with automated due date calculation and fine assessment for overdue returns. Build a reservation system allowing members to reserve unavailable books with automatic notifications when books become available. Create search functionality allowing members to find books by title, author, ISBN, or category across the database. Implement a fine calculation system with configurable rates and mechanisms to waive fines in special circumstances. Build notification systems for overdue reminders, available book notifications, and membership expiry alerts. Track borrowing history for analytics and personalized recommendations. Implement damaged book reporting and replacement mechanisms. Create reports showing popular books, member borrowing patterns, and inventory status for library administration.

Design an ATM system enabling users to perform banking operations securely. Implement user authentication through card insertion and PIN verification with attempts limit and card blocking after maximum failed attempts. Build account management functionality allowing users to check balance, view recent transactions, and update PIN. Implement cash withdrawal with denomination selection, daily limit enforcement, and physical cash dispensing simulation. Build deposit functionality allowing users to deposit checks and cash with verification. Create fund transfer capabilities between accounts with beneficiary management. Implement real-time balance updates after transactions and comprehensive transaction receipts. Handle edge cases like insufficient balance, daily limit exceed, and invalid card scenarios gracefully. Build a session management system ensuring automatic logout after inactivity timeout. Implement error handling for network failures, printer jams, and cash dispenser issues. Create audit logs tracking all transactions for fraud detection and compliance. Support multiple account types with different withdrawal limits and features for each type.

Design a coffee shop ordering system managing menu items, customizations, and order processing. Build a menu system categorizing items (beverages, food, desserts) with detailed descriptions, prices, and ingredient information highlighting allergens. Implement customization options allowing customers to modify items (size selection, extra shots, milk type) with additional pricing. Create a shopping cart system where customers can add items, apply modifications, and review orders before checkout. Implement payment processing supporting multiple payment methods with transaction confirmation and receipt generation. Build an order tracking system displaying order status from received to preparing to ready for collection. Create a preparation queue system optimizing kitchen workflow with estimated wait time calculations. Implement notification systems alerting customers when orders are ready for pickup. Build inventory management tracking ingredient stock levels and alerting when items run low. Create a loyalty program system offering discounts to repeat customers. Implement special offer management allowing seasonal promotions and bundle deals with automatic discount application.

 

Design an e-commerce shopping cart and checkout system enabling customers to browse products and make purchases. Build product catalog displaying items with descriptions, images, prices, ratings, and availability status. Implement shopping cart functionality allowing customers to add items, update quantities, remove items, and persist cart across sessions. Create a wishlist feature allowing customers to save items for future purchase consideration. Build a coupon and discount system supporting percentage-based and fixed-amount discounts with minimum purchase requirements and expiration validation. Implement inventory management checking stock availability during checkout and reserving inventory upon order placement. Create an address management system allowing customers to save multiple addresses for shipping and billing. Build a shipping method selection system displaying different options with costs and estimated delivery times. Implement tax calculation based on shipping address and product categories. Create an order summary display showing item breakdown, applied discounts, taxes, shipping cost, and final total. Build payment gateway integration supporting credit cards, digital wallets, and other payment methods with PCI compliance.

Design a chat application supporting one-on-one and group messaging with real-time delivery. Implement user authentication and profile management with status indicators (online, offline, away). Build a one-on-one conversation system maintaining message history and conversation metadata like creation date and last message time. Create a group chat functionality supporting multiple participants with features like admin controls and participant management. Implement message functionality supporting text with rich formatting, media attachments, and emoji reactions. Build message delivery status tracking (sent, delivered, read) with read receipts for transparency. Create typing indicators showing when other users are composing messages for better UX. Implement message search functionality allowing users to find messages by content, sender, or timestamp. Build notification systems alerting users about new messages when offline with message preview. Create message archival functionality allowing users to search old messages without deleting them. Implement block/mute functionality giving users control over unwanted communications and notifications.

Design a hotel booking system allowing customers to search, view, and reserve rooms. Implement room inventory management tracking room count by type, availability dates, and pricing. Build search functionality allowing customers to filter by check-in/checkout dates, room type, price range, and amenities. Create a room booking system with calendar view showing availability and detailed room information including photos and amenities. Implement pricing rules supporting seasonal pricing, dynamic pricing, and bulk booking discounts. Build a reservation confirmation system generating confirmation numbers and sending booking details to customers. Implement cancellation policies with automatic refund calculation based on cancellation timing. Create a payment system supporting multiple payment methods with installment options for group bookings. Build a guest check-in/check-out system recording actual stay dates and handling late checkouts. Implement housekeeping integration assigning rooms to staff and tracking cleaning status. Create a rating and review system allowing guests to provide feedback on rooms, service, and amenities.

Design a movie theater booking system enabling customers to select movies, showtimes, and seats for reservation. Implement a movie catalog displaying current and upcoming movies with descriptions, ratings, duration, and language options. Build a showtime management system with multiple shows per day, different theater screens, and seat capacity tracking. Create a seat selection interface displaying available and occupied seats with different pricing for premium and standard seats. Implement a booking system with cart functionality allowing customers to select multiple tickets before checkout. Build a pricing system with dynamic pricing based on showtime (peak/off-peak) and seat location (premium/standard). Implement a reservation confirmation system generating e-tickets with QR codes and sending booking details via email. Create a cancellation system with automatic refund processing and seat release back to available pool. Build a blocking mechanism preventing double-booking of same seats during concurrent bookings. Implement group booking discounts and special pricing for students, seniors, and matinee shows.

Design a vending machine system managing inventory, payments, and item dispensing. Implement product inventory tracking with quantity available, pricing, and location within machine (slot/row/column). Build a payment system accepting cash and card payments with change calculation and display of transaction status. Create an item selection mechanism allowing customers to select products by entering slot numbers or scanning items. Implement a transaction system recording all purchases, payment methods, and inventory changes. Build a low-inventory alert system notifying maintenance personnel when items need restocking. Create an error handling system for jammed items, payment processing failures, and insufficient change scenarios. Implement a receipt generation system printing transaction details on demand. Build a maintenance mode allowing staff to restock, collect revenue, and perform system diagnostics. Create a cash management system tracking revenue collected and float requirements. Implement analytics tracking popular items, sales by category, and machine utilization rates.

Design a food delivery platform connecting restaurants, delivery partners, and customers. Implement a restaurant management system displaying menus, availability, operating hours, and ratings. Build a restaurant search and filtering system allowing customers to find restaurants by cuisine, price range, delivery time, and ratings. Create an order system enabling customers to browse menus, customize items, and select delivery addresses. Implement a cart system with order summary showing item breakdown, taxes, delivery charges, and discounts. Build a payment system with multiple payment methods and online payment processing. Create an order tracking system showing order status from confirmation to delivery with real-time delivery partner location. Implement a delivery partner assignment algorithm matching orders to nearby available delivery partners considering distance, ratings, and current load. Build a rating and review system for restaurants and delivery partners. Implement a support system handling cancellations, refunds, and customer complaints. Create an analytics system tracking order patterns, popular items, and delivery performance metrics.

Design a social media platform where users create accounts, post tweets, follow others, and interact with content. Build user profile management with profile pictures, bios, follower/following lists, and verification badges. Implement a tweet creation system allowing users to post text with media attachments (images, videos). Build a feed system displaying tweets from followed users in chronological order with caching for performance. Create an engagement system with likes, retweets, and replies showing interaction counts and preventing duplicate interactions. Implement a hashtag system tracking trending topics and allowing users to search by hashtags. Build a notification system alerting users about likes, replies, follows, and mentions with notification management. Create a search system enabling users to find tweets, accounts, and hashtags. Implement a block and mute functionality giving users control over their experience. Build privacy controls allowing users to make accounts private and manage followers. Create a moderation system for reporting and removing inappropriate content.

Design an email system allowing users to compose, send, receive, and organize emails. Implement user authentication and mailbox management with inbox, sent, draft, and trash folders. Build email composition functionality supporting text/HTML content, attachments, and recipient lists with cc and bcc. Create a sending mechanism with validation, queuing for retry on failure, and delivery confirmation. Implement email receiving with parsing, storage, and real-time notification delivery. Build a folder management system allowing users to create custom folders and organize emails through moves and labels. Create a search functionality enabling full-text search, filtering by sender/date/subject, and saved searches. Implement attachment handling with virus scanning, size limits, and preview generation. Build a spam filtering system with machine learning for automatic spam detection and user-reported spam. Create an archival system allowing users to backup old emails and restore when needed. Implement POP3/IMAP protocols for third-party email client access. Build an unsubscribe mechanism for marketing emails and compliance with email regulations.

Design a calendar application allowing users to manage events, meetings, and reminders. Implement event creation with date, time, location, description, and attendee management. Build recurring event support (daily, weekly, monthly, yearly) with exception handling for specific instances. Create a calendar view with multiple perspectives (day, week, month, year) and navigation between periods. Implement event search and filtering by title, date range, attendees, and event type. Build a meeting invitation system sending invites to attendees with RSVP functionality (accept, decline, tentative). Create a notification system with customizable reminders (at event time, 15 minutes before, one day before). Implement calendar sharing allowing users to share calendars with specific people or make public. Build a conflict detection system preventing double-booking and alerting users. Create a calendar synchronization system syncing events across devices and third-party calendar services. Implement an analytics system tracking time utilization and meeting patterns.

Design a file storage and sharing platform allowing users to upload, organize, and share files. Implement user authentication with storage quota management and quota upgrade options. Build file upload functionality with chunked upload for large files, progress tracking, and resume capability. Create a file organization system with folder hierarchies, custom folder creation, and file naming. Implement file versioning allowing users to view and restore previous versions of files. Build a sharing system with link-based sharing, access control (view/edit/admin), expiry dates, and password protection. Create collaboration features allowing multiple users to edit shared documents simultaneously with conflict resolution. Implement a commenting system on files for feedback and discussion. Build a search functionality with full-text search for document content and metadata filtering. Create a trash/recycle bin allowing file recovery within retention period. Implement access logging tracking who accessed/modified files and when. Build a sync functionality keeping local and cloud copies synchronized automatically.

Design a ticket booking system for concerts, flights, or events with inventory and availability management. Implement a venue/flight inventory system tracking available seats/capacity with real-time updates. Build a search and filter system allowing customers to find events by date, location, price, and category. Create a seat/slot selection interface with layout visualization and dynamic pricing for premium locations. Implement a booking cart allowing multiple tickets with applied discounts and group bookings. Build a payment system with multiple payment method support and transaction security. Create a booking confirmation with ticket generation (digital/physical barcode) and delivery options. Implement a cancellation system with refund processing following cancellation policies. Build a waiting list for sold-out events with automatic notification when tickets become available. Create a dynamic pricing algorithm adjusting prices based on demand, availability, and time to event. Implement fraud detection for suspicious booking patterns and verification mechanisms.

Design a logging framework for applications to record, format, and store log messages at various severity levels. Implement log level filtering (DEBUG, INFO, WARN, ERROR, CRITICAL) with configurable minimum levels. Build log message formatting with timestamp, source location, thread information, and custom patterns. Create multiple output handlers (console, file, database, remote server) allowing simultaneous output to different destinations. Implement log file rotation based on size or time preventing disk space exhaustion. Build a filtering system allowing selective logging of specific components or classes. Create an async logging mechanism preventing blocking application threads during logging. Implement structured logging supporting key-value pairs for better analysis. Build a log aggregation system collecting logs from multiple application instances. Create a visualization dashboard for log analysis, searching, and alerting on error patterns. Implement performance metrics tracking logging overhead and optimization techniques.

Design an in-memory caching system improving application performance by storing frequently accessed data. Implement key-value storage with O(1) average lookup time using hash tables. Build eviction policies (LRU, LFU) removing least useful entries when capacity limits are reached. Create TTL (time-to-live) functionality automatically expiring entries after specified durations. Implement cache invalidation mechanisms through explicit removal or pattern matching. Build a multi-tier caching with local and distributed cache support for scalability. Create cache statistics tracking hit rate, miss rate, and eviction patterns for optimization. Implement atomic operations (increment, append) on cached values without full replacement. Build a warm-up mechanism pre-loading frequently used data into cache on startup. Create a consistency mechanism between cache and persistent storage ensuring data accuracy. Implement distributed caching supporting multiple cache nodes with replication and partitioning strategies.

Build detailed error responses indicating rate limit exceeded with retry-after headers. Create monitoring dashboards displaying current rates, rejections, and throttling events. Implement fallback mechanisms for distributed rate limiter failures ensuring service availability. Create configuration management allowing dynamic adjustment of rate limits without service restart. Build logging and alerting for suspicious patterns like sudden traffic spikes or individual users exceeding limits.

Design a URL shortening service converting long URLs into short, shareable links. Implement a unique short code generation using Base62 encoding ensuring no collisions across millions of URLs. Build a database storing mappings between short codes and original URLs with metadata. Create a redirection mechanism efficiently retrieving original URL from short code and performing redirect. Implement analytics tracking click count, geographical distribution, and referrer information for each shortened URL. Build an expiration mechanism allowing optional TTL for temporary shortened URLs. Create a custom alias feature allowing users to specify custom short codes (if available). Implement a collision handling mechanism ensuring uniqueness even with custom codes. Build a QR code generation feature creating scannable codes for shortened URLs. Create a user dashboard allowing users to manage their shortened URLs and view analytics. Implement rate limiting preventing API abuse and quota management for different user tiers.

Design an autocomplete system providing relevant suggestions as users type search queries. Implement a trie data structure efficiently storing dictionary words with autocomplete capability. Build a ranking algorithm suggesting most relevant queries based on frequency and recency. Create a caching mechanism storing top suggestions for common prefixes to reduce latency. Implement a spell correction feature suggesting corrected queries for misspellings. Build a relevance scoring considering user location, trending queries, and historical user searches. Create a filter mechanism removing inappropriate or adult suggestions from recommendations. Implement geographic customization showing location-specific suggestions and results. Build analytics tracking popular searches, top suggestions selected, and user patterns. Create a data update mechanism continuously refreshing trie with new popular queries. Implement prefix mat

Design a notification system delivering messages to users through multiple channels. Implement channel-specific notification handlers for email, SMS, push notifications, and in-app messages. Build a notification queuing system managing high-volume notifications with processing guarantees. Create a user preference system allowing users to control notification frequency and channels. Implement template management for notification content with variable substitution. Build a scheduling system sending notifications at optimal times respecting user timezones. Create a delivery tracking mechanism ensuring notification delivery with retry logic for failures. Implement a deduplication system preventing duplicate notifications in short time windows. Build a priority queue ensuring critical notifications are delivered before less important ones. Create analytics tracking delivery rates, open rates, and user engagement metrics. Implement a do-not-disturb mechanism respecting user preferences about notification timing.

Design a user management system handling registration, authentication, and profile management. Implement user registration with email verification and password strength validation. Build authentication supporting multiple methods (username/password, OAuth, social login). Create a session management system tracking active sessions with timeout and invalidation. Implement password reset functionality with secure token-based reset links. Build a profile management system allowing users to update personal information and preferences. Create a role-based access control system defining permissions for different user types. Implement two-factor authentication for enhanced security. Build account deactivation and deletion functionality with data retention policies. Create an audit log tracking user actions for security and compliance. Implement API key management for programmatic access with rotation capabilities.

Design a recommendation system suggesting relevant content to users based on their behavior. Implement collaborative filtering finding similar users and recommending items they liked. Build content-based filtering recommending items similar to previously liked items. Create a hybrid approach combining collaborative and content-based filtering for better accuracy. Implement machine learning models training on user-item interaction data. Build a caching mechanism storing pre-computed recommendations for faster serving. Create a feedback loop continuously improving recommendations based on user engagement. Implement A/B testing framework comparing recommendation algorithms’ effectiveness. Build real-time recommendation capability adapting to recent user behavior immediately. Create diversity mechanisms ensuring recommendations include variety not just most relevant. Implement serendipity factors introducing unexpected recommendations to expand user horizons.

Design a job queue system processing asynchronous tasks in background workers. Implement a queue data structure storing pending jobs with FIFO or priority ordering. Build a worker pool managing multiple worker processes pulling jobs from queue. Create a job status tracking mechanism allowing users to monitor job progress. Implement a retry mechanism handling job failures with exponential backoff. Build a persistence mechanism ensuring jobs survive system restarts. Create scheduled job support running jobs at specific times or intervals. Implement a dead-letter queue storing permanently failed jobs for analysis. Build a worker health monitoring system detecting and replacing failed workers. Create metrics tracking job throughput, latency, and failure rates. Implement priority queuing ensuring critical jobs are processed before others.

Design a pub-sub system enabling decoupled communication between components. Implement topic-based routing allowing publishers to send to topics and subscribers to listen. Build subscription management with subscribe/unsubscribe functionality. Create message persistence storing messages for late subscribers or replay scenarios. Implement filtering allowing subscribers to receive only relevant messages. Build guaranteed delivery mechanisms ensuring messages reach subscribers. Create acknowledgment handling with automatic redelivery for failed deliveries. Implement message ordering guarantees for messages on same partition/topic. Build scalability through partitioning and multiple brokers. Create consumer group support allowing multiple subscribers to share load. Implement monitoring and metrics tracking message throughput and lag.

Design a distributed lock system preventing concurrent access to shared resources. Implement a leader election mechanism determining which process acquires lock. Build a timeout mechanism preventing permanent locks from crashed processes. Create a fair queuing ensuring FIFO lock acquisition preventing starvation. Implement read-write locks allowing multiple readers or single writer. Build deadlock detection preventing circular lock dependencies. Create a lock status monitoring system tracking lock holders and wait queues. Implement automatic lock release on process death. Build a performance optimization through lock striping reducing contention. Create a debugging mechanism allowing inspection of lock state and holders. Implement lock metrics tracking acquisition time and contention levels.

Design a distributed caching system scaling across multiple nodes. Implement consistent hashing determining which node stores which key. Build replication ensuring cache availability despite node failures. Create invalidation mechanisms synchronizing changes across cache replicas. Implement TTL functionality with distributed expiration. Build a warm-up mechanism pre-loading cache from persistent storage. Create hit rate monitoring identifying optimization opportunities. Implement cache coherency protocols ensuring data consistency. Build a migration mechanism seamlessly adding/removing cache nodes. Create a write-through and write-back policies supporting different consistency requirements. Implement a capacity management distributing storage across nodes optimally.

Design a system coordinating transactions across multiple databases. Implement two-phase commit ensuring atomicity across databases. Build a transaction log tracking operations for recovery. Create a deadlock detection and resolution mechanism. Implement isolation levels preventing dirty reads and phantom reads. Build a timeout mechanism handling slow transactions. Create a rollback mechanism reverting failed transactions. Implement distributed snapshot isolation for better concurrency. Build a conflict detection mechanism handling concurrent modifications. Create failure recovery mechanisms. Implement a transaction monitoring system tracking progress and identifying bottlenecks.

Design an event sourcing system storing state changes as immutable events. Implement event store persisting all events in append-only manner. Build event replay mechanism reconstructing current state from events. Create snapshots reducing replay time for frequently accessed aggregates. Implement temporal queries retrieving state at any historical point. Build CQRS separating reads and writes for scalability. Create multiple read models optimized for different query patterns. Implement eventual consistency handling asynchronous view updates. Build event versioning handling schema changes over time. Create an audit trail through immutable event history. Implement event projections deriving new events from existing ones.

Q1: Design Instagram/Pinterest (Large Scale Photo Sharing)

Design a large-scale photo sharing platform handling billions of photos with real-time feed generation. The system architecture must support millions of concurrent users uploading and viewing photos simultaneously. Implement a distributed storage system using cloud providers like S3 for photo storage with CDN distribution for fast retrieval globally. Design a feed generation system using message queues to process new posts from followed users and update user feeds asynchronously. Implement a caching layer using Redis for frequently accessed data like user profiles, feeds, and like counts. Create a database sharding strategy partitioning users across multiple database instances to handle scale. Build an image processing pipeline resizing photos for different devices using queue workers. Implement a real-time notification system alerting users about likes, comments, and follows. Design a search system for discovering photos by hashtags, location, or users using Elasticsearch. Create a recommendation engine suggesting relevant photos and users based on user behavior and interests. Implement a consistent hashing system for distributing cache and database load across nodes. Consider GDPR compliance, data privacy, and secure user authentication.

Design a video streaming platform supporting billions of video uploads and trillions of views. The system must handle video uploads, processing, transcoding into multiple formats/resolutions, and streaming to users worldwide. Implement a distributed video storage system using object storage with geographic replication for availability. Design a video transcoding service using distributed workers processing videos into multiple bitrates (720p, 480p, 360p, etc.) for adaptive streaming. Build a video delivery system using CDN nodes globally ensuring low latency viewing worldwide. Implement a recommendation system suggesting videos based on watch history, preferences, and trending content. Create a real-time analytics system tracking views, watch duration, engagement metrics across videos. Design a search system indexing videos by title, description, tags enabling quick discovery. Build a live streaming capability supporting millions of concurrent viewers. Implement a user interaction system for likes, comments, subscriptions with eventual consistency. Design a monetization system supporting ads insertion and creator revenue sharing. Create a content moderation system detecting and removing policy-violating content.

Design a real-time social network supporting hundreds of millions of users. Implement a tweet creation and distribution system handling millions of tweets per second. Design a feed generation system aggregating tweets from followed users with timeline consistency. Build a real-time notification system alerting users about mentions, likes, retweets instantly. Implement a tweet search system using Elasticsearch supporting full-text search on billions of tweets. Design a trending topics system identifying emerging hashtags and keywords in real-time using stream processing. Create a real-time messaging system supporting direct messages with delivery guarantees. Build a media handling system supporting images, videos, and link previews in tweets. Implement a user follow relationship system managing billions of follow connections efficiently. Design a content delivery system ensuring tweets reach followers with minimal latency. Create a distributed counter system tracking likes and retweets accurately at scale. Build a spam and abuse detection system using machine learning. Design a failover and recovery system ensuring platform availability 24/7.

Design a global ride-sharing platform serving millions of daily rides. Implement a location-based matching system quickly finding nearest drivers for ride requests. Build a real-time tracking system displaying driver location to riders with near-instant updates. Design a pricing algorithm calculating surge pricing dynamically based on supply/demand. Create a distributed routing system optimizing pickup and dropoff locations considering traffic. Implement a payment system processing millions of transactions securely. Design a supply and demand forecasting system predicting driver needs in specific areas. Build a quality assurance system tracking driver and rider ratings ensuring safety. Create a customer support system handling ride issues and disputes. Implement a driver lifecycle management system tracking driver onboarding and performance. Design a geospatial database optimizing location queries and spatial operations. Build a real-time analytics system providing insights on rides, revenue, and user behavior. Create disaster recovery mechanisms ensuring service availability during incidents.

Design a global accommodation platform connecting millions of hosts with travelers. Implement a search and filtering system allowing users to find accommodations by location, dates, amenities, and price. Build a booking system managing reservations, payments, and confirmation. Design an inventory management system for hosts tracking availability and managing listings. Implement a messaging system enabling host-guest communication. Create a review and rating system maintaining trust through feedback. Build a payment system handling multi-currency transactions with host payouts. Design a search backend using Elasticsearch optimizing for location-based queries. Implement a real-time availability system preventing double-booking. Create a recommendation system suggesting accommodations based on user preferences. Build a dynamic pricing system suggesting optimal prices for hosts based on demand. Implement compliance and verification systems ensuring legal requirements. Design a notification system informing users about bookings, reviews, and messages.

Design a video streaming service handling millions of concurrent viewers globally. Implement a content delivery network distributing videos across global edge locations. Build a video encoding service transcoding content into multiple bitrates and formats. Design an adaptive bitrate streaming system adjusting video quality based on network conditions. Create a recommendation system suggesting shows/movies based on watch history. Implement a user watch history system tracking viewing progress enabling resumption. Build a licensing and rights management system tracking content availability by region. Design a subscriber management system handling billions of subscriptions. Create a real-time analytics system tracking viewing patterns and engagement. Implement a search system enabling discovery by title, genre, cast, and keywords. Build a personalization system customizing UI based on user preferences. Design a disaster recovery system ensuring availability during outages. Create a content management system enabling producers to upload and manage content.

Design a social network with billions of users and trillions of connections. Implement a feed generation system aggregating posts from friends, followers, and pages. Build a real-time notification system delivering billions of notifications daily. Create a distributed graph database storing relationship data efficiently. Implement a messaging system supporting one-on-one and group conversations. Design a photo and video sharing system similar to Instagram. Build a privacy system controlling content visibility based on user settings. Implement an advertising system serving targeted ads to billions of users. Create a content moderation system detecting policy violations at scale. Build a real-time analytics system tracking user engagement. Design a distributed cache layer reducing database load. Implement a disaster recovery system maintaining high availability. Create a compliance system meeting GDPR and regional data regulations.

Design a messaging platform serving billions of users with real-time message delivery. Implement end-to-end encryption ensuring message privacy from users to users. Build a message queue system ensuring reliable delivery with offline message storage. Create a presence system showing user online status in real-time. Implement a group messaging system supporting thousands of members efficiently. Build a media sharing system for images, videos, and documents. Design a distributed system scaling to handle peak traffic loads. Create a notification system alerting users about new messages. Implement a backup system enabling user data recovery. Build metrics and monitoring for system health and performance. Design a failover system maintaining availability during failures. Create a compliance system following regional data protection laws. Implement account security features like 2FA and suspicious login detection.

Design an e-commerce platform with billions of products and millions of transactions daily. Implement a product catalog system managing billions of products with search and filtering. Build a shopping cart system persisting user selections across sessions. Create an order processing system handling millions of orders daily. Implement a payment system supporting multiple payment methods securely. Build an inventory management system tracking stock across warehouses. Design a recommendation system suggesting products based on browsing and purchase history. Implement a search system using Elasticsearch for product discovery. Create a review and rating system maintaining seller ratings. Build a logistics system coordinating shipment and delivery. Design a return and refund system handling product returns efficiently. Implement a seller management system enabling third-party sellers. Create a pricing system supporting dynamic pricing and promotions. Build a fraud detection system preventing payment fraud.

Design a professional networking platform with hundreds of millions of users. Implement a profile system showcasing user professional information and achievements. Build a connection system managing professional relationships. Create a feed system displaying professional updates and articles. Implement a job search system with millions of job listings. Build a messaging system enabling professional communication. Design a recommendation system suggesting connections and job opportunities. Implement a skill endorsement system validating professional skills. Create a notification system informing users about connections and opportunities. Build a search system finding professionals by skills and experience. Implement analytics showing professional insights and trends. Design a content publishing system for articles and professional insights. Create a recruitment system matching candi

Design a team communication platform with millions of teams and workspaces. Implement a workspace management system organizing teams and channels. Build a messaging system supporting text, reactions, and threading at scale. Create a notification system delivering real-time updates to team members. Implement a search system enabling users to find messages and files across workspaces. Design an integration platform allowing third-party apps to connect and extend functionality. Build a file sharing system supporting document collaboration. Implement presence system showing user availability status in real-time. Create an audit log system tracking all activities for compliance. Design a permission system controlling access at channel and workspace levels. Build a notification preference system respecting user customization. Implement a disaster recovery system ensuring data durability and availability.

Design a mapping service supporting billions of location queries and real-time navigation. Implement a map tiling system dividing world maps into manageable chunks. Build a geocoding service converting addresses to coordinates and vice versa. Create a routing engine calculating optimal routes considering traffic conditions. Implement a real-time traffic system collecting and analyzing location data from users. Design a search system finding locations by name, category, or proximity. Build a POI (Point of Interest) database storing millions of business locations. Implement a navigation system providing turn-by-turn directions. Create a real-time updates system for traffic, transit, and road closures. Design a reverse geocoding system identifying nearby places from coordinates. Build a spatial indexing system for efficient location queries. Implement caching strategies reducing latency for popular routes.

Design a live streaming platform supporting millions of concurrent viewers. Implement a streaming server accepting video uploads from streamers. Build a content delivery network distributing streams to viewers globally. Design an adaptive bitrate system adjusting stream quality based on viewer connection. Create a chat system enabling real-time interaction between streamers and viewers. Implement a recommendation system suggesting popular streams to viewers. Build a monetization system supporting donations and subscriptions. Design a moderation system managing streamer behavior and content. Implement analytics system tracking viewer engagement and stream metrics. Create a discovery system enabling users to find streams by category and language. Build a recording system saving streams for on-demand replay. Design a redundancy system preventing stream interruptions during failures.

Design a video conferencing platform supporting millions of concurrent meetings. Implement a meeting server coordinating video/audio streams between participants. Build a codec system supporting efficient video compression for bandwidth optimization. Design a network optimization system adapting to varying network conditions. Create a screen sharing feature enabling application or desktop sharing. Implement a recording feature capturing meetings for future reference. Build a virtual background system allowing participants to customize backgrounds. Design a meeting scheduling system integrating with calendars. Implement a chat system alongside video enabling text communication. Create a polling and Q&A system enabling audience engagement. Build a permissions system controlling participant abilities (mute, share). Design a scalability system supporting large meetings with hundreds of participants.

Design a cloud file storage platform enabling users to store and sync files across devices. Implement a chunking system breaking large files into pieces for efficient storage. Build a sync engine detecting changes and propagating updates across devices. Design a versioning system enabling file history and recovery. Implement a sharing system allowing users to share files and folders with others. Create a collaboration system enabling multiple users to work on same files. Build a bandwidth optimization system minimizing data transferred during sync. Implement a conflict resolution system handling concurrent modifications. Design a storage optimization through deduplication and compression. Create a backup system ensuring data durability. Build a recovery system enabling file restoration after accidental deletion. Implement end-to-end encryption for user privacy.

Design a music streaming platform with millions of songs and users. Implement a music library system storing metadata for billions of songs. Build a recommendation system suggesting songs based on listening history. Design a playlist system enabling users to create and share playlists. Implement a search system finding songs, artists, albums quickly. Build a personalized feed system showing recommendations and new releases. Create a caching layer reducing database load for popular content. Design an analytics system tracking listening patterns and trends. Implement a recommendation algorithm using collaborative filtering. Build a podcast integration alongside music content. Create an offline mode enabling downloading songs for offline listening. Design a lyrics and metadata system enriching music experience.

Design a community platform for gamers and communities. Implement a server system organizing users into communities and channels. Build a messaging system supporting text, voice, and video communication. Design a permission system enabling granular access control. Create a role system defining user responsibilities and abilities. Implement a bot integration platform enabling community automation. Build a streaming integration enabling in-app streaming. Design a notification system alerting users about important events. Create a moderation system maintaining community standards. Implement an analytics system tracking community health. Build a customization system enabling community branding. Design a integration platform connecting external services.

Design a short-form video platform with billions of videos and users. Implement a video upload and transcoding system handling massive uploads. Build a recommendation engine suggesting videos using machine learning. Design a feed system showing personalized video recommendations. Create a video editing system enabling in-app content creation. Implement a duet and stitch features enabling content collaboration. Build a trending system identifying emerging creators and sounds. Design a monetization system supporting creator revenue. Implement a moderation system preventing harmful content. Create an analytics system tracking video performance. Build a search system finding videos by sound, creator, hashtag. Design disaster recovery ensuring platform availability.

Design a platform enabling users to create and play games. Implement a game engine supporting user-created experiences. Build a matchmaking system connecting players for multiplayer games. Design a content delivery system distributing game assets efficiently. Create a monetization system supporting in-game purchases and creator revenue. Implement a safety system protecting users, especially children. Build an analytics system tracking game popularity and engagement. Design a scripting system enabling game developers. Create a marketplace system for in-game assets and games. Implement a progression system tracking achievements and levels. Build a social system enabling player interactions. Design scalability supporting millions of concurrent players.

Design a food delivery platform operating across multiple cities. Implement a restaurant integration system managing menus and orders. Build a delivery logistics system optimizing delivery routes. Design a matcher system assigning orders to delivery partners efficiently. Create a real-time tracking system showing customer delivery status. Implement a pricing system with dynamic delivery fees. Build a payment system processing customer and merchant transactions. Design a customer support system handling issues and complaints. Create an analytics system tracking delivery metrics and revenue. Implement a fraud detection system preventing abuse. Build a surge pricing system during peak demand. Design a driver incentive system encouraging quality service.

Design a restaurant ordering platform aggregating restaurants and food options. Implement a restaurant catalog system managing menus and availability. Build a search system enabling users to discover restaurants. Design an ordering system with customization options. Create a delivery coordination system integrating with delivery partners. Implement a payment system with multiple payment methods. Build a review system maintaining restaurant and delivery ratings. Design a promotional system supporting discounts and offers. Create an analytics system tracking order patterns. Implement a restaurant management system for vendor operations. Build a customer loyalty program encouraging repeat orders. Design scalability supporting peak ordering times.

Design the hosting side of accommodation platform for property managers. Implement a property listing system showcasing accommodation details. Build a calendar management system tracking availability and bookings. Design a pricing system supporting dynamic and seasonal pricing. Create a reservation management system handling bookings and cancellations. Implement a payment system handling guest payments and host payouts. Build a guest communication system enabling inquiries and negotiations. Design a review system maintaining host credibility. Create analytics showing booking trends and revenue metrics. Implement a maintenance scheduling system tracking property upkeep. Build an insurance integration system managing liability. Design tax reporting system supporting compliance.

Design a payment processing platform handling billions in transactions. Implement a payment gateway accepting various payment methods. Build a compliance system ensuring PCI-DSS adherence. Design a fraud detection system preventing unauthorized transactions. Create a settlement system distributing funds to merchants. Implement a webhook system notifying merchants of transaction status. Build a retry logic handling transient payment failures. Design a reconciliation system matching transactions and settlements. Create a reporting system providing transaction insights. Implement a dispute and chargeback system. Build a rate limiting system preventing abuse. Design scalability handling payment spikes.

Design a POS system for small and medium businesses. Implement a transaction processing system for in-store purchases. Build an inventory management system tracking product stock. Design a customer relationship system maintaining buyer data. Create a reporting system providing business insights. Implement a security system protecting payment card information. Build an integration system with various hardware devices. Design an offline capability enabling operation without internet. Create a staff management system controlling access and permissions. Implement a refund and return processing system. Build an analytics system tracking sales trends. Design a disaster recovery ensuring data protection.

Design Discord’s infrastructure handling millions of concurrent users and real-time messaging. Implement a distributed message queue system ensuring message delivery. Build a distributed caching layer reducing database load. Design a sharding strategy distributing users across servers. Create a load balancing system distributing traffic across regions. Implement a real-time update system using WebSockets or similar. Build a conflict resolution system for distributed systems. Design a monitoring system tracking system health. Implement an auto-scaling system handling traffic spikes. Build a disaster recovery system ensuring availability. Create metrics and alerting for operational visibility. Design a database optimization supporting real-time queries.

Design a content aggregation platform with millions of subreddits and users. Implement a subreddit management system organizing content hierarchically. Build a content ranking system showing popular posts. Design a feed system personalizing content for users. Create a commenting system supporting nested discussions. Implement a voting system affecting post visibility. Build a moderation system enabling community self-governance. Design a search system finding content across platform. Create a user reputation system through karma points. Implement an analytics system tracking engagement. Build a content recommendation system. Design scalability supporting traffic spikes during events.

Design a project management tool enabling team collaboration. Implement a board system organizing work into cards. Build a card management system with descriptions, comments, attachments. Design a workflow system tracking card progression. Create a timeline system visualizing project schedules. Implement a sharing system enabling team collaboration. Build a notification system alerting about changes. Design an automation system reducing manual work. Create an integration system with other tools. Implement a history system tracking changes. Build an analytics system providing project insights. Design scalability supporting large teams and projects.

Design a visual discovery platform with billions of images. Implement a pin system storing and organizing images. Build a recommendation engine suggesting relevant pins. Design a board system enabling users to organize pins. Create a search system finding pins by content and metadata. Implement a user follow system building social graph. Build a feed system showing personalized recommendations. Design a shopping integration connecting to retailers. Create an analytics system tracking pin popularity. Implement a content moderation system. Build an image processing system optimizing images. Design disaster recovery ensuring content durability.

Design a real-time collaborative design platform. Implement a canvas system enabling design creation. Build a real-time collaboration enabling simultaneous editing. Design a version control system tracking design changes. Create a component system reusing design elements. Implement a plugin system extending functionality. Build a sharing system enabling feedback collection. Design a performance optimization for real-time sync. Create an asset management system. Implement a collaboration system with live cursors. Build an export system for various formats. Design scalability for complex designs.

Design a container orchestration platform automating deployment and scaling. Implement a cluster management system organizing compute resources. Build a container scheduling system placing workloads optimally. Design a service discovery system enabling communication. Create a load balancing system distributing traffic. Implement a scaling system auto-adjusting resource allocation. Build a health check system removing failed containers. Design a storage orchestration system managing persistent data. Create a networking system connecting containers. Implement a monitoring and logging system. Build a security system isolating workloads. Design a cluster upgrade system with zero downtime.

WhatsApp Icon

Hi Instagram Fam!
Get a FREE Cheat Sheet on System Design.

Hi LinkedIn Fam!
Get a FREE Cheat Sheet on System Design

Loved Our YouTube Videos? Get a FREE Cheat Sheet on System Design.