Christmas sale is live!

Avail Now

Uber 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: Bus Routes (Shortest Path)

Given an array of bus routes where each route is a list of bus stops, find the minimum number of buses you need to take to travel from a source stop to a target stop. This problem tests your understanding of BFS/graph traversal in a complex scenario. You need to model the problem as a graph where each route is a node, and edges exist between routes that share common stops. The key insight is treating routes as nodes rather than stops to optimize the search space.

 

Example: routes = [,], source = 1, target = 6 → Output: 2 (take route 0 to stop 7, then route 1 to stop 6)​

Given a string representing an integer n, return the closest integer (not including itself) which is a palindrome. This challenging problem requires careful handling of edge cases and understanding of number properties. You need to consider multiple candidate palindromes by mirroring the first half, incrementing/decrementing the middle digits, and handling special cases like 999…9 and 100…001. The solution involves string manipulation and comparison logic.

 

Example: Input: “123” → Output: “121” (closest palindrome to 123)

Find the size of the longest non-empty subarray where the absolute difference between any two elements is at most limit. This problem combines sliding window technique with data structures like deque or TreeMap to efficiently track maximum and minimum values in the current window. You maintain two deques to track potential maximum and minimum values, shrinking the window when the difference exceeds the limit.

 

Example: nums =, limit = 4 → Output: 2 (subarray has max diff of 2)​

Given a row-sorted binary matrix where each row is sorted in non-decreasing order, find the index of the leftmost column with at least one 1. The constraint is you can’t read the entire matrix – you must use the provided API efficiently. The optimal solution uses a staircase approach starting from top-right, moving left when you find a 1 or moving down when you find a 0, achieving O(m+n) time complexity.

 

Example: matrix = [,,] → Output: 1​

Given an array of intervals, merge all overlapping intervals and return an array of non-overlapping intervals. First sort the intervals by start time, then iterate through and merge when the current interval’s start is less than or equal to the previous interval’s end. This problem is fundamental for understanding interval manipulation and appears frequently in scheduling and calendar-related problems at Uber.

 

Example: intervals = [,,,] → Output: [,,]​​

Find the kth smallest element in a binary search tree. The most efficient solution uses inorder traversal (left-root-right) which visits BST nodes in sorted order. You can implement this iteratively using a stack or recursively, keeping a counter. For follow-ups, consider modifying the tree structure to store subtree sizes for O(h) queries, or using Morris traversal for O(1) space complexity.

 

Example: For BST [5,3,6,2,4,null,null,1], k=3 → Output: 3

Given a 2D grid of ‘1’s (land) and ‘0’s (water), count the number of islands. An island is surrounded by water and formed by connecting adjacent lands horizontally or vertically. Use DFS or BFS to traverse each island when found, marking visited cells. This problem tests graph traversal skills essential for Uber’s mapping and geographical problems. Can be extended to count island sizes or find the largest island.

 

Example: grid = [[“1″,”1″,”0”],[“1″,”0″,”0”],[“0″,”0″,”1”]] → Output: 2

Given a 2D board of characters and a list of words, find all words that exist in the board formed by sequentially adjacent cells. Use Trie data structure to store all words, then perform DFS from each cell, pruning branches when current prefix doesn’t exist in Trie. This optimization significantly reduces time complexity compared to searching for each word independently, making it efficient for Uber’s autocomplete-like features.

 

Example: board = [[“o”,”a”,”a”,”n”],[“e”,”t”,”a”,”e”],[“i”,”h”,”k”,”r”],[“i”,”f”,”l”,”v”]], words = [“oath”,”pea”,”eat”,”rain”] → Output: [“eat”,”oath”]

You are given equations in the format A / B = k, where A and B are variables and k is a real number. Given queries to find X / Y, return the result or -1 if impossible. Model this as a weighted directed graph where each variable is a node and each equation creates bi-directional edges with weights representing the division results. Use DFS/BFS or Union-Find to answer queries efficiently.

 

Example: equations = [[“a”,”b”],[“b”,”c”]], values = [2.0,3.0], queries = [[“a”,”c”]] → Output: [6.0]

Given a 2D board and a word, determine if the word exists in the grid formed by sequentially adjacent cells (not reusing cells). Implement backtracking DFS, marking cells as visited during recursion and unmarking during backtracking. This is a fundamental backtracking problem that tests your ability to explore all possible paths while maintaining state. Important for Uber’s string matching and search features.

 

Example: board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “ABCCED” → Output: true

Given a 2D matrix representing a grid, construct a quad tree representation. A quad tree is a tree data structure where each internal node has exactly four children representing four quadrants. This problem tests your understanding of recursive tree construction and spatial data structures, crucial for Uber’s map partitioning and geographical indexing systems. Handle both leaf and non-leaf nodes appropriately.

 

Example: grid = [,,,] → Single leaf node with val=True​

Given a string and an integer k, find the length of the longest substring containing the same letter after performing at most k character replacements. Use sliding window technique, tracking the count of the most frequent character in the current window. The window is valid if (window_length – max_frequency) ≤ k. This tests your ability to optimize string problems with constraints.

 

Example: s = “AABABBA”, k = 1 → Output: 4 (replace one B to get “AAAA”)

Given a list of words, return the k most frequent words sorted by frequency (descending) and alphabetically if frequencies are equal. Use HashMap to count frequencies, then use a min-heap of size k or sort with custom comparator. The heap approach gives O(n log k) time complexity. This problem appears in Uber’s search and ranking systems where frequency-based suggestions are needed.

 

Example: words = [“i”,”love”,”leetcode”,”i”,”love”,”coding”], k = 2 → Output: [“i”,”love”]

Find two numbers in an array that add up to a specific target. Use a HashMap to store complements as you iterate through the array, achieving O(n) time complexity. While simple, this problem tests your understanding of hash tables and is often used as a warm-up or screening question. Can be extended to 3-Sum, 4-Sum, or finding all pairs that sum to target.

 

Example: nums =, target = 9 → Output:​

Design a data structure that supports insert, delete, and getRandom operations all in O(1) average time complexity. Use a combination of ArrayList and HashMap – the list stores values for random access, and the map stores value-to-index mappings for O(1) lookup. For deletion, swap the target element with the last element before removing to maintain O(1) time.

 

Example: insert(1) → true, getRandom() → 1, insert(2) → true, getRandom() → randomly 1 or 2

Given an array of words and a max width, format the text such that each line has exactly maxWidth characters and is fully justified (except the last line). Distribute extra spaces as evenly as possible between words. This challenging string manipulation problem tests your ability to handle complex formatting rules and edge cases, relevant for Uber’s text processing and formatting systems.

 

Example: words = [“What”,”must”,”be”,”acknowledgment”], maxWidth = 16 → [“What must be”, “acknowledgment “]

Given a 2D grid with walls (‘W’), enemies (‘E’), and empty spaces (‘0’), find the best position to place a bomb that kills the maximum number of enemies. The bomb kills all enemies in the same row and column until hitting a wall. Use dynamic programming to precompute enemy counts for each direction (up, down, left, right) for optimal O(mn) solution.

 

Example: grid = [[“0″,”E”,”0″,”0″],[“E”,”0″,”W”,”E”],[“0″,”E”,”0″,”0″]] → Output: 3

Given n balloons with different values, burst them to collect maximum coins. When you burst balloon i, you get arr[left]*arr[i]*arr[right] coins. The key insight is to think about which balloon to burst last in a range, not first. Use interval DP where dp[i][j] represents the maximum coins obtainable by bursting balloons between i and j.

 

Example: nums = → Output: 167​

Given an array representing time each bus takes to complete one trip, and a total number of trips needed, find the minimum time required. Use binary search on the answer space – for each candidate time, calculate how many trips can be completed. This problem tests your ability to recognize binary search patterns in optimization problems.

 

Example: time =, totalTrips = 5 → Output: 3​

Find the length of the longest substring without repeating characters. Use sliding window with a HashSet or HashMap to track characters in the current window. When a duplicate is found, shrink the window from the left until the duplicate is removed. This fundamental sliding window problem is frequently asked in Uber interviews for its practical applications in string processing.

 

Example: s = “abcabcbb” → Output: 3 (“abc”)

Given a binary matrix with exactly two islands, find the length of the shortest bridge connecting them. First use DFS/BFS to find one complete island and mark it, then use multi-source BFS from that island to find the shortest path to the second island. This combines graph search techniques and demonstrates understanding of when to use different traversal methods.

 

Example: grid = [,,,,] → Output: 1​

Given a binary matrix, in one move you can flip a cell and its four adjacent cells. Find the minimum number of moves to convert the matrix to all zeros, or return -1 if impossible. Use BFS with state compression, treating each matrix state as a node. This tests your ability to handle state-space search problems efficiently.

 

Example: mat = [,] → Output: 3​

Implement Number of Islands using Union-Find data structure instead of DFS/BFS. Initialize each land cell as its own component, then union adjacent land cells. This approach is particularly useful when you need to dynamically add land cells (Number of Islands II) and track the count of distinct components efficiently.

 

Example: Supports dynamic queries for adding land cells and querying island count

Determine if a given graph with n nodes and edges forms a valid tree. A valid tree must be connected and have exactly n-1 edges with no cycles. Use Union-Find or DFS to check connectivity and cycle detection. This fundamental graph problem tests your understanding of tree properties and is relevant for Uber’s route validation systems.

 

Example: n = 5, edges = [,,,] → Output: true​

Given a sorted dictionary of an alien language, derive the order of characters. Build a directed graph where an edge from character a to b means a comes before b in the alien alphabet. Use topological sort to find the character ordering. Handle edge cases like invalid orderings and cycles, which indicate no valid alphabet exists.

 

Example: words = [“wrt”,”wrf”,”er”,”ett”,”rftt”] → Output: “wertf”

Determine if you can finish all courses given prerequisite pairs. Model as a directed graph and detect cycles using DFS with three states (unvisited, visiting, visited) or use topological sort with Kahn’s algorithm. This problem is fundamental for understanding dependency resolution and appears in various forms in Uber’s scheduling and ordering systems.

 

