20 real Flipkart interview questions with full model answers — Coding, System design. Drawn from the same verified bank ChannelPulse drills from (101 Flipkart questions in total).
101 Flipkart questions in the bank
2 categories covered
2 roles: Frontend Engineer, Software Engineer
CodingEasyFlipkartSoftware Engineer
1. Next Greater Element I (LeetCode)
Model answer
The task
For each value in one array, find the first larger value appearing to its right in a second array that contains it. Return -1 when no such value exists.
Key idea
Scan the second array from left to right with a decreasing stack. When a new value is larger than values on the stack, it is the next greater value for each of them; store those answers in a hash map.
Approach
Initialize an empty stack and a map of answers.
For each value in the second array, pop smaller values from the stack and map each popped value to the current value.
Push the current value onto the stack.
Values still on the stack have no greater value to their right.
Build the result by looking up each value from the first array, using -1 when it has no mapped answer.
from typing import List
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
next_greater = {}
decreasing_stack = []
for value in nums2:
# The current value is the first greater value for each
# smaller value waiting on the stack.
while decreasing_stack and decreasing_stack[-1] < value:
next_greater[decreasing_stack.pop()] = value
decreasing_stack.append(value)
# Any value without a recorded answer has no greater value to its right.
return [next_greater.get(value, -1) for value in nums1]
Complexity:
Time: O(n + m), where n and m are the lengths of the two arrays; each value is pushed and popped at most once.
Space: O(m), for the stack and answer map.
Common follow-ups
What if the second array is circular? Scan it twice, using indices modulo its length, and push only during the first pass.
What if values can repeat? Track indices on the stack and define how to match repeated values from the first array.
Can the answers be found online as values arrive? Yes; resolve stack entries when a larger value arrives, while retaining unresolved entries.
CodingEasyFlipkartSoftware Engineer
2. Diameter of Binary Tree (LeetCode)
Model answer
The task
Find the diameter of a binary tree: the largest number of edges on a path between any two nodes. The path does not have to pass through the root.
Key idea
At each node, the longest path that passes through it has length left_height + right_height. A postorder depth-first search computes child heights and updates the best diameter along the way.
Approach
Keep a variable for the largest diameter seen so far.
Recursively compute the height of each subtree, using zero for an empty subtree.
At each node, combine its left and right heights to get the path length through it.
Update the best diameter, then return the node’s height to its parent.
Return the recorded diameter after visiting the tree.
# The TreeNode type is provided by the platform.
class Solution:
def diameterOfBinaryTree(self, root):
diameter = 0
def height(node):
nonlocal diameter
if node is None:
return 0
left_height = height(node.left)
right_height = height(node.right)
# The path through this node uses one edge per level
# from each child subtree.
diameter = max(diameter, left_height + right_height)
# Return this subtree's height in nodes.
return 1 + max(left_height, right_height)
height(root)
return diameter
Complexity:
Time: O(n), because each node is visited once.
Space: O(h), for the recursion stack, where h is the tree height.
Common follow-ups
What if the diameter should be measured in nodes? Add one to the edge count for a non-empty tree.
How does a skewed tree affect recursion space? Its height is O(n), so recursion may use O(n) stack space.
Can this be done iteratively? Yes; use an explicit stack and process nodes in postorder while storing subtree heights.
CodingEasyFlipkartSoftware Engineer
3. Two Sum (LeetCode)
Model answer
The task
Given a list of integers and a target, return the indices of two distinct elements whose values add up to the target. The usual version guarantees a valid pair.
Key idea
As we scan the list, store each value’s index in a hash table. For the current value, check whether its needed complement has already appeared; this finds a pair in one pass.
Approach
Create a dictionary mapping previously seen values to their indices.
For each element, compute the complement needed to reach the target.
If that complement is in the dictionary, return its stored index and the current index.
Otherwise, store the current value and index, then continue.
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# Map each value already visited to its index.
seen = {}
for index, value in enumerate(nums):
complement = target - value
# A match must come from an earlier, distinct element.
if complement in seen:
return [seen[complement], index]
seen[value] = index
# The standard problem guarantees a solution.
raise ValueError("No two elements sum to the target")
Complexity:
Time: O(n), where n is the number of elements; each lookup and insertion is O(1) on average.
Space: O(n), for the dictionary of values seen so far.
Common follow-ups
What if there may be multiple valid pairs? Return the first pair found, or keep searching and collect pairs according to the required output rules.
What if the input is sorted? Use two pointers from opposite ends for O(1) extra space; preserve original indices if those are required.
What if values repeat? The dictionary stores indices, and checking before insertion ensures the current element is not paired with itself.
CodingEasyFlipkartSoftware Engineer
4. Valid Parentheses (LeetCode)
Model answer
The task
Determine whether a string of opening and closing round, square, and curly brackets is correctly nested and matched. Return a boolean.
Key idea
A closing bracket must match the most recent unmatched opening bracket. A stack captures that order: push openings, and check each closing bracket against the stack’s top.
Approach
Return False if the string has odd length.
Map each closing bracket to its matching opening bracket.
Scan the string from left to right.
Push opening brackets onto the stack.
For a closing bracket, return False if the stack is empty or its top does not match; otherwise pop.
Return True only if the stack is empty after the scan.
class Solution:
def isValid(self, s: str) -> bool:
pairs = {")": "(", "]": "[", "}": "{"}
openings = set(pairs.values())
stack = []
for char in s:
if char in openings:
stack.append(char)
else:
# A closing bracket must match the latest unmatched opening.
if not stack or stack[-1] != pairs.get(char):
return False
stack.pop()
# Unmatched opening brackets make the sequence invalid.
return not stack
Complexity:
Time: O(n), where n is the string length; each character is processed once.
Space: O(n) in the worst case, when all characters are opening brackets.
Common follow-ups
How would you support additional bracket types? Add their matching pairs to the map.
Can you stop early? Yes; return False as soon as a closing bracket mismatches or has no opening bracket.
What if the input includes non-bracket characters? Define how to handle them, then either ignore them or reject them during the scan.
CodingEasyFlipkartSoftware Engineer
5. Best Time to Buy and Sell Stock (LeetCode)
Model answer
The task
Given daily stock prices, find the greatest profit possible from one buy followed by one later sale. If no sale would make money, return zero.
Key idea
As we scan the prices, keep the lowest price seen so far. Treat each current price as a possible sale and update the best profit using the difference from that minimum.
Approach
Initialize the minimum price to a value larger than any price and the best profit to zero.
Visit each price in order.
Update the minimum price with the current price.
Check the profit from selling today and update the best profit.
Return the best profit.
class Solution:
def maxProfit(self, prices: list[int]) -> int:
min_price = float("inf")
best_profit = 0
for price in prices:
# The current price can be a new best day to buy.
min_price = min(min_price, price)
# Or it can be the day to sell after the cheapest earlier buy.
best_profit = max(best_profit, price - min_price)
return best_profit
Complexity:
Time: O(n), where n is the number of prices; each is processed once.
Space: O(1), since only a few variables are stored.
Common follow-ups
What if multiple buy-and-sell transactions are allowed? Sum the gains from every adjacent price increase.
What if a transaction fee is charged? Track the best holding and non-holding profits, incorporating the fee when selling.
What if at most k transactions are allowed? Use dynamic programming over the number of completed transactions and whether a share is currently held.
CodingEasyFlipkartSoftware Engineer
6. Find The Least Frequent Digit (LeetCode)
Model answer
The task
Given an integer, find the digit that occurs least often in its decimal representation. If several digits share the lowest frequency, return the smallest one.
Key idea
Count each digit, then choose the digit with the smallest pair (frequency, digit). Only digits that appear in the number are candidates.
Approach
Convert the absolute value of the number to a string, so negative signs are ignored.
Count the occurrences of each digit.
Select the digit with the smallest frequency, breaking ties by digit value.
Return that digit as an integer.
class Solution:
def getLeastFrequentDigit(self, n: int) -> int:
# Count the digits in the number; abs handles a possible negative sign.
counts = {}
for char in str(abs(n)):
digit = int(char)
counts[digit] = counts.get(digit, 0) + 1
# Minimize frequency first, then digit value for ties.
return min(counts, key=lambda digit: (counts[digit], digit))
Complexity:
Time: O(d), where d is the number of digits.
Space: O(1), since at most 10 distinct digits are counted.
Common follow-ups
How would you handle ties differently? Change the secondary sort key to the desired tie-breaking rule.
What if the input is given as a string? Count its digit characters directly, ignoring any sign.
Can you process digits without converting to a string? Repeatedly use % 10 and integer division, with a special case for zero.
CodingMediumFlipkartSoftware Engineer
7. Evaluate Division (LeetCode)
Model answer
The task
Given equations that define ratios between variables, answer queries asking for a ratio between two variables. Return -1.0 when the ratio cannot be determined.
Key idea
Represent each equation as two directed graph edges: from a to b with weight a / b, and from b to a with the reciprocal weight. A path’s edge weights multiply to give the ratio between its endpoints.
Approach
Build a weighted adjacency list from the equations.
For each query, return -1.0 if either variable is unknown.
Otherwise, use DFS to find a path between the variables, multiplying edge weights along the way.
Track visited variables so cycles do not cause repeated exploration.
If the variables are the same and known, the ratio is 1.0.
from collections import defaultdict
from typing import List
class Solution:
def calcEquation(
self,
equations: List[List[str]],
values: List[float],
queries: List[List[str]]
) -> List[float]:
graph = defaultdict(list)
for (numerator, denominator), value in zip(equations, values):
graph[numerator].append((denominator, value))
graph[denominator].append((numerator, 1.0 / value))
def find_ratio(start: str, target: str) -> float:
if start not in graph or target not in graph:
return -1.0
if start == target:
return 1.0
stack = [(start, 1.0)]
visited = {start}
while stack:
variable, product = stack.pop()
for neighbor, edge_value in graph[variable]:
if neighbor in visited:
continue
next_product = product * edge_value
if neighbor == target:
return next_product
visited.add(neighbor)
stack.append((neighbor, next_product))
return -1.0
return [find_ratio(a, b) for a, b in queries]
Complexity:
Time: O(Q(V + E)), where each query may traverse the full graph.
Space: O(V + E) for the graph and the DFS state.
Common follow-ups
How can repeated queries be sped up? Use weighted union-find to answer each query in near-constant time after preprocessing.
How would you handle inconsistent equations? Detect conflicting ratios when connecting variables or revisiting an already-connected pair.
What if the graph is very large but queries are few? Keep DFS/BFS per query to avoid more elaborate preprocessing.
CodingMediumFlipkartSoftware Engineer
8. Pacific Atlantic Water Flow (LeetCode)
Model answer
The task
Given a grid of elevations, find every cell from which water can flow to both the Pacific and Atlantic oceans. Water can flow between adjacent cells only downhill or across cells of equal height; the Pacific borders the top and left edges, and the Atlantic borders the bottom and right edges.
Key idea
Instead of tracing water downhill from every cell, search backward from each ocean. From a cell already reachable by an ocean, the reverse search can move to an adjacent cell of equal or greater height.
Approach
Return an empty list if the grid has no rows or columns.
Initialize one search from the Pacific-border cells and another from the Atlantic-border cells.
In each search, visit a neighbor only if it is in bounds, unvisited, and at least as high as the current cell.
Return the coordinates visited by both searches.
from collections import deque
from typing import List
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
if not heights or not heights[0]:
return []
rows, cols = len(heights), len(heights[0])
def reachable(starts):
visited = set(starts)
queue = deque(starts)
while queue:
r, c = queue.popleft()
for nr, nc in ((r - 1, c), (r + 1, c),
(r, c - 1), (r, c + 1)):
if (0 <= nr < rows and 0 <= nc < cols
and (nr, nc) not in visited
and heights[nr][nc] >= heights[r][c]):
visited.add((nr, nc))
queue.append((nr, nc))
return visited
pacific_starts = (
[(0, c) for c in range(cols)]
+ [(r, 0) for r in range(rows)]
)
atlantic_starts = (
[(rows - 1, c) for c in range(cols)]
+ [(r, cols - 1) for r in range(rows)]
)
pacific = reachable(pacific_starts)
atlantic = reachable(atlantic_starts)
return [[r, c] for r, c in pacific & atlantic]
Complexity:
Time: O(rows × cols), since each cell is visited at most once per search.
Space: O(rows × cols) for the visited sets and queues.
Common follow-ups
Can DFS replace BFS? Yes; either traversal finds the same reachable cells.
How would you handle diagonal flow? Include diagonal neighbors in the traversal.
What if the grid is updated repeatedly? Recompute reachability, or use a specialized dynamic-connectivity strategy if updates are frequent.
CodingMediumFlipkartSoftware Engineer
9. Number of Islands (LeetCode)
Model answer
The task
Given a grid of land and water, count the groups of connected land cells. Cells connect horizontally or vertically, not diagonally.
Key idea
Each group is one island. Scan the grid, and whenever an unvisited land cell is found, count a new island and explore its entire connected region. Mark cells as visited when adding them to the search queue so no cell is processed more than once.
Approach
Return 0 if the grid is empty.
Scan every cell in the grid.
When a land cell is found, increment the island count and start a breadth-first search from it.
During the search, mark each discovered land cell as water and add its in-bounds land neighbors to the queue.
Return the island count after the scan is complete.
from collections import deque
from typing import List
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
islands = 0
for row in range(rows):
for col in range(cols):
if grid[row][col] != "1":
continue
islands += 1
grid[row][col] = "0"
queue = deque([(row, col)])
while queue:
current_row, current_col = queue.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
next_row = current_row + dr
next_col = current_col + dc
if (
0 <= next_row < rows
and 0 <= next_col < cols
and grid[next_row][next_col] == "1"
):
# Mark when enqueuing to avoid duplicate work.
grid[next_row][next_col] = "0"
queue.append((next_row, next_col))
return islands
Complexity: Time: O(rows * cols), since each cell is examined at most a constant number of times.
Complexity: Space: O(rows * cols) in the worst case for the BFS queue.
Common follow-ups
Preserve the input grid? Track visited cells in a separate set instead of changing land cells to water.
Use depth-first search instead? Recursively or iteratively explore the four neighbors; iterative DFS avoids recursion-depth concerns.
Count diagonally connected land as part of the same island? Include the four diagonal directions in the neighbor list.
CodingMediumFlipkartSoftware Engineer
10. Delete Node in a BST (LeetCode)
Model answer
The task
Remove the node with a given key from a binary search tree, preserving the ordering property. If the key is absent, leave the tree unchanged.
Key idea
Finding the node uses the BST ordering, so only one search path needs to be explored. For a node with two children, replace its value with its in-order successor—the smallest value in its right subtree—and then remove that successor.
Approach
If the current node is empty, return it.
Compare the key with the current value and recurse into the appropriate subtree.
Once found, return its only child if it has at most one child.
If it has two children, copy the smallest value from the right subtree into it.
Delete that successor from the right subtree and return the updated root.
# Definition for a binary tree node:
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if root is None:
return None
if key < root.val:
root.left = self.deleteNode(root.left, key)
elif key > root.val:
root.right = self.deleteNode(root.right, key)
else:
# With zero or one child, the remaining subtree replaces this node.
if root.left is None:
return root.right
if root.right is None:
return root.left
# The successor is the leftmost node in the right subtree.
successor = root.right
while successor.left is not None:
successor = successor.left
root.val = successor.val
# Remove the duplicate successor now that its value was copied.
root.right = self.deleteNode(root.right, successor.val)
return root
Complexity:
Time: O(h), where h is the tree height; searching and successor removal each follow a path.
Space: O(h) for recursive calls; this is O(log n) for a balanced tree and O(n) in the worst case.
Common follow-ups
How would you avoid recursion? Use an iterative search while tracking the parent, then reconnect the replacement subtree.
What if the tree is highly unbalanced? The operation can take O(n); a self-balancing BST keeps height logarithmic.
Could you use the predecessor instead? Yes: take the largest value in the left subtree and remove that node instead.
CodingMediumFlipkartSoftware Engineer
11. Amount of Time for Binary Tree to Be Infected (LeetCode)
Model answer
The task
Given a binary tree and the value of its starting node, find how many minutes it takes for the infection to reach every node. Each minute, infection spreads from an infected node to its parent and children.
Key idea
Treat the tree as an undirected graph: each node is connected to its children and parent. A breadth-first search from the starting node visits nodes in increasing order of infection time.
Approach
Traverse the tree and record each node’s parent.
Find the node whose value matches start.
Run BFS from that node, tracking visited nodes to avoid revisiting through parent links.
Count BFS levels; the last level reached is the time needed to infect all nodes.
from collections import deque
from typing import Optional
# Assumes TreeNode has attributes val, left, and right.
class Solution:
def amountOfTime(self, root: Optional["TreeNode"], start: int) -> int:
if root is None:
return 0
parent = {}
start_node = None
stack = [root]
# Record parent links and locate the starting node.
while stack:
node = stack.pop()
if node.val == start:
start_node = node
if node.left:
parent[node.left] = node
stack.append(node.left)
if node.right:
parent[node.right] = node
stack.append(node.right)
# Visit each node once, expanding one infection minute at a time.
queue = deque([start_node])
visited = {start_node}
minutes = -1
while queue:
minutes += 1
for _ in range(len(queue)):
node = queue.popleft()
for neighbor in (node.left, node.right, parent.get(node)):
if neighbor is not None and neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return minutes
Complexity:
Time: O(n), since each node is processed a constant number of times.
Space: O(n), for parent links, the BFS queue, and the visited set.
Common follow-ups
What if the start value is absent? Return an error or a designated sentinel, depending on the API.
Can the parent map be avoided? Yes; use DFS to compute distances from the start while tracking paths, though the bookkeeping is less direct.
What if the tree is extremely deep? The iterative traversals avoid recursion-depth limits.
CodingMediumFlipkartSoftware Engineer
12. Rotting Oranges (LeetCode)
Model answer
The task
Given a grid of empty cells, fresh oranges, and rotten oranges, find the minimum number of minutes until no fresh oranges remain. Each minute, a rotten orange makes any fresh orange directly above, below, left, or right of it rotten; return -1 if some fresh oranges can never be reached.
Key idea
Use multi-source breadth-first search: all initially rotten oranges spread at the same time, so put them all in the queue at the start. Process the queue one minute at a time, counting newly rotten oranges to detect whether any fresh ones remain unreachable.
Approach
Count the fresh oranges and enqueue every initially rotten orange.
If there are no fresh oranges, return 0.
For each BFS layer, rot adjacent fresh oranges, decrement the fresh count, and enqueue them.
Count each processed layer as one minute.
Return the minutes if all fresh oranges rotted; otherwise return -1.
from collections import deque
from typing import List
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
queue = deque()
fresh = 0
# Gather all initial sources and count oranges that still need to rot.
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
queue.append((r, c))
elif grid[r][c] == 1:
fresh += 1
if fresh == 0:
return 0
minutes = 0
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
while queue and fresh > 0:
# Process exactly the oranges rotten before this minute began.
for _ in range(len(queue)):
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if (
0 <= nr < rows
and 0 <= nc < cols
and grid[nr][nc] == 1
):
grid[nr][nc] = 2
fresh -= 1
queue.append((nr, nc))
minutes += 1
return minutes if fresh == 0 else -1
Complexity:
Time: O(rows × cols), since each cell is visited at most once.
Space: O(rows × cols) for the BFS queue in the worst case.
Common follow-ups
What if diagonal neighbors also spread rot? Add the four diagonal directions to the neighbor list.
Can the original grid be preserved? Copy it first, or track visited cells separately.
How would you return which oranges rot each minute? Store each BFS layer’s cells or record a rot-time value per cell.
CodingMediumFlipkartSoftware Engineer
13. Maximum Width of Binary Tree (LeetCode)
Model answer
The task
Find the largest width among all levels of a binary tree. A level’s width counts the gaps between its leftmost and rightmost non-null nodes, as if the tree were complete.
Key idea
Assign each node the position it would occupy in a complete binary tree. The width of a level is the last occupied position minus the first, plus one. Normalize positions at each level to keep the indices manageable.
Approach
Return 0 if the tree is empty.
Use breadth-first search, storing each node with its position in the current level.
For each level, subtract its first position from all positions.
Record the width as the last normalized position plus one.
Enqueue each child at positions 2 index and 2 index + 1.
from collections import deque
from typing import Optional
class TreeNode:
def __init__(
self,
val: int = 0,
left: Optional["TreeNode"] = None,
right: Optional["TreeNode"] = None,
):
self.val = val
self.left = left
self.right = right
class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
# Store each node with its complete-tree position.
queue = deque([(root, 0)])
maximum_width = 0
while queue:
level_size = len(queue)
first_position = queue[0][1]
last_position = 0
for _ in range(level_size):
node, position = queue.popleft()
# Shift this level's positions so its first node is at 0.
position -= first_position
last_position = position
if node.left is not None:
queue.append((node.left, 2 * position))
if node.right is not None:
queue.append((node.right, 2 * position + 1))
maximum_width = max(maximum_width, last_position + 1)
return maximum_width
Complexity:
Time: O(n), visiting each node once.
Space: O(w), where w is the maximum number of nodes on any level.
Common follow-ups
Can this be solved with DFS? Yes; track the first position at each depth and compare later positions at that depth.
What if the tree is very skewed? The queue holds only the nodes at the current or next level, so it remains small.
Why normalize positions? It preserves gaps within a level while avoiding unnecessarily large absolute indices.
CodingMediumFlipkartSoftware Engineer
14. Course Schedule (LeetCode)
Model answer
The task
Given a number of courses and prerequisite pairs, decide whether it’s possible to complete every course. A prerequisite pair means one course must be taken before another.
Key idea
Represent courses as a directed graph, with an edge from each prerequisite to the course that depends on it. A cycle means the courses in that cycle depend on one another, so not all courses can be completed.
Use Kahn’s topological-sort algorithm: repeatedly take courses with no remaining prerequisites and remove their outgoing edges.
Approach
Create an adjacency list and count each course’s prerequisites (its indegree).
Add every course with indegree zero to a queue.
Remove courses from the queue, counting each as completed.
Decrease the indegree of each dependent course; enqueue it when its indegree reaches zero.
Return whether the number completed equals the total number of courses.
from collections import deque
from typing import List
class Solution:
def canFinish(
self, numCourses: int, prerequisites: List[List[int]]
) -> bool:
# Edges point from prerequisite to the course that depends on it.
graph = [[] for _ in range(numCourses)]
indegree = [0] * numCourses
for course, prerequisite in prerequisites:
graph[prerequisite].append(course)
indegree[course] += 1
# Begin with courses that have no prerequisites.
ready = deque(
course
for course in range(numCourses)
if indegree[course] == 0
)
completed = 0
while ready:
course = ready.popleft()
completed += 1
for dependent in graph[course]:
indegree[dependent] -= 1
if indegree[dependent] == 0:
ready.append(dependent)
return completed == numCourses
Complexity:
Time: O(V + E), where V is the number of courses and E is the number of prerequisite pairs.
Space: O(V + E) for the graph, indegrees, and queue.
Common follow-ups
How can you return a valid course order? Record courses as they are removed from the queue; return the order if it includes every course.
How can DFS detect a cycle? Track nodes as unvisited, visiting, or finished; reaching a visiting node reveals a cycle.
What if there are no courses? The algorithm returns True, since zero courses can all be completed.
CodingMediumFlipkartSoftware Engineer
15. Spiral Matrix (LeetCode)
Model answer
The task
Return the matrix values in clockwise spiral order, starting from the top-left corner and moving inward.
Key idea
Track the unvisited rectangle with four boundaries. Visit its top, right, bottom, and left edges in turn, then shrink the rectangle and repeat.
Approach
Return an empty list if the matrix has no rows or columns.
Initialize boundaries for the top, bottom, left, and right edges.
Traverse the top edge, then move the top boundary inward.
Traverse the right edge, then move the right boundary inward.
If rows remain, traverse the bottom edge in reverse; if columns remain, traverse the left edge upward.
Repeat until the boundaries cross.
from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return []
result = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
# Traverse the top edge from left to right.
for col in range(left, right + 1):
result.append(matrix[top][col])
top += 1
# Traverse the right edge from top to bottom.
for row in range(top, bottom + 1):
result.append(matrix[row][right])
right -= 1
# Traverse the bottom edge only if it has not been visited.
if top <= bottom:
for col in range(right, left - 1, -1):
result.append(matrix[bottom][col])
bottom -= 1
# Traverse the left edge only if it has not been visited.
if left <= right:
for row in range(bottom, top - 1, -1):
result.append(matrix[row][left])
left += 1
return result
Complexity: Time: O(m × n), where each cell is visited once.
Complexity: Space: O(1) auxiliary space, excluding the output list.
Common follow-ups
How would you return the values counterclockwise? Change the traversal order and edge directions while maintaining the same boundary updates.
How does this handle a single row or column? The boundary checks prevent an edge from being visited twice.
Can the traversal be done without boundary variables? Yes, by marking visited cells and turning when blocked, but that requires O(m × n) extra space.
CodingMediumFlipkartSoftware Engineer
16. Course Schedule II (LeetCode)
Model answer
The task
Return an ordering of all courses that satisfies the prerequisite relationships. If no such ordering exists because the relationships contain a cycle, return an empty list.
Key idea
Model each course as a graph node, with an edge from a prerequisite to the course that depends on it. Kahn’s topological-sort algorithm repeatedly takes courses with no remaining prerequisites; if it cannot take every course, the graph contains a cycle.
Approach
Build an adjacency list and count each course’s prerequisites as its indegree.
Add all zero-indegree courses to a queue.
Remove courses from the queue, adding each to the result and reducing the indegree of its dependent courses.
Add a dependent course to the queue when its indegree reaches zero.
Return the result if it includes every course; otherwise, return an empty list.
from collections import deque
from typing import List
class Solution:
def findOrder(
self, numCourses: int, prerequisites: List[List[int]]
) -> List[int]:
# Edges point from prerequisite to dependent course.
graph = [[] for _ in range(numCourses)]
indegree = [0] * numCourses
for course, prerequisite in prerequisites:
graph[prerequisite].append(course)
indegree[course] += 1
ready = deque(
course
for course in range(numCourses)
if indegree[course] == 0
)
order = []
while ready:
course = ready.popleft()
order.append(course)
for dependent in graph[course]:
indegree[dependent] -= 1
if indegree[dependent] == 0:
ready.append(dependent)
# A cycle prevents all courses from being added.
return order if len(order) == numCourses else []
**Complexity:**
- Time: O(V + E), where V is the number of courses and E is the number of prerequisite relationships.
- Space: O(V + E) for the graph, indegrees, queue, and result.
**Common follow-ups**
- How can DFS solve this? Use three node states—unvisited, visiting, and visited—to detect cycles while building a topological order.
- How can the algorithm return the number of courses that can be completed? Return the length of the processed order.
- How can you choose the smallest-numbered available course at each step? Use a min-heap instead of a queue, giving O((V + E) log V) time.
System designHardFlipkartFrontend EngineerSystem Design / Product Sense
17. Design a booking app.
Model answer
1. Requirements & scale
I’ll scope this as a mobile-first hotel booking app: users search by destination and dates, compare available rooms, book, pay, and manage or cancel reservations. The design focuses on a fast, reliable frontend, while covering the backend contracts it depends on.
Functional: location/date/guest search, filters, hotel and room details, price breakdown, booking, payment, confirmation, and reservation management.
Non-functional: search results should feel responsive, prices and availability must be revalidated before payment, and booking must be idempotent. The app should remain usable on slow or intermittent mobile connections.
Assumptions: 5 million monthly users, 200,000 daily searches, and a 2% search-to-booking conversion rate.
At peak, assume 10x average traffic: 200,000 searches/day ÷ 86,400 × 10 ≈ 23 search requests/s. Browsing detail pages and static assets can multiply read traffic; plan for 1,000 API reads/s and 50 booking attempts/s at peak.
If a search response averages 50 KB, 1,000 responses/s is about 50 MB/s before compression and CDN caching. At 100,000 bookings/day and 2 KB of core booking data, that is about 200 MB/day, or 73 GB/year before indexes and replicas.
2. High-level architecture
The frontend is a responsive web app, with a shared design system and server-rendered entry pages for discoverability. A BFF shapes backend data into screen-ready payloads; booking and payment remain authoritative server-side operations.
flowchart TD
subgraph Client
U[Guest]
W[Web App]
end
subgraph EdgeCDN[Edge and CDN]
CDN[CDN]
FW[Web Firewall]
end
subgraph LoadBalancer[Load Balancer]
LB[Regional Gateway]
end
subgraph APIServices[API and Services]
BFF[Frontend BFF]
Search[Search Service]
Booking[Booking Service]
Payment[Payment Service]
Notify[Notification Service]
end
subgraph Cache[Cache]
RC[Redis Search Cache]
end
subgraph Datastores[Datastores]
Index[Search Index]
SQL[Booking SQL]
Hotel[Hotel Catalog]
end
subgraph MessageQueue[Message Queue]
Q[Booking Events]
end
subgraph Workers[Workers]
Worker[Confirmation Worker]
end
U -->|browse| W
W -->|assets and page data| CDN
CDN -->|cache miss| FW
FW -->|API request| LB
LB -->|route| BFF
BFF -->|search query| Search
Search -->|read or write| RC
Search -->|availability lookup| Index
BFF -->|hotel content| Hotel
W -->|reserve and pay| LB
BFF -->|create reservation| Booking
Booking -->|transaction| SQL
Booking -->|payment intent| Payment
Booking -->|booking event| Q
Q -->|confirmation task| Worker
Worker -->|send confirmation| Notify
Diagram
3. API design
GET /v1/search?destination=&checkIn=&checkOut=&guests=&cursor= returns ranked hotels, room availability, price, and pagination metadata.
GET /v1/hotels/{hotelId}?checkIn=&checkOut= returns hotel details and date-specific room offers.
POST /v1/bookings accepts an offer ID, guest details, and an idempotency key; returns a pending booking and payment instructions.
POST /v1/bookings/{bookingId}/confirm confirms payment status; GET /v1/bookings/{bookingId} retrieves current status.
DELETE /v1/bookings/{bookingId} requests cancellation and returns the applicable refund policy.
4. Data model & storage
A search index stores denormalized hotel location, amenities, ratings, and searchable attributes. Partition geographically where useful; availability and prices are time-sensitive and must have a short freshness window.
Hotel content can live in a relational catalog or document store, with images in object storage behind a CDN.
SQL stores bookings, guests, payment references, and cancellation state. Partition by booking ID or creation month; enforce uniqueness on the idempotency key and use transactions for state transitions.
Redis caches popular search results by normalized destination, dates, occupancy, and filter set. Use short TTLs and never treat cached availability as a reservation guarantee.
5. Deep dive
The critical path is avoiding double booking while keeping search fast. Search results are advisory; booking must atomically revalidate and hold inventory. The UI should make that distinction clear, display a countdown for a temporary hold, and disable repeated submit actions without relying on the button as the only duplicate-prevention mechanism.
sequenceDiagram
participant U as Guest
participant W as Web App
participant B as Booking API
participant I as Inventory
participant P as Payment
participant Q as Event Queue
U->>W: Select room and submit
W->>B: Create booking with idempotency key
B->>I: Atomically check and hold inventory
I-->>B: Hold token and expiry
B->>P: Create payment intent
P-->>W: Payment instructions
W->>P: Complete payment
P-->>B: Signed payment result
B->>I: Confirm hold and decrement inventory
B->>Q: Publish booking confirmed
B-->>W: Confirmed booking
Diagram
The frontend models this as explicit states: idle, submitting, payment_required, confirmed, and failed. A refresh or network timeout calls GET /v1/bookings/{bookingId} rather than blindly submitting again. If payment succeeds but the confirmation response is lost, the idempotency key and booking status lookup recover safely. Payment callbacks are authenticated, deduplicated, and reconciled asynchronously; expired holds are released by a worker.
6. Scale, bottlenecks & trade-offs
Serve versioned JS, CSS, and images from the CDN; use responsive images, compression, lazy loading, and route-level code splitting. Server-render the initial search/detail shell, then hydrate interactive controls.
Cache popular searches, but vary keys by all result-affecting inputs and invalidate or expire aggressively. Availability correctness takes precedence over cache hit rate.
Run stateless APIs across zones; replicate read-heavy catalog and search data. Keep the booking database strongly consistent for inventory transitions, accepting that it may be less available during a partition than a stale search view.
Make payment and notification processing asynchronous after durable state changes. Use an outbox, retries with backoff, dead-letter queues, and reconciliation for delayed or duplicate events.
Measure Core Web Vitals, search latency, search-to-detail conversion, booking success, payment failure, and inventory conflict rate by device, network, and region. Roll out UI and API changes behind flags with a control group.
System designHardFlipkartFrontend EngineerSystem Design / Product Sense
18. Design Google Calendar.
Model answer
1. Requirements & scale
Functional requirements
Create, edit, delete, and view events; support recurring events, time zones, guests, reminders, and multiple calendars.
Provide day, week, month, and agenda views, plus search and invitations.
Keep changes synchronized across devices and reflect attendee responses.
Non-functional requirements
Calendar views should load quickly, remain usable on mobile, and work gracefully during transient network failures.
Event edits need durable storage and clear conflict handling; attendee updates should propagate promptly.
Recurrence and daylight-saving behavior must be correct. Access control must prevent unauthorized event disclosure.
Estimates Assume 100 million daily active users, 10 calendar reads per user per day, and 0.2 event mutations per user per day. That is about 1 billion reads/day, or 12K average reads/s; at 10× peak, about 120K reads/s. Mutations are about 20 million/day, or 230/s average. At 2 KB per event version, raw new event data is about 40 GB/day before indexes and replication. A month view usually needs only a bounded date range, not a full calendar download.
2. High-level architecture
flowchart TD
subgraph Client["Client"]
UI["Web and mobile UI"]
Local["Local cache and offline queue"]
end
subgraph Edge["Edge/CDN"]
CDN["Static assets and API edge"]
end
subgraph LB["Load Balancer"]
LB1["Regional API load balancer"]
end
subgraph Services["API / Services"]
Calendar["Calendar API"]
Event["Event and recurrence service"]
Share["Sharing and ACL service"]
Notify["Notification service"]
end
subgraph Cache["Cache"]
Cache1["Calendar range cache"]
Cache2["User and ACL cache"]
end
subgraph Stores["Datastores"]
DB["Sharded event database"]
Search["Search index"]
Blob["Attachments object storage"]
end
subgraph Queue["Message Queue"]
Events["Event change log"]
end
subgraph Workers["Workers"]
Fanout["Guest update and reminder workers"]
Indexer["Search indexer"]
Push["Push and email delivery"]
end
UI -->|"calendar range request"| CDN
Local -->|"queued edits and sync token"| CDN
CDN -->|"API request"| LB1
LB1 --> Calendar
Calendar -->|"authorize and resolve range"| Share
Calendar -->|"read or write"| Event
Event -->|"hot range lookup"| Cache1
Share -->|"ACL lookup"| Cache2
Event -->|"durable event data"| DB
Calendar -->|"text query"| Search
Event -->|"attachment metadata"| Blob
Event -->|"committed change"| Events
Events --> Fanout
Events --> Indexer
Fanout -->|"reminders and guest updates"| Push
Diagram
3. API design
GET /v1/calendars/{id}/events?timeMin=&timeMax=&syncToken= — fetch a bounded range or incremental changes.
POST /v1/calendars/{id}/events — create an event; accept an idempotency key.
PATCH /v1/events/{eventId} — update selected fields with an If-Match version.
DELETE /v1/events/{eventId} — delete or cancel an event.
POST /v1/events/{eventId}/attendees:respond — accept, decline, or tentatively accept.
GET /v1/events:search?q=&pageToken= — search authorized events.
4. Data model & storage
Store canonical event records in a sharded relational or distributed SQL store. Fields include event_id, calendar_id, organizer_id, start, end, time_zone, recurrence_rule, version, and visibility.
Store attendee state separately, keyed by (event_id, user_id), so guest responses can be updated without rewriting the event body.
Partition event access by calendar_id; index (calendar_id, start_time) for range reads. Large calendars may need time-bucketed partitions and a routing layer.
Keep ACLs in a strongly consistent store, with short-lived cached entries. Store attachments in object storage and searchable text in a derived index.
Keep a change log with monotonically increasing per-calendar sequence numbers. It supports incremental sync and asynchronous fan-out.
5. Deep dive
The main correctness challenge is recurring events across time zones, combined with efficient range loading and synchronization. Store the recurrence rule and the event's IANA time-zone identifier, not just a UTC offset. For a weekly event at 9 a.m. in a named zone, generate each occurrence in that zone and convert each resulting local time to UTC. This preserves 9 a.m. across daylight-saving transitions. Apply exceptions and cancellations as overrides keyed by the recurrence instance's original start time.
For a requested date range, expand only recurrence instances that overlap the range, with a bounded look-back for events that began earlier but continue into it. Cache the resulting range briefly, invalidating it when the calendar's change sequence advances. Avoid materializing an unbounded series of future occurrences.
Edits use optimistic concurrency: the client sends the version it last read. If it is stale, return a conflict with the current version; the UI can merge non-overlapping field changes or ask the user to resolve competing edits. Offline clients queue idempotent mutations and reconcile them using the server's change log.
sequenceDiagram
participant C as Client
participant A as Calendar API
participant E as Event service
participant D as Event database
participant Q as Change queue
participant W as Fanout workers
C->>A: GET range with sync token
A->>E: Check ACL and resolve recurrence
E->>D: Read range and sequence
D-->>E: Events and sequence
E-->>C: Events and next sync token
C->>A: PATCH event with version
A->>E: Validate ACL and version
E->>D: Commit event and new sequence
D-->>E: Commit success
E->>Q: Publish committed change
E-->>C: Updated event and version
Q->>W: Deliver change
W->>W: Notify guests and refresh derived indexes
Diagram
6. Scale, bottlenecks & trade-offs
Replicate event data across availability zones and use regional read replicas for range reads. Route writes to a calendar's home region to preserve ordering; fail over with explicit fencing to avoid split-brain writes.
Use cache-aside for range data and ACLs, but treat the database as authoritative. Invalidate by calendar sequence rather than relying only on TTLs.
Make guest notifications, search indexing, and reminders asynchronous and idempotent. The event save should not wait for email delivery; show the committed event immediately and expose delivery state separately if needed.
Use short-lived consistency for cached views, but strong validation on permission checks and event writes. A brief stale view is acceptable; leaking a private event is not.
Partitioning by calendar makes common access efficient but can create hot partitions for heavily shared calendars. Rate-limit abusive clients and split unusually large calendars by time range. Keep recurrence expansion bounded and paginate large responses.
Prefer relational transactions for event and attendee invariants; use the change log and search index as derived systems. This trades some indexing delay for reliable writes and simpler correctness.
System designHardFlipkartFrontend EngineerSystem Design / Product Sense
19. Design Flipkart's homepage.
Model answer
1. Requirements & scale
I’ll design Flipkart’s marketplace homepage for app and web, emphasizing fast discovery, relevant merchandising, and resilience during major sale events. The page should work for signed-in and anonymous users, with personalization that never blocks the initial render.
Functional: render campaign banners, search entry, category navigation, personalized product shelves, deal modules, and continue-browsing content. Support location-aware availability, deep links, and accessible responsive layouts.
Non-functional: fast first contentful paint, graceful loading on low-end devices, safe fallbacks when recommendation services fail, and fresh price/stock data at product selection.
Assume 100 million daily active users and 10 homepage visits per user per day: 1 billion views/day, or about 11,600 average requests/s. At a 5x peak, plan for roughly 58,000 homepage requests/s.
With a 100 KB compressed initial response, peak response traffic is about 5.8 GB/s. CDN delivery of static assets and cacheable merchandising content is therefore essential.
If each response references 40 product cards at 1 KB of compact card data, uncompressed product payload is about 40 KB per view. Persisting 10 KB of homepage interaction events per daily user is roughly 1 TB/day before compression and retention policies.
2. High-level architecture
Use a frontend BFF to assemble a page from independently degradable modules. The browser renders a stable shell and above-the-fold content first; lower shelves load on demand. Product cards may show cached display data, but product detail and cart APIs revalidate price and availability.
flowchart TD
subgraph Client
U[Shopper]
App[Flipkart Web or App]
end
subgraph EdgeCDN[Edge and CDN]
CDN[CDN Assets and Shell]
Edge[Edge Rules]
end
subgraph LoadBalancer[Load Balancer]
LB[Regional Gateway]
end
subgraph APIServices[API and Services]
BFF[Homepage BFF]
Merch[Merchandising Service]
Rec[Recommendation Service]
Catalog[Catalog Service]
Search[Search Service]
Profile[Profile Service]
end
subgraph Cache[Cache]
PageCache[Page Fragment Cache]
RecCache[Recommendation Cache]
end
subgraph Datastores[Datastores]
ProductDB[Product Catalog]
UserDB[User Profile Store]
SearchIndex[Search Index]
end
subgraph MessageQueue[Message Queue]
Events[Interaction Events]
end
subgraph Workers[Workers]
Ranker[Ranking and Analytics Workers]
end
U -->|open homepage| App
App -->|static assets| CDN
App -->|page request| Edge
Edge -->|dynamic request| LB
LB -->|homepage API| BFF
BFF -->|campaign modules| Merch
BFF -->|personalized shelves| Rec
BFF -->|product card data| Catalog
BFF -->|anonymous context| Search
Rec -->|read| RecCache
Merch -->|read| PageCache
Catalog -->|product and offer data| ProductDB
Rec -->|signals| UserDB
Search -->|candidate products| SearchIndex
App -->|views and clicks| Events
Events -->|consume| Ranker
Ranker -->|update rankings| RecCache
Diagram
3. API design
GET /api/v1/home?marketplace=IN&device=app&locationId=... returns page version, modules, and initial cards. Accept a request ID and experiment assignments.
GET /api/v1/home/modules/{moduleId}?cursor=... fetches later shelf pages without reloading the homepage.
GET /api/v1/products/{productId}/summary revalidates current offer, price, and availability for a card or quick view.
POST /api/v1/events batches impression, click, and dismissal events; return accepted event IDs.
GET /api/v1/search/suggestions?q=... supports the prominent search entry point.
4. Data model & storage
Product catalog records include product ID, category, attributes, image references, and listing status. Offers and inventory are separate, since they change more often. Partition catalog reads by product ID and index searchable attributes in a search engine.
Merchandising configuration stores campaign, module order, eligibility, and start/end times. Publish versioned snapshots to a low-latency cache so a campaign launch does not depend on querying a relational database per view.
User profile data stores consent, coarse preferences, and eligible personalization context. Use a privacy-aware user ID and do not expose sensitive attributes to the browser.
Cache anonymous and broadly shared fragments separately from personalized responses. Use short TTLs for offers, longer TTLs for static module configuration, and explicit versioning for invalidation.
Interaction events go to a durable queue and then an analytics store; they should not add synchronous latency to page rendering.
5. Deep dive
The main challenge is assembling a relevant page within a strict latency budget without making the whole homepage depend on its slowest service. The BFF should enforce a deadline, request independent modules in parallel, and return partial results. For example, reserve 150 ms for campaign and category content, 250 ms for personalized shelves, and a 500 ms overall server deadline; the client can continue loading below-the-fold modules afterward.
sequenceDiagram
participant C as Client
participant B as Homepage BFF
participant M as Merchandising
participant R as Recommendations
participant P as Product Catalog
participant E as Event Queue
C->>B: Request homepage with context
par Parallel module fetches
B->>M: Get active campaign modules
M-->>B: Versioned module list
B->>R: Get ranked product IDs
R-->>B: Ranked IDs or fallback IDs
end
B->>P: Batch fetch card summaries
P-->>B: Cards with display price and stock hint
B-->>C: Above-fold response and cursors
C->>E: Batch impressions and clicks
C->>B: Fetch next shelf page
Diagram
The client renders a shell immediately, prioritizes the search bar and first campaign, and uses skeletons only for modules that have not arrived. Each module has a stable schema and independent error state. If recommendations time out, the BFF returns category bestsellers or curated content; if a single product card fails, omit that card rather than failing the shelf. Impression events should be emitted only when a module is actually visible, with deduplication keys to avoid inflating metrics after rerenders.
6. Scale, bottlenecks & trade-offs
Put immutable assets and cacheable public page fragments on a CDN. Use responsive image variants, lazy loading, preconnect selectively, and split client bundles by route and module. Avoid shipping every homepage interaction in the initial JS payload.
Personalization improves relevance but reduces shared-cacheability. Cache a common shell and curated modules broadly; fetch user-specific ranking separately, keyed by a privacy-safe cohort or user context with strict TTLs.
Keep the BFF stateless and multi-zone. Apply per-service timeouts, bulkheads, circuit breakers, and concurrency limits so a recommendation outage cannot exhaust homepage capacity.
Precompute candidate rankings for common cohorts and refresh them asynchronously. Use online signals for re-ranking only when latency and freshness justify the added complexity.
Choose availability for homepage reads during partial outages, while clearly labeling data as a display snapshot and revalidating price and stock before cart or checkout. Do not let a cached card promise a final offer.
Track p75/p95 homepage latency, Core Web Vitals, module availability, search starts, product clicks, add-to-cart conversion, and revenue per session. Guardrails include crash rate, stale-price complaints, accessibility, and performance by device/network. Roll out experiments gradually and compare cohorts without changing the event definition mid-test.
System designHardFlipkartFrontend EngineerSystem Design / Product Sense
20. Design a website builder like Wix.
Model answer
1. Requirements & scale
Functional requirements
Let users visually build responsive websites from templates and components, edit text and media, configure styles, and preview desktop and mobile layouts.
Support pages, reusable sections, navigation, forms, asset uploads, collaboration, version history, and publishing to a custom domain.
Serve published sites quickly and safely, separately from the authenticated editor.
Non-functional requirements
Editing must feel immediate, autosave reliably, and recover after a refresh or network interruption.
Published pages need high availability, low latency, SEO-friendly output, and isolation between customer sites.
Publishing should be atomic: visitors see either the previous version or the new version, never a partially deployed site.
Estimates Assume 10 million published sites averaging 20 pages and 50 KB of compressed HTML/CSS/JS per page. That is roughly 10 TB of page output before replication; images and video dominate storage and live in object storage. At 100 million page views/day, average traffic is about 1.2K requests/s; at a 10× peak, about 12K requests/s. If 1 million creators make 30 edits/day, that is 30 million edit operations/day, about 350/s average and 3.5K/s at peak. CDN caching should serve most published traffic without hitting application services.
2. High-level architecture
flowchart TD
subgraph Client["Client"]
Editor["Visual editor"]
Runtime["Published site browser"]
Draft["Local draft and operation queue"]
end
subgraph Edge["Edge/CDN"]
CDN["Site and asset CDN"]
end
subgraph LB["Load Balancer"]
LB1["Regional API load balancer"]
end
subgraph Services["API / Services"]
Project["Project and page API"]
Collab["Collaboration service"]
Media["Media and domain service"]
Publish["Publish orchestration service"]
Render["Site render service"]
end
subgraph Cache["Cache"]
Cache1["Project snapshot cache"]
Cache2["Published manifest cache"]
end
subgraph Stores["Datastores"]
DB["Project and version database"]
Assets["Asset object storage"]
Search["Site search index"]
end
subgraph Queue["Message Queue"]
Jobs["Publish and indexing jobs"]
end
subgraph Workers["Workers"]
Build["Build and validation workers"]
Deploy["CDN deployment workers"]
Indexer["Search and sitemap workers"]
end
Editor -->|"load and edit project"| LB1
Draft -->|"replay pending operations"| LB1
LB1 --> Project
LB1 --> Collab
LB1 --> Media
LB1 --> Publish
Project -->|"read snapshot"| Cache1
Project -->|"persist operations and versions"| DB
Collab -->|"validate and append operations"| DB
Media -->|"upload and serve assets"| Assets
Publish -->|"create publish job"| Jobs
Jobs --> Build
Build -->|"read project and assets"| DB
Build -->|"write immutable site output"| Assets
Build -->|"deployment manifest"| Deploy
Deploy -->|"activate release"| Cache2
Deploy -->|"publish files"| CDN
Jobs --> Indexer
Indexer --> Search
Runtime -->|"site HTML and assets"| CDN
Diagram
3. API design
POST /v1/projects — create a project from a template.
GET /v1/projects/{projectId} — fetch a snapshot and current version.
POST /v1/projects/{projectId}/operations — append editor operations with a base version and idempotency key.
GET /v1/projects/{projectId}/operations?after= — retrieve changes for collaboration or recovery.
POST /v1/projects/{projectId}/assets:upload — create a signed upload URL and asset record.
POST /v1/projects/{projectId}/publish — validate and publish a specified project version.
GET /v1/projects/{projectId}/publish-status/{jobId} — report build and deployment status.
GET /v1/sites/{siteId}/pages/{slug} — serve or resolve a published page through the edge.
4. Data model & storage
Store project metadata and publication state in a relational database: project_id, owner_id, domain, permissions, current version, and active release ID.
Represent a page as a versioned component tree. Nodes have stable IDs, component types, props, style tokens, and child references. Keep page order and reusable symbols explicit.
Persist edits as an append-only operation log and periodically create compact snapshots. Partition by project_id; this makes project loading and version history localized.
Keep uploaded media and immutable published build artifacts in object storage, addressed by content hash. Store metadata, ownership, dimensions, and rights in the database.
Use a CDN for published output and assets, a cache for editor snapshots and release manifests, and a search index for public site discovery. These are derived stores, not sources of truth.
5. Deep dive
The central design challenge is translating a rich editor document into safe, responsive, publishable output while preserving the user's work. I would use a structured document model rather than save arbitrary generated HTML as the source of truth. Each editing action becomes a small operation, such as changing a text node, moving a component, or updating a style token. The editor applies it optimistically for immediate feedback, queues it locally, and sends it with a base version and unique operation ID. The server validates permissions and schema, persists the operation, and acknowledges the resulting version.
For concurrent editing, operations on independent nodes can be applied independently. For conflicting operations, use a defined policy: text editing can use a CRDT or operational transform; structural operations such as deleting a node should win over later edits to that deleted node, with a recoverable undo history. Do not rely on client clocks for ordering. A server-assigned sequence or collaboration protocol establishes canonical order.
Publishing is a separate, versioned pipeline. A publish request pins a project version; workers validate component schemas, resolve assets, generate SEO metadata and responsive output, and write an immutable release. Once all files are available, deployment atomically switches the site's release pointer. A failed build leaves the prior release active. Preview uses the same rendering pipeline but a signed, private URL and draft version.
sequenceDiagram
participant U as Editor
participant A as Project API
participant D as Project store
participant Q as Publish queue
participant B as Build worker
participant O as Object storage
participant C as CDN
U->>A: Append operation with base version and operation ID
A->>D: Validate and persist operation
D-->>A: New canonical version
A-->>U: Acknowledge version
U->>A: Publish pinned version
A->>Q: Enqueue build job
Q->>B: Run validation and rendering
B->>D: Read project snapshot and operations
D-->>B: Pinned project version
B->>O: Write immutable release files
O-->>B: Artifacts ready
B->>C: Atomically activate release manifest
C-->>U: Publish status complete
Diagram
6. Scale, bottlenecks & trade-offs
Serve published pages from a global CDN, with immutable, content-hashed assets and a short-cache or revalidated HTML manifest. Invalidate only the affected site's release pointer; do not purge every asset on each publish.
Keep editor reads and writes separate from public delivery. Autosave should be durable, batched when appropriate, and idempotent. On reconnect, replay queued operations and surface irreconcilable conflicts rather than silently dropping edits.
Shard project data by project ID and use snapshots to bound operation-log replay. Large projects may need limits on node count, asset count, and publish output size to protect build workers.
Use a durable queue for builds, retries with backoff, and a dead-letter queue for invalid or repeatedly failing jobs. Jobs must be idempotent so retrying cannot activate the wrong release.
Isolate published site execution: sanitize user input, enforce a component and plugin permission model, and prevent customer scripts from accessing editor credentials. Apply per-site quotas and abuse detection.
The editor favors low-latency optimistic updates, while canonical saves and permissions are server-authoritative. Collaboration can accept temporary eventual consistency; publish activation and project version selection need clear, atomic semantics. Static generation is fast and cacheable, while dynamic widgets may require isolated server-side or client-side execution and stronger operational controls.
Practice these out loud, don't memorise them
Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.