Example: numCourses = 2, prerequisites = [] → Output: true​

Given a list of accounts where each account has a name and email addresses, merge accounts belonging to the same person. Use Union-Find or DFS to group connected emails. Build a graph where emails are nodes and edges connect emails from the same account. This tests your ability to handle entity resolution problems relevant to Uber’s user account management.

 

Example: accounts = [[“John”,”

john@gmail.com

“,”

john@yahoo.com

“],[“John”,”

john@yahoo.com

“,”

john@outlook.com

“]] → Merged account with all three emails

Given an array of meeting time intervals, find the minimum number of conference rooms required. Sort meetings by start time and use a min-heap to track end times of ongoing meetings. When a new meeting starts, check if any room is free (earliest end time ≤ current start time). This greedy algorithm is crucial for Uber’s resource scheduling systems.

 

Example: intervals = [,,] → Output: 2​​

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water can be trapped after raining. Use two pointers moving from both ends, tracking the maximum height seen from each side. Water trapped at each position is min(left_max, right_max) – current_height. This classic problem tests array manipulation skills.

 

Example: height = → Output: 6​

Implement a basic calculator to evaluate a string expression containing non-negative integers and operators +, -, *, /. Use a stack to handle operator precedence – immediately evaluate * and / when encountered, but push results of + and – to stack for later summation. This tests your ability to parse and evaluate expressions, relevant for Uber’s pricing calculations.

 

Example: s = “3+2*2” → Output: 7

Given a string containing characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘, ‘]’, determine if the input string is valid (every opening bracket has a corresponding closing bracket in correct order). Use a stack to track opening brackets and match them with closing brackets. This fundamental stack problem appears in many variations and tests basic problem-solving skills.

 

Example: s = “()[]{}” → Output: true

Design a data structure that supports get and put operations in O(1) time complexity with a capacity limit. Use a combination of doubly-linked list and HashMap – the map provides O(1) access while the list maintains access order. When capacity is exceeded, remove the least recently used item (tail of the list). This is crucial for Uber’s caching strategies in high-performance systems.

 

Example: LRUCache(2), put(1,1), put(2,2), get(1)=1, put(3,3), get(2)=-1

Design algorithms to serialize a binary tree to a string and deserialize the string back to the original tree structure. Use preorder traversal for serialization, marking null nodes explicitly. For deserialization, parse the string and recursively build the tree. This tests your understanding of tree traversal and string parsing, important for data persistence in Uber’s systems.

 

Example: Tree [1,2,3,null,null,4,5] → “1,2,#,#,3,4,#,#,5,#,#”

Find the contiguous subarray within an array which has the largest sum. Use Kadane’s algorithm – at each position, decide whether to extend the current subarray or start a new one. Track the maximum sum seen so far. This O(n) algorithm is fundamental for understanding dynamic programming and appears in various forms in optimization problems at Uber.

 

Example: nums = [-2,1,-3,4,-1,2,1,-5,4] → Output: 6 (subarray [4,-1,2,1])

Given an array and a sliding window of size k, find the maximum element in each window position. Use a deque to maintain indices of elements in decreasing order of their values. Remove indices outside current window and smaller elements that can never be maximum. This efficient O(n) solution tests your ability to optimize with appropriate data structures.

 

Example: nums = [1,3,-1,-3,5,3,6,7], k = 3 → Output:​

Design a data structure that supports adding integers and finding the median efficiently. Use two heaps – a max heap for the smaller half and a min heap for the larger half, keeping their sizes balanced. The median is either the top of the larger heap or the average of both tops. This demonstrates understanding of heap data structures for streaming data.

 

Example: addNum(1), addNum(2), findMedian()=1.5, addNum(3), findMedian()=2

Given an array, return an array where each element is the product of all other elements except itself, without using division. Compute prefix products from left and suffix products from right in two passes, then multiply them. This O(n) time, O(1) extra space solution (excluding output) tests your ability to optimize array algorithms.

 

Example: nums = → Output:​

Given a list of unique words, find all pairs of distinct indices (i,j) such that the concatenation of words[i] + words[j] is a palindrome. Use a HashMap to store words and their indices. For each word, check all possible splits – if the left part is a palindrome and the reverse of the right part exists in the map, you have a valid pair.

 

Example: words = [“abcd”,”dcba”,”lls”,”s”,”sssll”] → Output: [,,,]​

Given an n x n binary matrix, find the length of the shortest clear path from top-left to bottom-right (8-directional movement). Use BFS with the starting cell, exploring all 8 directions. Mark visited cells to avoid revisiting. This tests your understanding of shortest path algorithms in grid-based problems, relevant for Uber’s route optimization.

 

Example: grid = [,] → Output: 2​

Implement a HashMap from scratch with custom hash function, handling collisions using chaining or open addressing. Support put, get, and remove operations. Consider load factor and implement dynamic resizing when threshold is exceeded. This low-level problem tests your deep understanding of hash table internals, crucial for understanding database indexing and caching.

 

Example: put(1,1), put(2,2), get(1)=1, remove(1), get(1)=-1

Given strings s and t, find the minimum window substring of s that contains all characters from t (including duplicates). Use sliding window with two pointers and frequency maps. Expand window until all characters are included, then shrink from left to find minimum. This challenging problem combines string manipulation with optimization techniques.

 

Example: s = “ADOBECODEBANC”, t = “ABC” → Output: “BANC”

Find the kth largest element in an unsorted array. Use QuickSelect algorithm for average O(n) time or min-heap of size k for O(n log k). The QuickSelect approach uses the partition logic from QuickSort but only recurses on one side. This fundamental selection problem has many real-world applications in Uber’s ranking systems.

 

Example: nums =, k = 2 → Output: 5​

Design a simplified version of Twitter where users can post tweets, follow/unfollow other users, and view their news feed (their tweets + tweets from people they follow in reverse chronological order). Use HashMap to store users and their tweets, and merge k sorted lists when retrieving the feed. This tests OOD skills combined with algorithm knowledge.

 

Example: postTweet(1,5), getNewsFeed(1)=, follow(1,2), postTweet(2,6), getNewsFeed(1)=​

Given two words (begin and end) and a dictionary, find the length of the shortest transformation sequence from begin to end, changing one letter at a time. Use BFS treating each word as a node and words differing by one character as neighbors. This graph problem tests your ability to model word relationships efficiently.

 

Example: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”] → Output: 5

Find the longest palindromic substring in a given string. Use expand around center approach – for each character (and each pair), expand outward while characters match. This gives O(n²) time, O(1) space solution. Alternative approaches include dynamic programming or Manacher’s algorithm for O(n). This tests your understanding of string manipulation and optimization.

 

Example: s = “babad” → Output: “bab” or “aba”

Given n non-negative integers representing heights, find two lines that together with the x-axis form a container with maximum water. Use two pointers starting from both ends, moving the pointer with smaller height inward. The greedy approach works because moving the taller pointer can only decrease the area.

 

Example: height = → Output: 49​

Find the maximum path sum in a binary tree where a path can start and end at any node. Use post-order traversal, computing maximum path sum through each node (considering left path, right path, or both). Track global maximum as you go. This challenging recursion problem tests your understanding of tree traversal and state management.

 

Example: root = → Output: 6 (path 2->1->3)​

Implement a trie data structure supporting insert, search, and startsWith operations. Each node contains an array/map of children and a boolean marking word end. Tries are essential for autocomplete features, spell checkers, and IP routing, all relevant to Uber’s search and navigation systems.

 

Example: insert(“apple”), search(“apple”)=true, search(“app”)=false, startsWith(“app”)=true

Given course prerequisites, return the ordering of courses to finish all courses, or empty array if impossible. Use topological sort with Kahn’s algorithm (BFS with in-degree count) or DFS with post-order traversal. This extends the cycle detection problem to actually produce a valid ordering.

 

Example: numCourses = 4, prerequisites = [,,,] → Output: or​

Determine if a 9×9 Sudoku board is valid (each row, column, and 3×3 sub-box contains digits 1-9 without repetition). Use HashSets to track seen numbers in each row, column, and box. The box index can be calculated as (row/3)*3 + col/3. This tests your ability to handle multiple constraints simultaneously.

 

Example: Valid board with some cells filled according to Sudoku rules → Output: true

Given an array where each element represents maximum jump length from that position, find the minimum number of jumps to reach the last index. Use greedy approach with BFS-like thinking – track the farthest reachable position in current jump and increment jump count when current range is exhausted. This optimization problem tests greedy algorithm skills.

 

Example: nums = → Output: 2 (jump 1 step to index 1, then 3 steps to last)​

Given a reference to a node in a connected undirected graph, return a deep copy of the graph. Use DFS or BFS with a HashMap to map original nodes to their clones, preventing infinite loops in cyclic graphs. This tests your understanding of graph traversal and proper handling of references in data structures.

 

Example: Given node 1 connected to nodes 2,3,4 → Return cloned structure

Given a string of digits, count the number of ways to decode it (where ‘A’=1, ‘B’=2, …, ‘Z’=26). Use dynamic programming where dp[i] represents ways to decode substring up to index i. Consider single digit (1-9) and two digits (10-26) cases. This classic DP problem tests your ability to identify subproblems and build solutions.

 

Example: s = “226” → Output: 3 (can be “BZ”, “VF”, or “BBF”)

Reverse a portion of a linked list from position m to n. Use three-pointer technique to reverse the sublist, carefully handling connections to the parts before and after the reversed section. This tests your linked list manipulation skills and attention to edge cases.

 

Example: head =, m = 2, n = 4 → Output:​

Return the zigzag level order traversal of a binary tree (alternating left-to-right and right-to-left by level). Use BFS with a queue, but reverse the order of nodes at even levels. Alternatively, use two stacks for a more intuitive alternating approach. This tests your ability to modify standard tree traversal algorithms.

 

Example: root = [3,9,20,null,null,15,7] → Output: [,,]​​

Given an array of distinct integers and a target, find all unique combinations that sum to target (same number can be used multiple times). Use backtracking, exploring including/excluding each number. Sort the array first to enable pruning when current sum exceeds target. This fundamental backtracking problem appears in many variations.

 

Example: candidates =, target = 7 → Output: [,]​

Given an integer array of unique elements, return all possible subsets (the power set). Use backtracking or iterative approach where for each element, you either include it or don’t. Total subsets = 2^n. This problem tests your understanding of combinations and is fundamental for understanding subset-based algorithms.

 

Example: nums = → Output: [[],,,,,,,]​

Given an array of distinct integers, return all possible permutations. Use backtracking with a visited array or by swapping elements. At each recursion level, try placing each unused element at the current position. This fundamental problem tests your understanding of permutation generation and backtracking.

 

Example: nums = → Output: [,,,,,]​

Rotate an n x n matrix 90 degrees clockwise in-place. First transpose the matrix (swap matrix[i][j] with matrix[j][i]), then reverse each row. This achieves the rotation without using extra space. Understanding matrix manipulation is crucial for Uber’s image processing and map rotation features.

 

Example: matrix = [,,] → [,,]​​

Given an array of strings, group anagrams together. Use a HashMap where the key is the sorted string or character count array, and value is the list of anagrams. This demonstrates understanding of hashing and string manipulation, relevant for Uber’s text processing and search features.

 

Example: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”] → [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]

Find the cheapest flight from source to destination with at most k stops. Use modified Dijkstra’s algorithm or BFS with priority queue, tracking both cost and number of stops. This variant of shortest path algorithm is directly applicable to Uber’s ride-sharing and route optimization where you want to find optimal paths with constraints.

 

Example: n = 3, flights = [,,], src = 0, dst = 2, k = 1 → Output: 200​

Given a network of n nodes and travel times between nodes, find the time it takes for all nodes to receive a signal from node k. Use Dijkstra’s algorithm to find shortest paths from source to all nodes, then return the maximum time. This tests your understanding of shortest path algorithms in weighted graphs.

 

Example: times = [,,], n = 4, k = 2 → Output: 2​

Given tasks and a cooldown period n, find the minimum time needed to complete all tasks where same task must have n intervals between repetitions. Use greedy approach with max heap or mathematical formula based on the most frequent task. This problem tests scheduling algorithm design relevant for Uber’s driver and ride scheduling.

 

Example: tasks = [“A”,”A”,”A”,”B”,”B”,”B”], n = 2 → Output: 8 (A -> B -> idle -> A -> B -> idle -> A -> B)

Implement an iterator to flatten a nested list structure. Use stack or recursion to handle arbitrary nesting levels. The challenge is to handle the next() and hasNext() operations efficiently, potentially using lazy evaluation. This tests your understanding of iterators and nested data structure traversal.

 

Example: [,2,] → Iterator returns: 1, 1, 2, 1, 1

Given a 2D matrix, calculate the sum of elements inside a rectangle defined by its upper-left and lower-right corners. Precompute prefix sums where dp[i][j] represents sum of rectangle from (0,0) to (i,j). Query answer = dp[row2][col2] – dp[row1-1][col2] – dp[row2][col1-1] + dp[row1-1][col1-1]. This demonstrates understanding of 2D prefix sums for efficient range queries.

 

Example: matrix = [,], sumRegion(2,1,4,3) → Output: 8​

Given a string, convert it to a palindrome by adding characters in front. Find the longest palindromic prefix and add the reverse of the remaining suffix to the front. Use KMP algorithm or rolling hash for efficient solution. This advanced string problem tests your knowledge of string matching algorithms.

 

Example: s = “aacecaaa” → Output: “aaacecaaa”

Find the length of the longest increasing path in a matrix (can move in 4 directions). Use DFS with memoization where dp[i][j] stores the longest path starting from cell (i,j). This combines matrix traversal with dynamic programming, testing your ability to optimize recursive solutions.

 

Example: matrix = [,,] → Output: 4 (path 1→2→6→9)​​

Given coins of different denominations and an amount, find the minimum number of coins needed to make that amount. Use dynamic programming where dp[i] represents minimum coins for amount i. For each amount, try all coins and take minimum. This classic DP problem tests your understanding of optimal substructure.

 

Example: coins =, amount = 11 → Output: 3 (5+5+1)​

Houses are arranged in a circle – you can’t rob adjacent houses or both the first and last house. Split into two subproblems: rob houses 0 to n-2, or rob houses 1 to n-1, then take maximum. This variation of House Robber tests your ability to handle circular constraints.

 

Example: nums = → Output: 3 (can’t rob both ends, rob middle)​

Find the minimum number of operations (insert, delete, replace) to convert one string to another. Use 2D DP where dp[i][j] represents edit distance between first i characters of word1 and first j characters of word2. This fundamental algorithm is used in spell checkers and DNA sequence analysis.

 

Example: word1 = “horse”, word2 = “ros” → Output: 3

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s. Convert to “largest rectangle in histogram” problem for each row, treating each row as the base and computing heights. This combines multiple algorithmic techniques and tests your problem decomposition skills.

 

Example: matrix = [[“1″,”0″,”1″,”0″,”0”],[“1″,”0″,”1″,”1″,”1”],[“1″,”1″,”1″,”1″,”1”]] → Output: 6

Given two strings s and t, count distinct subsequences of s which equals t. Use 2D DP where dp[i][j] represents number of ways to form t[0..j-1] using s[0..i-1]. This challenging DP problem tests your understanding of counting-based dynamic programming.

 

Example: s = “rabbbit”, t = “rabbit” → Output: 3

Given two strings, determine if one is a scrambled version of the other (via recursive scrambling). Use recursive DP with memoization, trying all possible split points. This complex string problem tests your ability to design recursive solutions with proper memoization.

 

Example: s1 = “great”, s2 = “rgeat” → Output: true

For each element in an array, count how many numbers to its right are smaller. Use merge sort with index tracking or Binary Indexed Tree (BIT). During merge sort, count inversions. This advanced problem tests your knowledge of sophisticated data structures.

 

Example: nums = → Output:​

Given envelopes with width and height, find the maximum number you can nest (smaller envelope can fit inside larger if both dimensions are smaller). Sort by width ascending and height descending, then find longest increasing subsequence on heights. This combines sorting with LIS algorithm cleverly.

 

Example: envelopes = [,,,] → Output: 3​

Q1. Design Twitter / Social Media Feed System

Create a simplified Twitter supporting posting tweets, following users, and viewing personalized news feeds. Implement User class with userId and set of followees, Tweet class with tweetId, userId, and timestamp. Use HashMap<userId, User> for user storage and HashMap<userId, List<Tweet>> for tweets. For news feed, merge multiple sorted lists (tweets from user and followees) using priority queue. Support follow/unfollow operations with O(1) complexity. Consider privacy settings, blocked users, and muting functionality for real-world scenarios.

Implement a multi-level parking lot with different vehicle types (motorcycle, car, bus). Create Vehicle abstract class with subclasses for each type. ParkingSpot class contains spotId, vehicle type, and availability. ParkingLevel has list of spots. ParkingLot manages multiple levels. Implement findParkingSpot() using strategy pattern for different vehicle sizes. Track occupied spots per level. Add payment system with hourly rates. Support handicapped spots, VIP spots, and different pricing tiers. Implement notification system for full parking levels.

 

Implement token bucket or sliding window rate limiter to prevent API abuse. For token bucket: maintain tokens counter and last refill timestamp per user. Refill tokens based on elapsed time. For sliding window: store request timestamps in queue per user, remove old timestamps beyond window. Support different rate limits per user tier (free, premium, enterprise). Implement distributed rate limiting using Redis with atomic operations. Handle race conditions with proper synchronization. Support multiple rate limit rules (per second, per minute, per hour).

Implement Least Recently Used cache with O(1) get and put operations. Use doubly-linked list to maintain access order (most recent at head, least recent at tail) and HashMap for O(1) access. On get: move accessed node to head. On put: add to head, remove tail if capacity exceeded. Implement proper node removal and insertion. Consider thread-safety with ReentrantLock. Add eviction policies (LRU, LFU, FIFO). Support time-based expiration and size-based eviction. Implement cache statistics (hit rate, miss rate).

Implement HashMap with custom hash function, collision resolution via chaining or open addressing. Internal array of buckets (linked lists or binary trees). Hash function uses modulo of array size. On put: compute hash, handle collisions. On get: compute hash, search bucket. Implement dynamic resizing when load factor exceeds 0.75. Rehash all entries during resize. Handle null keys specially. Support remove operation. Optimize bucket structure using balanced trees for high collision chains. Implement equals() and hashCode() properly.

Create system to shorten URLs and redirect to originals. Generate unique IDs using base62 encoding (a-z, A-Z, 0-9) giving 62^7 ≈ 3.5 trillion combinations for 7-character IDs. Store mapping in database (key: shortURL, value: longURL). On shorten: generate ID, check for collisions, store mapping. On redirect: lookup longURL, perform 301/302 redirect. Add expiration dates, custom aliases, analytics tracking (click counts, referrers, locations). Implement ID generation strategies (counter with base62 conversion, random generation with collision handling, hash-based approach).

Implement elevator control system for a building. Create Elevator class with currentFloor, direction (UP/DOWN/IDLE), set of destinationFloors. ElevatorController manages multiple elevators. Request class has floor and direction. Implement scheduling algorithms: SCAN (elevator continues in same direction until no more requests), LOOK (reverses at extremes of requests), or nearest car heuristic. Handle emergencies, maintenance mode, and VIP requests. Optimize for wait time minimization and energy efficiency. Support different building configurations (residential, commercial, high-rise).

Create classes for User, Book, Order, ShoppingCart, Inventory, Payment. Book has ISBN, title, author, price, quantity. ShoppingCart contains items and quantities. Order has orderId, userId, items, totalAmount, status. Implement addToCart(), removeFromCart(), checkout(), processPayment(). Inventory management with stock updates. Use Observer pattern for low stock alerts. Implement different payment methods via Strategy pattern. Add order history, wishlists, reviews and ratings. Support discounts, coupons, and promotional pricing. Handle concurrent purchases with proper locking.

Implement chess game with proper OOP. Create abstract Piece class with subclasses (King, Queen, Rook, Bishop, Knight, Pawn). Board class with 8×8 grid. Move class represents a move with source and destination. Implement isValidMove() for each piece type following chess rules. Game class manages turns, checks for checkmate/stalemate. Player class represents each player. Support special moves (castling, en passant, pawn promotion). Implement move validation, check detection, and game state persistence. Add move history and undo functionality.

Create Theater class with multiple Screens, each having Seats arranged in rows. Show class links Movie with Screen and timing. Booking class has showId, seats, userId, status. Implement searchMovies(), getAvailableShows(), bookSeats() with seat locking during booking process. Use optimistic locking or database transactions for seat reservation. Payment integration with timeout handling. Support different seat categories (regular, premium, VIP) with dynamic pricing. Add cancellation with refund policy. Implement waiting list for sold-out shows.

Create Board class with 100 cells, snakes (head→tail mapping), ladders (bottom→top mapping). Player class has position. Game class manages player turns and dice rolls. Implement rollDice(), movePlayer(), checkSnakeOrLadder(), checkWinner(). Support multiple players with turn rotation. Add game configurations (board size, number of snakes/ladders). Implement game save/resume functionality. Track statistics (number of turns, ladder climbs, snake bites). Support different game modes (timed, versus computer).

Create Table class with tableId, capacity, status (available/occupied). Order class with orderId, tableId, items, status (pending/preparing/served). Menu class with dishes and prices. Waiter class manages assigned tables. Kitchen class processes orders. Implement reserveTable(), placeOrder(), prepareOrder(), generateBill(). Queue management for waiting customers. Inventory tracking for ingredients. Support split bills, tips, and different payment methods. Add table merging for large groups. Implement waitlist management and table turn optimization.

Create Board class with 3×3 grid. Player class with symbol (X/O). Game class manages turns and win detection. Implement makeMove(row, col), checkWinner() (check rows, columns, diagonals), isBoardFull() for draw. Support N×N board generalization. Add AI opponent with minimax algorithm for optimal play. Implement difficulty levels (easy random, medium, hard optimal). Support multiplayer mode. Add game history and replay functionality. Handle invalid moves gracefully.

Implement in-memory file system with files and directories. Entry abstract class with File and Directory subclasses. Directory contains map of entries (name→Entry). Implement mkdir(), touch(), ls(), cd(), find(), rm() commands. Support absolute and relative paths. Handle permissions (read, write, execute). Implement file metadata (size, creation time, modification time, owner). Support symbolic links. Add file search with pattern matching. Implement copy and move operations with recursive handling for directories.

Create Book class with ISBN, title, author, copies. Member class with memberId, borrowedBooks, fines. Librarian class inherits from Member with additional privileges. LibrarySystem manages books and members. Implement searchBook(), issueBook(), returnBook(), calculateFine(). Track book availability and reservations. Support multiple copies of same book. Implement due date tracking with automated fine calculation. Add book categories and search by multiple criteria. Support renewal and reservation queue for popular books. Handle lost or damaged books.

Create Room class with roomId, type (single/double/suite), price, status. Guest class with guestId, name, contact. Booking class with bookingId, rooms, guest, checkIn/checkOut dates. Hotel class manages rooms and bookings. Implement searchAvailableRooms(), makeBooking(), checkIn(), checkOut(), calculateBill(). Support room service orders, housekeeping schedules, and maintenance tracking. Implement seasonal pricing and discounts. Add loyalty program with points. Handle overbooking situations. Support partial payments and advance bookings.

Create Account class with accountNumber, balance, PIN. Transaction class with transactionId, type (withdraw/deposit/transfer), amount. ATM class with cash inventory (denomination-wise). Implement authenticateUser(), checkBalance(), withdraw(), deposit(), changePIN(). Handle insufficient funds and invalid PIN with retry limits. Optimize cash dispensing using minimum number of notes. Support mini-statement printing. Implement proper security with PIN encryption. Handle network failures gracefully. Track daily withdrawal limits and transaction history.

Create Logger interface with methods log(level, message). LogLevel enum (DEBUG, INFO, WARN, ERROR). Implement different appenders: FileAppender, ConsoleAppender, DatabaseAppender. LogFormatter for message formatting. Support multiple log levels with filtering. Implement async logging using queue for performance. Add log rotation based on file size or time. Support structured logging with key-value pairs. Implement different log formats (JSON, XML, plain text). Add distributed tracing with correlation IDs. Handle logging in multi-threaded environment safely.

Create Notification abstract class with EmailNotification, SMSNotification, PushNotification subclasses. User has notification preferences. NotificationService manages sending. Implement send(), retry on failure, rate limiting per user. Support notification templates with variables. Queue notifications for batch processing. Implement delivery tracking and read receipts. Add priority levels (high, medium, low). Support scheduled notifications. Handle user opt-out and do-not-disturb settings. Implement notification aggregation to prevent spam.

Create Product class with name, price, quantity. Coin enum for different denominations. VendingMachine has inventory and current transaction state. State pattern for machine states (Idle, HasMoney, Dispensing). Implement insertCoin(), selectProduct(), dispense(), returnChange(). Calculate optimal change using greedy algorithm. Handle sold-out products and insufficient funds. Support multiple payment methods (cash, card). Implement restocking functionality. Add sales reporting and inventory management. Handle coin/note acceptance and validation.

Create Event class with title, startTime, endTime, attendees. Calendar class manages events for a user. Implement addEvent(), findConflicts(), findAvailableSlots(). Support recurring events (daily, weekly, monthly) using Strategy pattern. Implement reminder system with multiple notification types. Handle timezone conversions for global teams. Support event invitations with accept/decline responses. Find common free time slots among multiple participants. Add calendar sharing with different permission levels. Implement event search and filtering.

Create Song class with songId, title, artist, album, duration. Playlist class contains list of songs. User class has playlists, listening history, subscriptions. Implement play(), pause(), skip(), createPlaylist(), addToPlaylist(). Use Observer pattern for real-time lyrics sync and collaborative playlists. Implement recommendation engine based on listening history using collaborative filtering. Support offline downloads with DRM. Add shuffle and repeat modes. Track playback statistics for artists. Implement queue management with next up functionality. Support multiple audio quality levels based on subscription tier.

Create Rider and Driver classes extending User. Trip class with source, destination, fare, status. Location class with latitude, longitude. Implement requestRide(), acceptRide(), startTrip(), completeTrip(), calculateFare(). Use Strategy pattern for different fare calculation algorithms (base fare + distance + time, surge pricing). Implement driver matching algorithm based on proximity using geohashing or quadtree. Support ride sharing and carpooling. Add rating system for drivers and riders. Implement real-time location tracking. Handle cancellations with penalty logic. Support multiple ride types (economy, premium, XL).

Create Job class with jobId, priority, execution time, dependencies. Scheduler manages job queue using priority queue. Implement scheduleJob(), executeJob(), cancelJob(). Support cron-like scheduling with recurring jobs. Handle job dependencies using DAG (Directed Acyclic Graph). Implement retry mechanism with exponential backoff for failed jobs. Support distributed scheduling across multiple worker nodes. Add job monitoring and alerting for failures. Implement different scheduling strategies (FIFO, priority-based, deadline-based). Handle resource constraints and load balancing. Support job chaining and workflows.

Create Problem class with description, test cases, constraints. Submission class with code, language, result. CodeExecutor runs code in sandboxed environment. Implement submitCode(), runTestCases(), getResults(). Support multiple programming languages using Strategy pattern. Implement syntax highlighting and autocomplete. Add collaborative editing with WebSocket for real-time updates using Operational Transformation. Execute code in Docker containers for isolation. Implement timeout handling and resource limits (CPU, memory). Support custom input testing. Add code version history and diff viewing. Implement plagiarism detection.

Create TrieNode class for prefix tree structure. AutocompleteSystem maintains trie and frequency map. Implement input(char), getTop3() to return top 3 suggestions. Store frequency of each search term. On input, traverse trie to current prefix, perform DFS to collect all completions, sort by frequency. Optimize with pruning and caching. Support fuzzy matching for typos using edit distance. Implement personalized suggestions based on user history. Add trending searches using time-decay algorithm. Support multi-language autocomplete. Handle special characters and phrases. Implement real-time suggestion updates.

Create Order class with orderId, symbol, type (buy/sell), price, quantity, timestamp. OrderBook maintains buy and sell orders using two priority queues (max heap for buy, min heap for sell). Implement placeOrder(), cancelOrder(), matchOrders(). Match orders when buy price ≥ sell price. Execute at best available price. Support different order types (market, limit, stop-loss). Handle partial order fulfillment. Implement fair queuing (FIFO at same price level). Add circuit breakers for extreme volatility. Support multiple exchanges and cross-listing. Implement real-time order book depth visualization.

Create Comment class with commentId, userId, text, timestamp, parentCommentId, replies list. Implement postComment(), editComment(), deleteComment(), getCommentThread(). Store comments hierarchically allowing infinite nesting. Implement pagination for large threads. Support voting/likes on comments. Add moderation features (report, hide, delete). Implement mention system with notifications. Support markdown formatting. Add threaded view and chronological view options. Implement comment search and filtering. Handle deleted comments gracefully (show [deleted] placeholder). Support real-time updates for new comments.

Create URL class with url, status, retry count. Crawler maintains queue of URLs to crawl and visited set. Implement crawl(), extractLinks(), storeContent(). Use BFS for breadth-first crawling or DFS for depth-first. Implement robots.txt compliance and rate limiting per domain. Handle different content types (HTML, PDF, images). Implement distributed crawling across multiple machines with coordination. Add duplicate detection using URL normalization and content hashing. Support incremental crawling (only fetch changed pages). Implement politeness delays and user-agent rotation. Handle redirects and different status codes properly.

Create Server class representing origin and edge servers. Content class with contentId, url, data. CacheNode implements LRU/LFU caching strategy. Implement getContent() with geographic routing to nearest edge server. Use consistent hashing for content distribution across servers. Implement cache invalidation strategies (TTL, manual purge). Support content replication with configurable replication factor. Add health checks and automatic failover. Implement bandwidth throttling and QoS policies. Support SSL/TLS termination at edge. Add analytics for cache hit rates and traffic patterns. Implement origin shield to protect origin servers.

Create Topic class with subscribers list. Message class with messageId, topic, content, timestamp. Publisher publishes to topics, Subscribers consume messages. Implement publish(), subscribe(), unsubscribe(), poll(). Support message filtering with predicates. Implement message retention with TTL. Add delivery guarantees (at-most-once, at-least-once, exactly-once). Support message ordering within partitions. Implement dead letter queues for failed messages. Add consumer groups for load distribution. Support message replay from specific offset. Implement backpressure handling. Add message compression and batching for efficiency.

Create Metric class with name, value, timestamp, tags. MetricsCollector aggregates metrics. Implement recordMetric(), query(startTime, endTime, aggregation). Support different metric types (counter, gauge, histogram, timer). Implement time-series data storage with bucketing. Support aggregation functions (sum, avg, min, max, percentiles). Add dimensional metrics with tag-based filtering. Implement downsampling for long-term storage. Support alerting based on metric thresholds. Add dashboard visualization with real-time updates. Implement data retention policies. Support distributed collection across multiple services.

Create Product class with productId, name, price, inventory. CartItem contains product and quantity. ShoppingCart maintains map of items. User has cart, order history, wishlist. Implement addItem(), removeItem(), updateQuantity(), calculateTotal(), checkout(). Handle concurrent modifications with optimistic locking. Implement cart persistence (saved cart). Support guest checkout. Add coupon code validation and discount calculation. Implement inventory reservation during checkout. Support cart sharing and gift registry. Add abandoned cart recovery with email reminders. Implement maximum quantity limits per item. Handle out-of-stock scenarios gracefully.

Create Road class with direction. Signal class with currentState (RED/YELLOW/GREEN), timer. TrafficController manages multiple signals. Implement changeSignal(), handleEmergencyVehicle(). Use State pattern for signal state transitions. Implement fixed-time and adaptive timing based on traffic density. Support pedestrian crossing signals. Add emergency vehicle detection with priority signal changes. Implement coordination between adjacent intersections for green waves. Support manual override for traffic management. Add countdown timers for driver convenience. Implement rush hour vs off-peak timing adjustments. Handle power failures with fallback to flashing mode.

Create Card class with suit and rank. Deck class with shuffle(), deal(). Hand class evaluates card combinations. Player class tracks chips/money. Game class manages game flow. For Poker: implement evaluateHand() to determine hand rank (royal flush, straight, etc.). For Blackjack: implement hit(), stand(), calculateScore() with Ace handling (1 or 11). Support multiple players and betting rounds. Implement different game variants. Add dealer AI with strategy. Support side bets and insurance. Track game statistics and player winnings. Implement anti-cheating measures like deck tracking prevention.

Create Lock class with lockId, holder, expirationTime. LockManager provides acquire() and release() operations. Implement using database (pessimistic locking), Redis (SETNX with TTL), or ZooKeeper (ephemeral nodes). Handle lock expiration to prevent deadlocks from crashed holders. Implement reentrant locks allowing same holder to acquire multiple times. Support try-lock with timeout. Add fair queuing for lock requests. Implement lock monitoring and metrics. Handle split-brain scenarios in distributed environment. Support read-write locks for concurrent reads. Implement lock lease renewal for long operations.

Create Problem class with test cases, constraints, difficulty. Solution class with code, language, verdict. Judge class compiles and executes code. Implement submit(), judge(), getVerdict(). Execute in sandboxed containers with resource limits. Support multiple languages with different time/memory limits. Implement test case evaluation with stdin/stdout comparison. Handle special judge for problems with multiple correct answers. Support partial scoring for optimization problems. Implement plagiarism detection using code similarity algorithms. Add contest mode with leaderboards and penalty calculations. Support custom checkers and interactive problems. Implement submission queue with priority processing.

Create Restaurant class with menu, location, ratings. Customer and DeliveryAgent classes. Order class with items, status, delivery address. Implement placeOrder(), assignDeliveryAgent(), trackOrder(), completeDelivery(). Use matching algorithm to assign orders to nearby available agents. Implement dynamic pricing based on distance, time, demand. Support scheduling for later delivery. Add real-time tracking with ETA calculation. Implement rating system for restaurants and agents. Support group orders and split payments. Add dietary preferences and allergy filters. Implement restaurant queue management during peak hours. Handle order modifications and cancellations with proper refund logic.

Create CacheNode representing individual cache servers. CacheCluster manages multiple nodes. Implement get(), put(), delete() with consistent hashing for key distribution. Support replication for fault tolerance with configurable replication factor. Implement cache coherence protocols for updates. Add read-through and write-through caching strategies. Support cache warming with preloading. Implement eviction policies (LRU, LFU, TTL-based). Add cache statistics (hit rate, latency). Handle node failures with automatic rebalancing. Support cache invalidation patterns. I

Create MeetingRoom class with roomId, capacity, facilities (projector, whiteboard). Booking class with roomId, userId, start time, end time. System class manages rooms and bookings. Implement searchAvailableRooms(), bookRoom(), cancelBooking(), checkConflicts(). Use interval tree for efficient conflict detection. Support recurring bookings (daily, weekly, monthly). Implement waiting list for popular rooms. Add room suggestions based on meeting size and required facilities. Support buffer time between meetings for cleanup. Implement automated cancellation for no-shows. Add integration with calendar systems (Google Calendar, Outlook). Support desk hoteling and workspace reservation.

Create User class with profile, interaction history. Item class with features, categories. Recommendation Engine generates suggestions. Implement collaborative filtering (user-based, item-based), content-based filtering, and hybrid approaches. Use matrix factorization for latent factor models. Implement real-time recommendations using online learning. Support A/B testing for different recommendation strategies. Add diversity and serendipity to avoid filter bubbles. Implement cold start solutions for new users/items. Track recommendation effectiveness with click-through rates. Support contextual recommendations based on time, location, device. Implement explanation generation for recommendations. Add privacy-preserving techniques for sensitive data.

Create Item class with itemId, description, starting price, end time. Bid class with bidId, bidderId, amount, timestamp. Auction maintains current highest bid. Implement placeBid(), getHighestBid(), closeAuction(). Support different auction types (English, Dutch, sealed-bid). Implement automatic bidding with maximum bid limits (proxy bidding). Add bid increment rules and reserve price. Handle last-minute bidding with time extensions (anti-sniping). Support buy-it-now option. Implement fraud detection for suspicious bidding patterns. Add notification system for outbid alerts. Support auction cancellation and relisting. Implement escrow payment system for security.

Create Commit class with commitId, parent, changes, message, author, timestamp. Repository maintains commit history as DAG. Implement commit(), branch(), merge(), diff(). Store file snapshots or deltas efficiently. Implement merge conflict detection and resolution. Support branching strategies (feature branches, git-flow). Add tagging for releases. Implement distributed architecture allowing offline work. Support cherry-pick and rebase operations. Add blame functionality to track line-by-line authors. Implement garbage collection for unreachable commits. Support hooks for pre-commit and post-commit actions. Add LFS support for large files.

Create Canvas class representing drawing surface. Shape classes (Line, Rectangle, Circle, Text) with position, color, size. User has cursor position and drawing tool. Implement draw(), erase(), undo(), redo(). Use WebSocket for real-time synchronization. Implement Operational Transformation or CRDT for conflict-free concurrent editing. Support layers and Z-ordering of shapes. Add selection and grouping of multiple shapes. Implement collaborative cursor showing other users’ positions. Support infinite canvas with pan and zoom. Add drawing tools (pen, highlighter, shapes, text). Implement permissions (view-only, edit). Support export to PDF/image formats. Add version history with playback.

Create Video class with videoId, title, URL, resolutions, duration. User has watch history, preferences, subscription. Implement play(), pause(), seek(), changeQuality(). Use adaptive bitrate streaming (HLS/DASH) based on network conditions. Implement CDN integration for efficient content delivery. Support video encoding in multiple resolutions (480p, 720p, 1080p, 4K). Add resume watching from last position. Implement recommendation engine for similar videos. Support subtitles/closed captions with multiple languages. Add download for offline viewing with DRM. Implement concurrent stream limits per account. Support live streaming with low latency. Add video analytics (watch time, drop-off points). Implement content categorization and search.

Create Block class with index, timestamp, transactions, previousHash, nonce, hash. Blockchain maintains chain of blocks. Transaction class with sender, receiver, amount, signature. Implement addTransaction(), mineBlock(), isChainValid(). Use proof-of-work (finding hash with leading zeros) or proof-of-stake consensus. Implement digital signatures using public-key cryptography. Support wallet creation and management. Add transaction pool (mempool) for pending transactions. Implement block propagation in P2P network. Handle chain forks with longest chain rule. Support smart contracts with Turing-complete scripting. Add merkle trees for efficient verification. Implement UTXO or account-based model.

Create Candidate class with candidateId, name, party. Voter class with voterId, hasVoted flag. Vote class (encrypted/anonymized). VotingSystem manages election. Implement authenticate(), castVote(), countVotes(), getResults(). Use cryptographic techniques for vote anonymity while preventing double voting. Implement blockchain for tamper-proof vote recording. Support multiple voting methods (plurality, ranked-choice, approval voting). Add voter verification with digital signatures. Implement real-time result tallying with security against premature disclosure. Support absentee and mail-in voting with verification. Add audit logs for transparency. Handle recounts and vote verification. Implement accessibility features for disabled voters.

Create Message class with messageId, senderId, receiverId, content, timestamp, status (sent/delivered/read). Conversation class maintains message history. Implement sendMessage(), receiveMessage(), markAsRead(), deleteMessage(). Use WebSocket for real-time message delivery. Support one-on-one and group chats. Implement end-to-end encryption using Signal Protocol or similar. Add message persistence with pagination for history. Support multimedia messages (images, videos, files). Implement typing indicatorsand presence information. Support group admin features. Implement message search and filtering. Add voice and video calling. Support message reactions and replies. Implement message expiration for ephemeral chats.

Create RateLimitRule class with limit, window duration, scope (user/IP/API key). Gateway intercepts all requests. Implement checkRateLimit(), incrementCounter(). Use sliding window log or token bucket algorithm. Support multiple rate limit tiers (free: 100/hour, premium: 1000/hour). Implement distributed rate limiting with Redis. Add burst allowance for temporary spikes. Support different limits for different endpoints. Implement graceful degradation with 429 status codes and retry-after headers. Add rate limit exemptions for certain users/IPs. Implement analytics dashboard for API usage patterns. Support dynamic rate limit adjustment based on system load.

Create Zone class representing geographical areas. Demand class tracks riders and drivers per zone. PricingEngine calculates fares. Implement calculateFare() using base fare + distance × per-km rate + time × per-minute rate + surge multiplier. Surge multiplier increases with demand/supply ratio. Use geohashing for zone definition. Implement real-time demand tracking. Support different vehicle categories with different base rates. Add time-based pricing (peak hours, late night). Implement predictive surge pricing using ML models. Support promotional discounts and coupon codes. Add transparent pricing with upfront fare estimates. Implement fare caps and minimum guarantees for drivers.

Create Board class containing lists. List class contains cards. Card class has title, description, assignee, labels, due date, attachments, checklist. Implement createCard(), moveCard(), updateCard(), addComment(). Support drag-and-drop reordering. Use Observer pattern for real-time updates to multiple users. Implement access control (board admin, members, viewers). Add activity log tracking all changes. Support card templates and recurring tasks. Implement dependencies between tasks. Add time tracking and estimation. Support multiple views (kanban, list, calendar, timeline). Implement search and filtering with complex queries. Add email integration for creating cards from emails.

Create Product class with SKU, name, quantity, reorder level, supplier. Warehouse class manages inventory by location. Transaction class tracks stock movements (IN/OUT). Implement addStock(), removeStock(), checkAvailability(), generateReorderReport(). Support multi-warehouse inventory with transfer between locations. Implement FIFO/LIFO/FEFO stock rotation policies. Add batch and lot tracking for pharmaceuticals. Support serial number tracking for electronics. Implement barcode/RFID scanning integration. Add automated reorder when stock falls below threshold. Support inventory forecasting based on sales trends. Implement cycle counting and stocktake features. Add inventory valuation methods (weighted average, FIFO).

Create Server class with IP, port, health status, current connections. LoadBalancer distributes requests across servers. Implement different algorithms: Round Robin (cycle through servers), Least Connections (send to server with fewest connections), IP Hash (consistent routing based on client IP), Weighted Round Robin (assign weights to servers). Support health checks with automatic server removal on failure. Implement session persistence (sticky sessions) using cookies. Add SSL termination and HTTP/2 support. Support active-passive and active-active configurations. Implement rate limiting per client. Add request queuing during overload. Support dynamic server addition/removal. Implement metrics collection (requests per second, latency, error rates).

Create Event class with eventId, name, venue, datetime, capacity. Seat class with seatId, section, row, price, status. Ticket class links seat to purchase. Implement searchEvents(), selectSeats(), bookTickets(), processPayment(). Use optimistic locking or database transactions for concurrent seat selection. Implement seat hold mechanism (reserve for 10 minutes during checkout). Support different ticket types (general admission, reserved seating, VIP). Add dynamic pricing based on demand and time to event. Implement waitlist for sold-out events. Support season tickets and group bookings. Add ticket transfer and resale with verification. Implement digital tickets with QR codes. Support different delivery methods (e-ticket, mobile, physical).

Create Player class with playerId, position, health, inventory. GameRoom class manages players in a match. GameState synchronizes across clients. Implement joinRoom(), leaveRoom(), updatePlayerState(), handleAction(). Use authoritative server architecture to prevent cheating. Implement lag compensation and client-side prediction. Support matchmaking based on skill rating (ELO, MMR). Add lobby system for pre-game setup. Implement spectator mode. Support different game modes and maps. Add anti-cheat detection systems. Implement voice chat integration. Support tournaments and leaderboards. Add replay system for match recording. Implement graceful handling of disconnections with reconnection ability.

Create Customer class with billing information. Invoice class with invoiceId, items, amount, tax, status, due date. Payment class tracks payment transactions. Implement generateInvoice(), sendInvoice(), recordPayment(), handleOverdue(). Support multiple payment methods (credit card, bank transfer, digital wallets). Implement recurring billing for subscriptions with automatic charge. Add dunning management for failed payments with retry logic. Support partial payments and payment plans. Implement tax calculation for different jurisdictions. Add credit notes and refunds. Support multi-currency billing with exchange rate handling. Generate PDF invoices with company branding. Implement payment reminders and late fees. Add integration with accounting software (QuickBooks, Xero).

Create Question class with questionId, title, body, tags, votes, views. Answer class with answerId, questionId, body, votes, accepted flag. User has reputation points. Implement askQuestion(), answerQuestion(), vote(), acceptAnswer(). Calculate user reputation based on votes and accepted answers. Support editing with revision history. Implement commenting on questions and answers. Add moderation features (flag, close, delete). Support tags for categorization with synonyms. Implement search with ranking (votes, relevance, recency). Add badges and gamification. Support markdown formatting and syntax highlighting for code. Implement duplicate question detection. Add user following and notifications. Support bounties for questions.

Create User class with userId, name, balance with each other user. Expense class with amount, paidBy, splitAmong, category, date. Group class for trips or shared living. Implement addExpense(), settleUp(), simplifyDebts(), getBalance(). Calculate net balance between users using graph algorithms. Implement debt simplification (minimize number of transactions needed to settle). Support different split types (equal, by shares, by percentage, exact amounts). Add expense categories and spending analytics. Support multiple currencies with conversion. Implement recurring expenses for regular bills. Add receipt photo upload and OCR. Support group expenses with unequal splits. Generate expense reports and summaries. Implement payment integrations for direct settlement.

Create NotificationType enum (email, SMS, push, in-app). NotificationPreference class per user per type per category. Implement setPreference(), canSendNotification(), getChannels(). Support fine-grained control (new-follower, like, comment, weekly-digest). Implement quiet hours per user. Support batching and digesting of notifications. Add frequency capping (max per day). Implement notification templates with personalization. Support A/B testing of notification content. Add delivery tracking (sent, delivered, opened, clicked). Implement smart delivery timing based on user engagement patterns. Support channel failover (if email fails, try push). Add compliance with do-not-disturb and unsubscribe regulations.

Create Product class with limited quantity. Sale class with startTime, endTime, discountPercentage. Implement notifyUsers(), handlePurchase(), preventOverselling(). Use Redis atomic operations or database transactions for inventory management. Implement queue system to handle traffic spikes. Add virtual waiting room during high demand. Use cache for product information to reduce database load. Implement bot detection and prevention. Support purchase limits per user. Add countdown timers for sale urgency. Implement automatic cancellation of unpaid orders after timeout. Use CDN for static content. Implement gradual rollout across regions. Add load testing and auto-scaling preparation. Support flash sale analytics (conversion rate, time to sell out).

Q1. Design Uber (Ride-Sharing Service)

Requirements: Real-time ride matching, ETA calculation, fare estimation, driver tracking, payment processing. Components: Client apps (rider/driver), API Gateway, Ride Matching Service, Location Service, Payment Service, Notification Service, Analytics. Use geo-spatial indexing (geohashing, quadtree, or S2 cells) to efficiently find nearby drivers. WebSocket for real-time location updates. Implement surge pricing based on demand-supply ratio using dynamic pricing service. Store ride history in SQL database, cache hot data in Redis. Use message queue (Kafka) for async processing of payments and notifications. Implement load balancing across multiple regions. Handle millions of concurrent rides with horizontal scaling. Use CDN for map tiles and static content.

Requirements: Video upload/encoding, storage, streaming, search, recommendations, user profiles. Components: Upload Service, Transcoding Pipeline (FFmpeg), Content Delivery Network, Streaming Service (HLS/DASH), Metadata Service, Recommendation Engine, User Service. Store original videos in object storage (S3), transcode to multiple resolutions (360p, 720p, 1080p, 4K). Use CDN (CloudFront, Akamai) with edge caching for low-latency streaming. Implement adaptive bitrate streaming based on network conditions. Store metadata in NoSQL (Cassandra) for fast reads. Build recommendation system using collaborative filtering and ML models. Use distributed cache for user sessions. Handle 200M+ concurrent streams globally. Implement content pre-positioning based on predicted popularity.

 

Requirements: One-to-one messaging, group chats, media sharing, end-to-end encryption, online status, last seen. Components: WebSocket servers for real-time messaging, Message Queue (Kafka) for reliable delivery, Key-Value Store (Cassandra/HBase) for message storage, Media Service for file uploads, Presence Service for online status. Implement end-to-end encryption using Signal Protocol. Use consistent hashing for chat routing. Store messages with TTL in NoSQL database. Implement message acknowledgments (sent/delivered/read) using ACK protocol. Use compression for media files. Support offline message queue with push notifications. Handle 100B+ messages per d

Requirements: Photo/video upload, feed generation, following/followers, likes, comments, stories. Components: Upload Service, Image Processing (resize, filters), Object Storage (S3), Feed Generation Service, Graph Database (Neo4j) for social connections, Timeline Service, Notification Service. Implement news feed with fanout-on-write for users with few followers, fanout-on-read for celebrities. Use CDN for image delivery with multiple resolutions. Store user graph in graph database for efficient follower queries. Implement stories with 24-hour TTL in Redis. Use Cassandra for timeline storage with user_id as partition key. Handle 500M+ daily active users. Implement like counts with counter service for high write throughput.

Requirements: Tweet posting, timeline, following, retweets, trending topics, search. Components: Tweet Service, Timeline Service (home/user), Graph Service for relationships, Search Service (Elasticsearch), Trending Service, Media Service. Implement hybrid push-pull model for timeline generation – push to active users, pull for inactive. Use Lucene/Elasticsearch for full-text search. Calculate trending topics using Count-Min Sketch for memory efficiency. Store tweets in Cassandra with composite key (user_id, timestamp). Use Redis for timeline cache. Implement rate limiting (300 tweets/3 hours). Handle 6000 tweets/second with horizontal scaling. Support hashtag and mention indexing for fast lookup.

Requirements: Shorten long URLs, redirect to original, custom aliases, analytics. Components: URL Service, Redirect Service, Analytics Service, Database (SQL/NoSQL). Generate unique IDs using base62 encoding (a-z, A-Z, 0-9) giving 62^7 combinations. Use counter-based approach with sharding or snowflake ID generation. Store mapping in SQL with index on short URL. Use Redis cache for hot URLs (80-20 rule). Implement 301 (permanent) vs 302 (temporary) redirects. Track click analytics (timestamp, location, referrer) in time-series database. Handle 100M URLs with billions of redirects. Support custom aliases with uniqueness check. Implement expiration dates and cleanup job. Use CDN for redirect service globally.

Requirements: Video upload, streaming, search, comments, subscriptions, recommendations. Components: Upload Service, Transcoding Pipeline, Video Storage (object store), CDN, Search Service, Comment Service, Recommendation Engine. Upload large videos using resumable uploads with chunking. Transcode using distributed workers to multiple formats/resolutions. Store metadata in SQL, video files in blob storage with CDN. Implement view counter using distributed counters (Redis/Cassandra). Build recommendation using collaborative filtering on watch history. Use Elasticsearch for video search with ranking by relevance, views, recency. Support live streaming with lower latency using WebRTC. Handle 500 hours of video uploaded per minute. Implement content moderation pipeline with ML models.

Requirements: Post creation, news feed generation, privacy settings, likes/comments, friend suggestions. Components: Post Service, Timeline Service, Graph Database, Ranking Service, Notification Service. Implement fanout-on-write for users with moderate followers – write to follower timelines asynchronously. Use EdgeRank algorithm to rank posts (affinity, weight, time decay). Store posts in Cassandra with user_id partition. Use graph database (TAO) for social graph queries. Implement different post types (text, photo, video, link) with polymorphic storage. Cache timeline in Redis with invalidation on new posts. Handle billions of posts daily. Support complex privacy settings (friends, friends-of-friends, custom). Implement friend suggestion using mutual friends algorithm.

Requirements: Profile management, connections, job postings, feed, messaging, recommendations. Components: Profile Service, Connection Service, Job Service, Feed Service, Messaging Service, Recommendation Engine. Store profiles in document database (MongoDB) for flexible schema. Use graph database for connection degrees (1st, 2nd, 3rd). Implement “People You May Know” using common connections and similar profiles. Build job recommendations using candidate skills matching. Store professional experience with timeline model. Implement endorsements and recommendations with graph relationships. Support groups and company pages. Handle search with Elasticsearch for profiles and jobs. Implement real-time messaging using WebSocket. Add analytics for profile views and post engagements.

Requirements: Product catalog, search, cart, checkout, order management, inventory, payments. Components: Product Service, Search Service (Elasticsearch), Cart Service, Order Service, Inventory Service, Payment Service, Recommendation Engine. Store product catalog in document database for varied attributes. Implement search with faceted navigation, filters, sorting. Use Redis for shopping cart with session management. Handle checkout with distributed transactions (Saga pattern). Implement inventory reservation during checkout with timeout. Integrate payment gateways with retry and fallback. Build recommendation using collaborative filtering (“customers who bought this also bought”). Use event sourcing for order state management. Handle Black Friday traffic with auto-scaling. Implement warehouse management for multi-location inventory.

Requirements: Map data storage, routing, real-time traffic, location search, directions. Components: Map Tile Service, Routing Service, Traffic Service, Search Service, Geospatial Index. Store map data in geospatially indexed database using S2 cells or geohashing. Implement routing using Dijkstra’s or A* algorithm on road network graph. Use historical and real-time data for traffic predictions with ML models. Store POIs (points of interest) in Elasticsearch with geospatial queries. Implement ETA calculation considering traffic, road types, historical patterns. Use CDN for map tiles with different zoom levels. Handle millions of location queries per second. Implement turn-by-turn navigation with voice guidance. Support offline maps with pre-downloaded tiles. Add Street View with panoramic images stored in object storage.

Requirements: File upload/download, synchronization across devices, sharing, versioning. Components: Upload Service (chunking for large files), Metadata Service (SQL), Block Storage (S3), Sync Service, Notification Service (long polling/WebSocket). Split files into 4MB blocks, calculate hash (SHA-256) for deduplication. Store metadata (filename, path, version, blocks) in SQL database. Use block-level sync – only upload changed blocks. Implement conflict resolution for simultaneous edits (timestamp-based or manual). Store multiple versions with delta encoding. Share files with access control (view/edit permissions). Handle 500M users with petabytes of data. Implement client-side encryption for privacy. Use CDN for download acceleration. Add offline mode with local cache synchronization when online.

Requirements: Video/audio calls, screen sharing, recording, chat, meeting scheduling. Components: Signaling Server (WebRTC), Media Server (SFU – Selective Forwarding Unit), Recording Service, Chat Service, Scheduling Service. Use WebRTC for peer-to-peer communication initially, fallback to SFU for group calls. Implement adaptive bitrate based on bandwidth (360p to 1080p). Use TURN servers for NAT traversal. Record meetings in cloud storage with transcription service. Support up to 1000 participants with breakout rooms. Implement virtual backgrounds using ML. Use UDP for low-latency media transport with packet loss handling. Add end-to-end encryption for security. Implement waiting room and host controls. Support live streaming to YouTube/Facebook. Handle zoom bombing with security features.

Requirements: Event listing, seat selection, booking, payment, ticket generation. Components: Event Service, Inventory Service, Booking Service, Payment Service, Ticket Service, Queue Service. Use distributed transactions or Saga pattern for booking flow. Implement seat locking with TTL (10 minutes) during selection. Handle high concurrency with optimistic locking or database row locking. Use queue system (virtual waiting room) for popular events to prevent server overload. Implement dynamic pricing based on demand. Store seat map in JSON with real-time availability. Generate QR code tickets with verification. Support resale marketplace with price caps. Handle flash sales with rate limiting per user. Use Redis for real-time inventory updates. Implement fraud detection for bot purchases.

Requirements: Property listing, search with filters, booking, payments, reviews. Components: Listing Service, Search Service (Elasticsearch with geo queries), Booking Service, Payment Service, Review Service, Recommendation Engine. Store listings in document database (MongoDB) for flexible attributes. Implement geospatial search with filters (price, dates, amenities). Use calendar system for availability with double-booking prevention. Handle reservations with holds and expiration. Implement pricing algorithms considering seasonality and demand. Build recommendation using collaborative filtering on bookings. Support instant book vs request-to-book workflows. Implement review system with mutual reviews (host/guest). Handle disputes with mediation service. Add smart pricing suggestions for hosts using ML. Support multi-currency payments with proper tax handling across jurisdictions.

Requirements: Post submission, voting, commenting, subreddits, trending content. Components: Post Service, Vote Service, Comment Service, Ranking Service, Subreddit Service. Store posts and comments in tree structure (nested comments). Implement vote counting with eventual consistency to handle high throughput. Use hot ranking algorithm: score = (upvotes – downvotes) / (time_since_post)^gravity. Cache hot posts in Redis with periodic recomputation. Implement rate limiting for posting and voting. Support different post types (text, link, image, video). Store karma points per user. Implement moderation tools for subreddit mods. Support awards/gold with payment integration. Use Elasticsearch for search with ranking. Handle millions of posts daily. Implement spam detection and shadowbanning. Add live discussion threads with WebSocket.

Requirements: Payment processing, wallet management, transaction history, fraud detection, refunds. Components: Payment Gateway, Wallet Service, Transaction Service, Fraud Detection Service, Reconciliation Service, Ledger System. Implement double-entry bookkeeping for financial accuracy. Use ACID transactions with 2PC or Saga for distributed transactions. Store transaction logs immutably for audit. Integrate multiple payment methods (cards, bank transfer, digital wallets). Implement fraud detection using ML models (velocity checks, device fingerprinting, behavioral analysis). Support idempotency for payment retries. Handle payment failures with retry logic and fallback gateways. Implement chargebacks and dispute resolution. Support multi-currency with FX rates. Add PCI DSS compliance for card data. Implement real-time balance updates. Use message queue for async payment processing. Add transaction limits and velocity checks.

Requirements: Restaurant listing, menu management, order placement, delivery tracking, payments. Components: Restaurant Service, Order Service, Delivery Service, Menu Service, Location Service, Payment Service, Notification Service. Store menus in document database for flexibility. Implement restaurant search with filters (cuisine, rating, delivery time). Use matching algorithm to assign orders to delivery agents based on proximity and current orders. Implement route optimization for multi-order pickups. Track real-time location with geohashing. Calculate delivery time using ETA service considering traffic. Support scheduled orders and group orders. Implement dynamic pricing for delivery fees. Handle order modifications and cancellations with refund logic. Add restaurant capacity management during peak hours. Support contactless delivery. Implement rating system for restaurants and delivery agents. Use ML for demand prediction and driver positioning.

Requirements: Pin creation, boards, following, personalized feed, visual search. Components: Pin Service, Board Service, Feed Service, Image Service, Search Service (visual + text), Recommendation Engine. Store pins in NoSQL database with image metadata. Use CDN for image delivery with multiple resolutions. Implement feed generation using interest-based ranking. Build visual search using CNN models for image similarity. Use collaborative filtering for recommendations based on pins and boards. Store user interests graph. Implement infinite scroll with cursor-based pagination. Support video pins with streaming. Add shopping features with product tagging. Use Elasticsearch for text search with image metadata. Handle image recognition for automatic tagging. Implement trending pins algorithm. Support group boards with collaboration. Add analytics for pin performance.

Requirements: Business listings, search, reviews, ratings, photos, reservations. Components: Business Service, Review Service, Search Service (geospatial), Photo Service, Reservation Service, Ranking Algorithm. Store business data in SQL with geospatial index. Implement search with location-based ranking using distance and rating. Calculate aggregate ratings with weighted algorithms (recency, verified purchases). Store reviews in NoSQL with sentiment analysis. Support photo uploads with moderation pipeline. Implement spam detection for fake reviews using ML. Use Elasticsearch for full-text search with filters. Add business analytics dashboard for owners. Support reservations with restaurant integration. Implement “people also viewed” recommendations. Handle review disputes and takedown requests. Add check-in feature with location verification. Support different business categories with custom attributes.

Requirements: Music streaming, playlists, search, recommendations, offline mode, social features. Components: Streaming Service, Catalog Service, Playlist Service, Search Service, Recommendation Engine, User Service. Store music metadata in SQL, audio files in object storage. Use CDN with edge caching for popular songs. Implement streaming with chunk-based delivery. Build recommendation using collaborative filtering on listening history. Use content-based filtering for similar songs analysis. Implement Discover Weekly using matrix factorization. Support offline downloads with DRM using Widevine. Create radio stations using seed-based algorithms. Handle 500M users with billions of streams monthly. Implement lyrics sync with timestamp matching. Support podcast hosting and streaming. Add social features (following artists, sharing playlists). Implement queue management and crossfade. Use ML for automatic playlist generation.

Requirements: Channels, direct messages, file sharing, search, integrations, notifications. Components: Message Service, Channel Service, File Service, Search Service (Elasticsearch), Notification Service, Integration Service (webhooks, bots). Use WebSocket for real-time messaging. Store messages in Elasticsearch for full-text search with sharding by channel/time. Implement message threading for organized discussions. Support @mentions with notification triggers. Store files in object storage with link sharing. Implement presence system showing online/away status. Support slash commands and bot integrations. Add message reactions and editing. Implement channel types (public, private, shared between organizations). Use Redis pub/sub for real-time updates. Support rich media embeds (links, images, videos). Add message retention policies for compliance. Implement enterprise features (SSO, audit logs). Handle message delivery guarantees with ACKs.

Requirements: Video upload, feed generation, following, likes, comments, trending. Components: Upload Service, Transcoding Service, CDN, Feed Service, Ranking Algorithm, Social Graph Service, Trending Service. Compress and transcode videos to multiple formats. Use CDN for global video delivery with edge caching. Implement “For You” feed using ML model considering watch time, engagement, user interests. Use collaborative filtering for similar users. Implement trending algorithm using engagement velocity. Store videos in object storage with metadata in NoSQL. Add effects and filters using FFmpeg and ML models. Support duets and stitching existing videos. Implement comment system with nested replies. Use Redis for real-time like counters. Add sound library for background music. Implement content moderation using ML for inappropriate content. Support live streaming with RTMP. Handle viral content with auto-scaling.

Requirements: Restaurant discovery, ordering, delivery tracking, payments, reviews. Components: Restaurant Service, Order Management Service, Delivery Fleet Management, Routing Service, Payment Service, Review Service. Implement restaurant search with multiple filters (cuisine, rating, delivery time, cost). Use geospatial indexing for nearby restaurants. Build menu management system with item availability. Implement order workflow (received → preparing → picked up → delivered). Use matching algorithm for delivery partner assignment based on proximity, ratings, current load. Implement route optimization for multiple orders using TSP algorithms or ML-based routing. Track real-time location with frequent updates. Calculate dynamic delivery fees based on distance, demand, weather. Support scheduled orders and subscriptions. Implement surge pricing during peak hours. Add restaurant capacity management with estimated preparation time. Handle promotions and coupon codes with validation rules.

Requirements: Repository hosting, version control, pull requests, issues, CI/CD, code review. Components: Git Server, Storage Service, Collaboration Service, Search Service, CI/CD Pipeline, Notification Service. Store repositories using Git protocol with pack files for efficiency. Implement distributed storage across multiple servers. Support pull requests with diff views and merge strategies (merge commit, squash, rebase). Add code review with inline comments and approval workflow. Implement issues and project management with labels, milestones, assignments. Use Elasticsearch for code search with syntax awareness. Integrate CI/CD with webhooks triggering automated pipelines. Support GitHub Actions for custom workflows. Implement repository forking and branching. Add wikis and documentation hosting. Support security scanning for vulnerabilities. Implement access control with organization/team permissions. Handle large repositories with LFS for binary files.

Requirements: Hotel search, booking, payments, cancellations, reviews. Components: Inventory Service, Search Service, Booking Service, Payment Service, Review Service, Pricing Engine. Store hotel inventory with room types and availability calendar. Implement geospatial search with filters (price, amenities, rating, dates). Use calendar system with overbooking prevention. Handle booking holds with TTL during payment process. Implement cancellation policies (free cancellation, non-refundable). Build dynamic pricing considering demand, seasonality, events. Support multiple room booking with group discounts. Add review system with verified bookings only. Implement fraud detection for fake bookings. Use caching for popular destinations. Support multiple currencies and languages. Add loyalty programs with points. Implement inventory distribution across multiple channels. Handle no-shows and late cancellations. Support instant confirmation vs on-request bookings.

Requirements: Real-time quotes, order placement, portfolio management, market data, notifications. Components: Order Management System, Market Data Feed, Matching Engine, Portfolio Service, Risk Management, Settlement Service. Integrate real-time market data feeds (NYSE, NASDAQ). Implement order types (market, limit, stop-loss, trailing stop). Use order book with price-time priority matching. Handle partial fills and order queues. Implement portfolio tracking with real-time P&L calculation. Add risk management with margin requirements and position limits. Support after-hours trading with different rules. Implement dividend tracking and corporate actions. Use WebSocket for real-time quote updates. Add watchlists with price alerts. Implement paper trading for practice. Support options and derivatives trading. Handle T+2 settlement cycle. Add tax reporting with 1099 generation. Implement pattern day trader detection and rules.

Requirements: Article publishing, reading, clapping, commenting, following, recommendations. Components: Article Service, User Service, Social Graph, Recommendation Engine, Search Service, Payment Service (for writers). Store articles in document database with rich text content. Implement draft autosaving with version history. Use CDN for images and media. Build reading time estimation algorithm. Implement “clap” system with limits per user per article. Calculate article rankings using engagement metrics (reads, claps, read percentage). Use collaborative filtering for personalized recommendations. Implement paywall for premium content with metered model. Support publication management with editors and contributors. Add highlighting and note-taking features. Use Elasticsearch for full-text search. Implement follower feed with chronological and algorithmic sorting. Support email subscriptions for publications. Add writer earnings calculation based on member reading time.

Requirements: Lessons, progress tracking, gamification, practice exercises, social features. Components: Content Service, Progress Service, Exercise Engine, Gamification Service, Social Service, Analytics. Store course content in hierarchical structure (course → unit → lesson). Implement spaced repetition algorithm for optimal review timing. Use ML for personalized difficulty adjustment based on user performance. Track user progress with XP points and streaks. Implement gamification with achievements, leaderboards, leagues. Add practice exercises (multiple choice, translation, speaking, listening). Use speech recognition API for pronunciation checking. Implement hearts system for limited mistakes. Support adaptive learning path based on weak areas. Add social features (following friends, comparing progress). Use A/B testing for content effectiveness. Implement notification system for streak reminders. Support offline mode with content downloads. Add progress sync across devices.

Requirements: Servers, channels (text/voice), direct messages, roles/permissions, bots, streaming. Components: Message Service, Voice Service (WebRTC), Server Service, Permission Service, Bot Framework, CDN. Use WebSocket for real-time text messaging. Implement voice channels using WebRTC with SFU for group calls. Store messages with retention policies per channel. Support server organization with categories and channels. Implement hierarchical permission system (server → role → channel). Add bot integration with webhook and gateway API. Support rich embeds and markdown formatting. Implement screen sharing and Go Live streaming. Use Redis for presence management. Add server discovery and templates. Support nitro subscriptions with perks. Implement content moderation with AutoMod. Handle voice regions for low latency. Add server boost system with tier rewards. Support threads for organized discussions. Implement stage channels for events.

Requirements: Question posting, answering, voting, following, search, recommendations. Components: Question Service, Answer Service, Vote Service, Social Graph, Search Service, Recommendation Engine. Store questions and answers with tree structure for comments. Implement voting system with reputation points for quality content. Calculate answer ranking using votes, views, recency, author credibility. Use Elasticsearch for question search with semantic understanding. Implement topic tagging with hierarchy (Technology → Programming → Python). Build feed using followed topics and similar questions answered. Add A2A (Ask to Answer) feature for expert targeting. Support answer editing with revision history. Implement duplicate question detection using NLP. Add moderation for policy violations. Use ML for answer quality prediction. Support anonymous posting with identity protection. Implement spaces for communities. Add writing prompts and question suggestions. Support monetization through Quora Partner Program.

Requirements: Order management, kitchen display system, inventory, menu management, multiple brands. Components: Order Aggregation Service, KDS (Kitchen Display System), Inventory Management, Menu Service, Analytics Dashboard. Aggregate orders from multiple platforms (UberEats, DoorDash, direct). Display orders on kitchen screens with preparation time tracking. Implement inventory tracking with ingredient-level management. Support recipe management with yield calculations.

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.