Expedia 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.
- DSA
- LLD
- HLD
Q1: Area of Triangle
Given three sets of distinct coordinates that form a triangle, calculate the area of the triangle. At least one side will be parallel to either the x-axis or y-axis.
Example:
Input: x = [0, 3, 6]
y = [0, 3, 0]
Output: 9
Explanation: Base = 6, Height = 3, Area = (6 * 3) / 2 = 9
Q2: Simple Cipher
Decrypt a given string by shifting each uppercase English letter k steps counterclockwise (Z → A).
Example:
Input: encrypted = “CDEF”, k = 2
Output: “ABCD”
Q3: Connected Groups
Given a binary relationship matrix where related[i][j] = 1 means person i knows person j, determine the number of connected groups.
Example:
Input: related = [‘1100’, ‘1110’, ‘0110’, ‘0001’]
Output: 2
Explanation: Group 1 → {0,1,2}, Group 2 → {3}
Q4: Minimum Partitions
Given used space and total capacity of partitions, determine the minimum number of partitions required to accommodate all data.
Example:
Input: used = [3, 2, 1, 3, 1]
total Capacity = [3, 5, 3, 5, 5]
Output: 2
Q5: Shopping Cart Billing
Given a list of products with discounts, determine the minimum total cost after applying the best discount.
Discounts can be:
- Type 0 → Fixed Price
- Type 1 → Percentage
- Type 2 → Fixed Amount
Q6: Celebrity Problem
Find the celebrity in a group — a person known by everyone but knows no one.
Concepts Covered:
- Matrix Problem
- Stack or Two-Pointer Elimination
- O(N) Optimization
Q7: Valid Parentheses
Given a string containing only ()[]{}, determine if the parentheses are valid.
Concepts Covered:
- Stack
- String Matching
Example:
Input: “{[()]}”
Output: true
Q8: Hotel Reviews Filter
Given a list of preferred words and hotel reviews, return hotel IDs with reviews containing the maximum number of preferred words.
Concepts Covered:
- String Matching
- HashSet
- Map Counting
Q9: Sliding Window Questions
Common Expedia topics include:
- Longest Substring Without Repeating Characters
- Maximum Sliding Window
- Subarray Sum Variants
Example:
Input: “abcabcbb”
Output: 3 (“abc”)
Q10: Graph & Greedy Mix
Expedia’s OA and DSA rounds often test Greedy + Graph blend logic like:
- Bipartite Graph check
- Greedy scheduling
- Subarray optimization
Concepts Covered:
- BFS / DFS
- Sorting-based Greedy logic
Q11: Merge Intervals Problem
Given a collection of intervals represented as [start_time, end_time], merge all overlapping intervals and return a new array of merged intervals. If there are no overlapping intervals, return a single interval that covers all given intervals. This classic interval merging problem requires identifying overlapping segments based on time coordinates and consolidating them efficiently. The solution typically involves sorting by start time and maintaining a result array. Example: [, ] returns []. Edge cases include empty arrays and non-overlapping intervals.
Q12: Maximum Profit in Non-Overlapping Trades
Given an array of stock trading logs with [buy_time, sell_time, profit], select non-overlapping trades that maximize total profit. Two trades overlap if one’s sell_time occurs after another’s buy_time. Trades can occur on the same day (sell on day 3, buy again on day 3). The solution requires dynamic programming or greedy selection with binary search to efficiently find the best trade combinations. Example: [,, ] selects trades at indices 0 and 2 for maximum profit of 30.
Q13: Minimum Partitions Problem
Given two arrays representing space used on each drive partition and total capacity of each partition, determine the minimum number of partitions required to consolidate all data without exceeding any partition’s total capacity. This problem involves optimizing storage allocation through data movement across partitions. You can move data between partitions freely to minimize the number of active partitions needed. Example: used=, capacity= requires minimum 2 partitions. Use a greedy approach sorting capacities in descending order.
Q14: Simple Cipher Decryption
Given an encrypted string containing only uppercase English letters (A-Z) and an integer K, decrypt the string by shifting each character K positions counter-clockwise on an alphabet wheel. The shift should wrap around (A shifted back 1 becomes Z). Optimize by using modulo 26 to handle unnecessary rotations. Example: encrypted=”BCD”, K=1 returns “ABC”. This requires understanding circular arrays and modular arithmetic for character transformations.
Q15: Shopping Cart Billing with Multiple Discounts
Calculate the minimum cost to purchase products with multiple discount options applied as: Type 0 (direct discounted price), Type 1 (percentage discount from retail), Type 2 (fixed amount off). For each product, evaluate all applicable discounts and select the minimum resulting price. Truncate to integer before summing costs. Example: product price 10 with 27% discount becomes 7, with 5 fixed discount becomes 5, so minimum is 5. This involves discount comparison logic and price calculation.
Q16: Conveyor Belt Shipments Logic
A conveyor belt has packages that must be shipped from one port to another within B days. Each package has a weight. Daily, load the ship with packages in order from the conveyor belt, ensuring total weight doesn’t exceed ship capacity. Return the minimum ship capacity needed to ship all packages within B days. Example: A=, B=5 requires capacity 15. This involves binary search on capacity with validation logic.
Q17: Maximum Length Subarray of Ones
Given a binary array containing only 0s and 1s and an integer B, find the maximum length subarray of 1s after flipping at most B zeros to ones. This sliding window problem requires tracking zero counts and expanding/contracting window boundaries. Example: A=, B=1 returns length 4 (after flipping one zero). Edge cases include all zeros, all ones, and B larger than zero count.
Q18: Sort Stack Using Temporary Stack
Given a stack of integers, sort it in ascending order using only another temporary stack as additional storage. You cannot use extra data structures. Push elements back to the original stack sorted. This requires understanding stack operations (push, pop) and implementing efficient sorting logic. The optimal approach involves comparing and repositioning elements between the two stacks strategically to achieve sorted order.
Q19: Area of Triangle
Given three points representing vertices of a triangle, calculate the area using the coordinate formula: Area = |x1(y2-y3) + x2(y3-y1) + x3(y1-y2)| / 2. Handle edge cases where points are collinear (area = 0). This involves coordinate geometry and absolute value calculations. Example: points (0,0), (3,0), (0,4) form a triangle with area 6.
Q20: Celebrity Problem
In a group of N people, identify the celebrity (if exists) who is known by everyone but knows nobody. Given a knows(a, b) function returning true if person A knows person B, find the celebrity in O(N) time with O(1) space. This classic problem uses the elimination principle to identify the single candidate, then validates with two passes through the people list.
Q21: Palindrome Substring Count
Count all palindromic substrings in a given string. Include single characters as palindromes. Example: “abc” returns 3, “aab” returns 4. Use expand-around-center technique for O(N²) time complexity or dynamic programming for clarity. Handle both odd-length palindromes (single center) and even-length palindromes (two-character center).
Q22: Binary Game Problem
A game involves binary representations of numbers. Players perform operations to manipulate binary digits according to specific rules. The problem typically requires understanding bit operations, game theory, and optimal play strategy. This tests knowledge of bitwise AND, OR, XOR operations and recursive game state evaluation.
Q23: Efficient Teams Problem
Given a list of team member capabilities/efficiencies, determine optimal team formation to maximize total efficiency under constraints. This may involve selecting a subset of members such that combined efficiency meets requirements or forms the best possible team. Requires understanding subset selection and optimization under constraints.
Q24: Minimum Operations to Make Elements Unique
Given an array of integers, determine the minimum number of operations to make all elements unique (all distinct values). Each operation can increment any element by 1. Example: requires operations to become. Use sorting and greedy assignment to find minimum increments needed.
Q25: Monotonic Stack Problem
A medium-hard problem involving monotonic stack data structure. Common variants include finding next greater element, removing K digits to get smallest number, or removing duplicate letters while maintaining order. Monotonic stacks maintain elements in increasing or decreasing order for efficient processing.
Q26: Array Observation Problem
An easy-medium array problem requiring good observation skills. The solution is simple but discovery requires careful analysis of the input. Typically involves identifying patterns, calculating specific values, or implementing straightforward algorithms once the pattern is recognized.
Q27: String and Hashing Problem
A medium-hard problem combining string manipulation with hashing. May involve bit parity checks, character frequency analysis, or hash-based lookups. Tests understanding of hash functions, string operations, and problem-solving under constraints with hashing optimizations.
Q28: Maximum Subarray Sum with Constraint
Given an array of integers and a constraint K, find the maximum sum of a subarray such that the subarray length does not exceed K. Use dynamic programming where dp[i] represents the maximum sum ending at index i with length at most K. For each position, track the maximum sum considering all valid subarray lengths. Example: array=, K=2 returns 7 (subarray ). Handle negative numbers and optimize space complexity by using sliding window with deque to maintain maximum sums for each valid length up to K.
Q29: K-th Largest Element in Stream
Design a data structure that receives integer values from a stream and returns the k-th largest element. Use a min-heap of size K where the root stores the k-th largest. For each new element, if heap size < K, add it; otherwise, compare with min and update if larger. Time complexity: O(log K) per insertion, O(1) for retrieval. Example: stream=, K=3 returns 4 as k-th largest. Handle edge cases where fewer than K elements have been received.
Q30: Number of Islands (Advanced)
Given a 2D grid with 1s (land) and 0s (water), count distinct islands where islands are connected horizontally or vertically. Use DFS/BFS with visited matrix. For each unvisited land cell, perform DFS marking all connected cells, incrementing island count. Support follow-ups: island perimeter calculation, largest island area, minimum number of days to remove all islands. Example: [,,] contains 2 islands. Optimize space using recursive DFS or iterative BFS.
Q31: Longest Increasing Subsequence (LIS)
Find the longest subsequence of an array where elements are in increasing order but not necessarily contiguous. Use dynamic programming: dp[i] = longest increasing subsequence ending at index i. For each position, check all previous elements and extend their sequences if current element is larger. Time: O(N²) or O(N log N) with binary search. Example: returns 4 (subsequence ). Include space-optimized versions and follow-ups for LDS (Longest Decreasing Subsequence).
Q32: Smallest Range in K Lists
Given K sorted lists of integers, find the smallest range that includes at least one element from each list. Use a min-heap approach: maintain a pointer for each list, keep track of the current range [min, max], and move the pointer pointing to the minimum element. Track the range with minimum difference. Time: O(N log K) where N is total elements. Example: lists=[,,] returns. Handle duplicate values and large datasets efficiently.
Q33: Trapping Rain Water
Given elevation map where array[i] represents bar height, calculate how much water can be trapped between bars. Use two pointers or dynamic programming: left[i] = maximum height to the left, right[i] = maximum to the right. Water at position i = min(left[i], right[i]) – height[i]. Example: traps 6 units. Optimize to O(1) space using two-pointer approach. Handle varying bar heights and cascading water scenarios.
Q34: Word Ladder (Shortest Path)
Given a start word, end word, and dictionary, find the shortest path (minimum transformations) changing one letter at a time. Each intermediate word must be in the dictionary. Use BFS for shortest path: level = word length, explore neighbors by changing one letter. Prune search by checking if neighbors exist in dictionary set. Example: start=”hit”, end=”cog”, dict=[“hot”,”dot”,”dog”,”lot”,”log”] returns 5. Handle large dictionaries and optimize neighbor generation.
Q35: Median of Two Sorted Arrays
Find the median of two sorted arrays efficiently. Use binary search on the shorter array to partition both arrays such that left elements ≤ right elements. Time complexity: O(log(min(m,n))). Handle edge cases: different sizes, empty arrays, odd vs even total length. Example: nums1=, nums2= returns 2.0. Explain how median changes for odd (middle element) vs even (average of two middle) total elements.
Q36: Next Permutation
Given an array representing a permutation, rearrange it to the next lexicographically greater permutation. Algorithm: find rightmost position where arr[i] < arr[i+1], find smallest element to right larger than arr[i], swap, and reverse the suffix. Example: →. Handle edge case where array is the last permutation (return first). Time: O(N), Space: O(1). Useful for generating all permutations iteratively.
Q37: Burst Balloons
Given an array of balloons with values, burst balloons to maximize coins. When bursting balloon i, you get coins = left[i] * balloon[i] * right[i]. Use dynamic programming with interval DP approach: dp[left][right] = maximum coins bursting all balloons between left and right. Process middle balloons before boundaries. Example: with surrounding 1s at edges. Handle base cases and subproblem dependencies.
Q38: Zigzag Conversion
Given a string and number of rows, write the string in zigzag pattern and then read row by row. Example: “PAYPALISHIRING” with 3 rows creates: P A H R A P P L S I I G Y I R N (reading row by row: “PAHNRAPLSIIGYI”). Direct calculation: determine which row each character belongs to based on position in zigzag pattern. Time: O(N), Space: O(N). Handle single row and two-row edge cases.
Q39: Remove K Digits
Given a string of digits and integer K, remove K digits to get the smallest possible number. Use a greedy stack approach: for each digit, remove larger digits from stack if possible, then push current digit. Ensure result doesn’t have leading zeros. Example: num=”1432219″, K=3 returns “1219”. Handle cases where K exceeds number of digits. Optimize to achieve lexicographically smallest result.
Q40: Shortest Subarray with Sum at Least K
Find the shortest subarray with sum at least K. Naive approach is O(N²). Optimize with deque: use prefix sums, maintain deque of indices in increasing order of prefix sum. For each position, check if any prefix sum is ≤ current – K, then update the answer. Time: O(N). Example: A=, K=4 returns 1 (subarray ). Handle negative numbers carefully.
Q41: Minimum Window Substring
Given two strings S and T, find the minimum window in S that contains all characters from T. Use a sliding window with two pointers and character frequency map. Expand the right pointer until the window contains all characters, then contract left to minimize. Track character count and required count. Example: S=”ADOBECODEBANC”, T=”ABC” returns “BANC”. Handle duplicates in T.
Q42: Valid Parentheses Sequence
Given a string with parentheses, determine if it’s valid (properly matched and ordered). Use a stack: push opening brackets, pop when seeing closing bracket matching top. String is valid if stack is empty at end and no unmatched closing brackets found. Time: O(N), Space: O(N). Example: “(())” is valid, “([)]” is not. Extend to multiple bracket types and complex nesting.
Q43: LRU Cache Implementation
Implement a cache with fixed capacity supporting get and put operations in O(1) time. Use HashMap for value lookup and DoublyLinkedList for LRU ordering. When capacity exceeded, evict the least recently used item. Example: LRUCache(2) → put(1,1) → put(2,2) → get(1)=1 → put(3,3) removes 2. Handle concurrent access considerations.
Q44: Rotated Sorted Array Search
Search for a target in a rotated sorted array in O(log N) time using binary search. Determine which half is properly sorted, then decide which half contains the target. Example:target=0 returns 4. Handle duplicates in extended version:. Optimize space to O(1).
Q45: Product of Array Except Self
Given array, return array where result[i] = product of all elements except array[i] without using division. Use prefix and suffix products: left[i] = product of all elements to left, right[i] = product to right. Result[i] = left[i] * right[i]. Time: O(N), Space: O(N) or O(1) if output array doesn’t count. Example: returns .
Q46: Minimum Cost to Connect Ropes
Given array of rope lengths, connect all ropes minimizing total cost. Cost to connect two ropes = sum of their lengths. Use a min-heap: repeatedly connect two shortest ropes, add result back to heap. Example: costs 3+4=7, then 7+5=12, then 12+6=18, total=37. Prove why greedy approach works. Handle single rope edge case.
Q47: Group Anagrams
Given array of strings, group anagrams together. Anagrams have same characters in different order. Use sorted string as key: sort each word, use as HashMap key. All anagrams with same sorted form group together. Time: O(N*K log K) where K is max word length. Example: [“eat”,”tea”,”ate”,”nat”,”tan”,”bat”] groups into [[“eat”,”tea”,”ate”],[“nat”,”tan”],[“bat”]]. Optimize key generation using character frequency.
Q48: Longest Substring Without Repeating Characters
Given a string, find the length of longest substring without repeating characters. Use sliding window with character-to-index map. Expand right pointer, track maximum length. When repeating character found, move left pointer. Example: “abcabcbb” returns 3 (“abc”). Handle Unicode and special characters. Optimize to single pass with O(N) time, O(min(N, charset size)) space.
Q49: Coin Change Problem
Given coin denominations and amount, find minimum number of coins needed. Use dynamic programming: dp[i] = minimum coins for amount i. For each amount, try each coin and take minimum. Example: coins=, amount=5 returns 1 coin (5). Handle impossible amounts (return -1). Optimize space with single array. Follow-up: count number of ways to make amount.
Q49: Coin Change Problem
Given coin denominations and amount, find minimum number of coins needed. Use dynamic programming: dp[i] = minimum coins for amount i. For each amount, try each coin and take minimum. Example: coins=, amount=5 returns 1 coin (5). Handle impossible amounts (return -1). Optimize space with single array. Follow-up: count number of ways to make amount.
Q50: Jump Game II
Given array where each element represents max jump length, find minimum jumps to reach last index. Use greedy approach: track farthest reachable position, update when passing previous range end. Example: returns 2 (jump 1 step from index 0 to 1, then 3 steps to reach last index). Handle single element array and unreachable scenarios.
Q51: Interval Scheduling (Activity Selection)
Given intervals, select maximum non-overlapping intervals. Sort by end time, greedily select intervals that don’t overlap with previously selected. Time: O(N log N) for sorting. Example: intervals=[,,,] returns 3 intervals. Prove optimality of greedy approach. Follow-up: minimum number of rooms needed.
Q52: Majority Element
Find element appearing more than N/2 times in array. Use Boyer-Moore voting algorithm: candidate and count. For each element, if count=0, new candidate; else increment/decrement count. Verify candidate appears > N/2 times. Time: O(N), Space: O(1). Example: returns 3. Extend to find all elements appearing > N/K times.
Q53: House Robber with Constraint
Given array of house values, rob non-adjacent houses maximizing loot. Can’t rob adjacent houses. Use DP: dp[i] = max loot up to house i. Choice: rob current (skip previous) or skip current. Example: returns 4 (rob houses 0 and 2). Handle circular array (house 0 and n-1 are adjacent) and tree structure variations.
Q1. Ticket Booking System
Design a simplified ticket booking system. Include services, data models, and APIs for booking, cancellation, and seat availability.
Concepts Discussed:
- Classes & Relationships
- SOLID Principles
- Service Layer Abstraction
Q2. Delivery Service API
Design an API to check if a product can be delivered within 2 days based on pincode.
Focus Areas:
- API structure
- Extensibility (multi-region)
- Scalability & Failure Handling
Q3. Rate Limiter
Implement a rate limiter to allow a fixed number of requests in a time window.
Focus Areas:
- Token Bucket / Leaky Bucket
- Thread-safety
- Efficient Cache usage
Q4. Notification Service
Design a notification service capable of sending real-time alerts via multiple channels (SMS, Email, Push).
Focus Areas:
- Observer Pattern
- Event Queues
- Retry Mechanisms
Q5. Design a Scalable Web Crawler
Design a system that crawls websites efficiently while respecting rate limits and robots.txt. Consider: URL frontier management, duplicate detection (using bloom filters), multi-threaded crawling with thread pools, politeness policies for domain rate limiting, URL normalization, and storage of crawled data. Include classes for URL Queue, Crawler Worker, Domain Throttler, and Result Storage. Handle circular references and dynamic content appropriately.
Q6. Design a Standard LLD Question
Based on Expedia interview experiences, candidates are asked to design standard data structures or systems. This typically involves creating a class hierarchy with proper encapsulation, demonstrating SOLID principles, handling edge cases, and explaining design trade-offs. The exact question varies but emphasizes clean code, modularity, and maintainability.
Q7. Design a Workflow System for HR Operations
Create a system for managing HR workflows where tasks are distributed to employees (sending emails, approvals, notifications). Design classes for Task, WorkflowEngine, Employee, and Notification handlers. Implement task routing logic, status tracking, and role-based permissions. Consider asynchronous task execution and error handling for failed tasks.
Q8. Implement an E-commerce Product Filtering System
Design classes to support filtering products by multiple attributes (price range, category, ratings, availability). Use a Filter interface with implementations for each filter type. Implement composite filtering where multiple filters combine logically. Optimize for performance with indexing strategies and lazy evaluation of filter chains.
Q9. Design a Rate Limiting System
Implement a token bucket or sliding window rate limiter for API requests. Design User, Bucket, and RateLimiter classes. Handle concurrent requests, time window management, and cleanup of expired tokens. Support different rate limits for different user tiers or API endpoints with configurable parameters.
Q10. Design a Data Structure for Time-based Key-Value Store
Create a data structure that stores key-value pairs with timestamps and retrieves values based on timestamps. Support operations: set(key, value, timestamp), get(key, timestamp) returning the value at that timestamp or closest previous timestamp. Use TreeMap or sorted lists for efficient timestamp-based queries.
Q11. Design an Event Management System
Implement classes for Event, EventListener, EventBus/EventDispatcher supporting publish-subscribe pattern. Handle event registration, unregistration, and dispatching with optional filtering. Support synchronous and asynchronous event handling with thread-safe operations for concurrent systems.
Q12. Design a Shopping Cart System
Create Cart, Item, and CartManager classes supporting add, remove, update quantity, calculate total price with tax. Implement discount application logic for percentage and fixed discounts. Handle inventory checks and persist cart state. Include serialization for saving/loading carts.
Q13. Design a Notification System
Implement multi-channel notification delivery (email, SMS, push notifications) using strategy or decorator patterns. Create NotificationService, Channel implementations, and Message classes. Handle retry logic for failed deliveries, queuing, and rate limiting per channel. Support template-based notifications.
Q14. Design a Caching Layer
Implement LRU (Least Recently Used) cache with O(1) get/put operations using HashMap and DoublyLinkedList. Support TTL (time-to-live) for cache entries. Handle concurrent access with proper synchronization. Include cache statistics for hits, misses, and eviction tracking.
Q15. Design an LRU Cache
Implement a cache with fixed capacity supporting get(key) and put(key, value) operations in O(1) time. When capacity exceeded, evict least recently used item. Use HashMap for O(1) value lookup and DoublyLinkedList for LRU ordering. Most recently used moves to tail. When accessing/inserting, move node to end. Capacity eviction removes head (oldest). Design considerations: thread safety with locks, optional time-based expiration (TTL), statistics tracking (hits, misses), bulk operations. Example: LRUCache(2) → put(1,1),
Q16. Design a Parking Lot System
Model a multi-level parking lot with parking spots, vehicles, and payment system. Classes: ParkingLot (entrance, levels, fee calculator), Level (spots, display available count), ParkingSpot (occupied status, vehicle reference), Vehicle (license plate, type, entry/exit time), TicketManager (generate/process tickets), PaymentProcessor (handle various payment methods). Spot types: compact, regular, large. Spot assignment algorithm: prefer closest available spot or by type. Tracking: entry timestamp, exit timestamp, duration, fee calculation. Follow-ups: reservation system, handicap spots, compact spot upgrade logic. Design handles: vehicle entry, spot allocation, exit with fee calculation, spot status updates.
Q17. Design a Meeting Room Scheduler
Build system for booking meeting rooms with conflict resolution. Classes: Room (capacity, id, available slots), TimeSlot (start, end times), Booking (user, room, time slot, meeting details), RoomScheduler (manage bookings, check availability, book rooms). Availability checking: no overlapping bookings. Booking operations: create, cancel, reschedule. Constraints: room capacity limits, unavailable time blocks, recurring meetings. Data structures: interval trees or TreeMap for efficient time slot management. Conflict detection: O(log N) with balanced tree. Features: recurring bookings, meeting reminders, cancellation policies, room preferences. Database persistence of bookings.
Q18. Design a Library Management System
Create system managing books, members, checkouts, and returns. Classes: Book (ISBN, title, author, availability status, location), Member (membership ID, details, borrowed books limit), Reservation (book, member, reservation date, expiry), Librarian (staff functions), Catalog (search books), CheckoutManager (issue/return books). Operations: add book, search by title/author/ISBN, check availability, checkout (update book status, add to member borrowed list), return (mark available, track late fees). Constraints: checkout duration (typically 21 days), late fees calculation, reservation queue if unavailable. Database transactions for consistency. Features: hold requests, renewal capability, analytics (popular books, member activity).
Q19. Design an Online Auction System
Build platform for buying/selling items through auctions. Classes: Item (seller, description, starting price, auction start/end time, current highest bid), Bid (bidder, amount, timestamp), Auction (manages item and bids), User (buyer/seller profile), PaymentProcessor (handles transactions). Auction logic: accept bids higher than current highest, track bidders, validate timestamps (auction must be active), prevent seller self-bidding. End auction: highest bidder wins, payments processed, seller notified. Features: automatic bid increment, proxy bidding (bid up to max automatically), bid retraction with restrictions, auction extension if bid near end. Concurrency: handle simultaneous bids with locking or optimistic concurrency control. Notifications for outbid and auction end.
Q20. Design a Ride-Sharing System (Uber/Lyft)
Model ride request, driver matching, trip management. Classes: User (passenger/driver), Location (lat, long, address), RideRequest (passenger, pickup, destination, time, vehicle type), Driver (location, vehicle, availability status, ratings), Vehicle (type, capacity, license plate), Trip (request, assigned driver, route, fare, status), RideManager (match requests to drivers), PaymentProcessor (fare calculation and payment). Matching algorithm: find available drivers near passenger location by distance/time. Fare calculation: base fee + distance + time + surge pricing. Trip states: requested, accepted, started, completed, cancelled. Driver ratings and review system. Features: pickup location confirmation, route optimization, driver location updates, cancellation charges, multiple passenger types (UberX, UberPool). Real-time location tracking and ETA calculation.
Q21. Design a Movie Ticket Booking System
Build online cinema ticket reservation platform. Classes: Theater (location, screens), Screen (movies, capacity, seating layout), Show (movie, time, screen, available seats), Seat (row, column, type, availability), Ticket (show, seat, price, buyer), Booking (user, tickets, total price, status), PaymentProcessor. Seating: different types (regular, premium, recliner) with different prices. Seat selection: show available seats, prevent double booking. Booking workflow: select show, choose seats, payment, ticket generation with barcode. Constraints: group booking limits, user booking limits per transaction, cancellation policies (refund if cancelled before deadline, penalties otherwise). Concurrency: handle simultaneous seat selections with reservation locks. Features: advance bookings (60-90 days), combo offers (tickets + food), membership discounts, dynamic pricing based on occupancy.
Q22. Design a Restaurant Reservation System
Platform for booking restaurant tables. Classes: Restaurant (name, location, capacity, tables, timings), Table (capacity, location in restaurant, availability), ReservationSlot (time slot, available table count), Reservation (customer, table, time, party size, status), Menu (items, prices), PaymentProcessor. Availability check: find tables matching party size for requested time slot. Reservation confirms: table assignment, confirmation details, cancellation policy. Table management: reservations need to be released by specified time or marked no-show. Features: waitlist management (assign to cancelled slots), special requests (seating preferences, dietary requirements), deposit/prepayment options, integration with reviews/ratings. Notifications: confirmation email, reminder SMS. Cancellation: free if >2 hours, charges thereafter. Database maintains reservation history for no-show tracking.
Q23. Design an ATM System
Create ATM machine software managing transactions. Classes: ATM (card reader, keypad, cash dispenser, printer), Card (account number, PIN, balance), Account (balance, transaction history, overdraft limit), Transaction (type, amount, timestamp, status), Bank (manages accounts, validates transactions), CashDispenser (tracks bills, dispenses cash). Operations: insert card, authenticate PIN (3 attempts limit, card blocked), select transaction, validate amount against balance/limit, dispense cash, print receipt. States: idle, accepting card, transaction mode. Security: encrypt PIN, validate card expiration, confirm amount before dispensing. Features: withdraw, deposit envelope, balance inquiry, change PIN, transfer funds, mini-statement. Error handling: insufficient cash, invalid amount, network timeout (rollback transaction), card retention on suspicious activity.
Q24. Design a Vending Machine
Simulate vending machine for snacks/beverages. Classes: VendingMachine (inventory, price list, cash handler), Item (product name, price, quantity), Selection (row, column, item), Payment (method, amount), Transaction (selected item, payment, change, status). States: idle, accepting payment, dispensing, out-of-stock. Inventory management: track quantities, restock items, alert when low stock. Payment: cash (coins and bills), card, mobile payment. Payment validation: sufficient amount, exact change or change calculation, refund on cancellation. Dispensing: confirm item availability, dispense item, return change. Features: multi-language display, sales tracking, maintenance alerts, discount codes, combo deals. Error scenarios: exact change not available, item stuck, card payment failure, invalid amount input.
Q25. Design a Chess Game
Implement chess game with piece movements, board state, and game rules. Classes: Board (8×8 grid), Piece (type, color, current position, movement rules), Player (white/black, pieces, captures), Game (players, current turn, move history, game state), Move (from position, to position, captured piece, promotion). Piece types: Pawn, Rook, Bishop, Knight, Queen, King with specific movement rules. Validation: move legality, not moving opponent’s pieces, special moves (castling, en passant, pawn promotion). Check/Checkmate detection: king under attack, no legal moves. Game states: ongoing, check, checkmate, stalemate, draw. Features: move history with ability to undo, move suggestions, time control (blitz, rapid, classical), ratings, PGN notation. Turn-based: validate move, update board, check game state, switch turns. Piece capture and board state persistence.
Q26. Design a File System
Create in-memory file system with files and directories. Classes: FileSystem, FileNode (stores data), DirectoryNode (stores children), Path (directory traversal). Operations: createDirectory, createFile, list (show contents), read file, write/append to file, delete (recursive for directories). Representation: tree structure with root directory. Path parsing: split by “/” and traverse nodes. Permissions: optional read/write/execute. Features: symbolic links, hard links, file metadata (size, creation/modification time, permissions), file locks, concurrent access control. Memory optimization: sparse files, deduplication. Error handling: file not found, permission denied, invalid paths, circular symbolic links. Comparison with real file systems (FAT, NTFS, ext4).
Q27. Design a Wordle Game
Create Wordle clone with word guessing logic. Classes: Game (target word, attempts, status), Player (name, guesses, score), WordValidator (dictionary, word length validation), Guess (word, feedback), LetterFeedback (correct position, wrong position, not in word). Game flow: set target word (5-letter), player makes 6 guesses, feedback on each letter (green=correct position, yellow=wrong position, gray=not in word). Win condition: correct word within 6 attempts. Score calculation: bonus for fewer attempts. Features: difficulty levels (common vs obscure words), daily challenge (same word for all), statistics tracking (games played, win rate, streak), hint system (reveal letter), hard mode (must use revealed letters). Word validation: check against dictionary, minimum word length. Statistics persistence and leaderboards.
Q28. Design a Distributed Counter
Implement counter in distributed system with concurrent increments. Base approach: single counter with locking (bottleneck). Optimized: local counters per thread/process with periodic aggregation. Sharded counters: hash incoming request to shard, increment shard counter, aggregate for total. Classes: Counter (value, lock), ShardedCounter (shards, aggregator). Consistency: eventual consistency acceptable for high throughput. Batching: accumulate local changes, sync periodically. Features: read operations (return approximate current value), background sync, shard rebalancing, counter reset. Handles: high-frequency increments (millions per second), distributed nodes, fault tolerance. Trade-offs: accuracy vs throughput, consistency vs performance.
Q29. Design a Key-Value Store with Expiration
Implement in-memory KV store with TTL (time-to-live) support. Classes: KeyValueStore (data map, expiration map), KVPair (key, value, expiration time), ExpirationManager (background cleanup). Operations: set(key, value, ttl), get(key) returns null if expired, delete(key), exists(key). Expiration handling: lazy deletion (check on access) or background thread (periodic cleanup). Data structures: HashMap for O(1) access, separate TreeMap for expiration times to efficiently find expired keys. Features: atomic operations, cache statistics, optional persistence to disk, LRU eviction when memory full, update extends TTL. Concurrency: thread-safe with minimal locking. Background cleanup: efficient scanning of expired entries without checking all keys. Comparison with Redis and Memcached.
Q30. Design a Logger System
Build multi-level logging framework with filtering and output destinations. Classes: Logger (logs messages with levels), LogLevel (DEBUG, INFO, WARNING, ERROR, FATAL), LogFormatter (formats message with timestamp, level, context), LogWriter (writes to console, file, network). Features: different log levels with severity filtering, multiple handlers (file, console, network sink), asynchronous logging (buffer messages, batch write), log rotation (size-based, time-based), configuration reload without restart. Message format: timestamp, level, thread ID, class/method, message. Performance: non-blocking logging with queue. Internationalization: multi-language error messages. Sampling: log only percentage of high-volume messages. Metrics: logging rate, bytes written, handler errors.
Q31. Design a Notification System
Create system sending notifications across multiple channels (email, SMS, push, in-app). Classes: Notification (recipient, message, type), NotificationService (manager), NotificationChannel (interface), EmailChannel, SMSChannel, PushChannel, InAppChannel. Delivery guarantees: at-least-once (retry on failure) or exactly-once (deduplicate). Queue-based: enqueue notifications, background workers process by channel. Retry logic: exponential backoff, max retries. Templating: predefined message templates with variable substitution. User preferences: opt-in/out per channel, frequency limits, quiet hours. Features: scheduling (send at specific time), batching, priority levels, delivery status tracking, analytics. Persistence: store sent notifications for audit trail. Idempotency: unique notification ID prevents duplicate sends on retry.
Q32. Design an Inventory Management System
Manage product inventory across warehouse locations. Classes: Product (SKU, name, description), Warehouse (location, stock levels), Stock (product, warehouse, quantity, reserved), Order (order ID, items, source warehouse, status), InventoryManager (track stock, fulfill orders). Operations: add product, check availability at location, reserve stock for order, deduct on shipment, restock. Stock management: physical quantity vs available (available = physical – reserved). Allocation logic: find warehouse with sufficient stock, prefer closest to customer. Overselling prevention: check availability before confirming order. Low stock alerts: trigger reorder when stock below threshold. Features: stock transfer between warehouses, backorder management, serial number tracking, expiration dates (FIFO). Concurrency: prevent race conditions in stock updates. Reporting: stock levels, movement history, slow-moving inventory.
Q33. Design a URL Shortener
Create service shortening long URLs (like bit.ly, TinyURL). Classes: URLMapping (long URL, short code, creation time, expiration), ShortenedURL (short code, original URL, stats), AnalyticsTracker (clicks, geographic data, referrer), URLShortener (generation and retrieval). Encoding: convert ID to base62 (alphanumeric) for short codes. Collision handling: check existing mapping, try different encoding. Reverse lookup: map short code to original URL. Features: custom short codes, expiration dates, click tracking, geolocation analytics, QR code generation. Rate limiting: prevent abuse of shortening API. Redirect: 301 (permanent) vs 302 (temporary) redirects. Scalability: distributed systems with consistent hashing. Database: store mappings with index on short code. TTL: delete expired entries periodically. Privacy: obfuscate sequential IDs, random generation.
Q34. Design a Rate Limiter
Implement rate limiting to prevent API abuse. Algorithms: Token Bucket (accumulate tokens, consume per request), Sliding Window (count requests in time window), Leaky Bucket (constant outflow rate). Classes: RateLimiter (bucket/window, capacity, refill rate), User (ID, limits), Request (user, timestamp, resource). Token Bucket: starts full, refill at rate, request consumes token (accept if available else reject). Sliding Window: count requests in window, reject if exceeds limit. Per-user limits: different limits for different tiers. Features: distributed rate limiting (across multiple servers), graceful degradation (queue requests), rate limit headers (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset), burst allowance. Policies: hard limits, soft limits with warnings. Monitoring: rejection rate, hit rate, performance impact.
Q1. Hotel Search System
Design a scalable Hotel Search System to display prices for check-in and check-out dates, with currency formatting and tax breakdowns.
Key Points Discussed:
- Service Design (Search, Pricing, Currency)
- Database Schema (Hotel, Price, Room)
- Scalability (Caching, Indexing)
Q2. Video Streaming Platform (Feature Design)
Asked in Hiring Manager round — design a simple video streaming functionality focusing on video fetching and user sessions.
Focus:
- Distributed storage for video
- Caching
- Load balancing
Q3. Design a Scalable Web Crawler Architecture
Design a distributed web crawling system that processes millions of URLs. Components: URL frontier (using distributed queues like Kafka), crawler workers (horizontally scalable), DNS resolver service, duplicate URL detection (using bloom filters or distributed HyperLogLog), content storage (distributed databases), and result indexing. Handle rate limiting per domain, respect robots.txt, and manage crawling politeness policies. Use master-worker or peer-to-peer architecture for scalability.
Q4. Design a High-Traffic E-commerce Platform
Design an architecture for an e-commerce system like Expedia handling millions of concurrent users. Components: CDN for static content, API Gateway for routing, Microservices (product catalog, cart, payment, booking), load balancers, caching layers (Redis), distributed databases (write to primary, read from replicas), message queues (Kafka) for asynchronous operations, and search engines (Elasticsearch). Handle inventory synchronization, real-time pricing updates, and transaction consistency.
Q5. Design a Hotel/Travel Booking System
Architect a booking platform similar to Expedia. Core components: Inventory management service (room availability, pricing), Booking service with transaction support, Payment gateway integration, Notification service (email, SMS), Search service (using Elasticsearch for fast queries), Recommendation engine, User management, and Analytics pipeline. Handle concurrent bookings, overbooking prevention, and cancellation workflows with distributed transactions or saga pattern.
Q6. Design a Distributed Search Service
Create a search system handling billions of documents. Use Elasticsearch cluster with multiple nodes, implementing sharding for horizontal scaling, replication for high availability, and indexing pipelines. Design indexing components for data ingestion, analyzers for text processing, and query engines supporting various search types (full-text, range, faceting). Include caching layers and query optimization.
Q7. Design a Real-time Analytics Platform
Build a system for processing and analyzing high-volume streaming data. Components: Data ingestion (Kafka), Stream processing (Apache Flink/Spark Streaming), Data warehouse (data lakes on S3/HDFS), OLAP databases (Druid, ClickHouse), visualization dashboards, and alerting systems. Support real-time aggregations, historical analysis, and complex queries on massive datasets.
Q8. Design a Distributed Messaging System
Architect a message queue system like Kafka handling millions of messages per second. Components: Brokers (message storage and replication), Zookeeper/Consensus for leader election, producers, consumers with offset management, and partitioning strategy for parallel processing. Ensure high availability, data durability, and exactly-once delivery semantics.
Q9. Design a Content Recommendation System
Build a recommendation engine for travel/products. Use collaborative filtering, content-based filtering, and hybrid approaches. Components: User-item interaction pipeline, feature engineering, model training infrastructure, real-time prediction service, A/B testing framework, and feedback loop for continuous improvement. Scale to millions of users and items.
Q10. Design a Distributed Caching System
Create a caching layer (like Redis Cluster) supporting millions of concurrent requests. Handle consistent hashing for key distribution, replication for fault tolerance, eviction policies (LRU), TTL management, and cache invalidation strategies. Support atomic operations, transactions, and Lua scripting for complex operations.
Q11. Design a Rate Limiting System at Scale
Architect a globally distributed rate limiting service. Use token bucket or leaky bucket algorithms distributed across multiple nodes. Components: Node local counters with synchronization, distributed consensus for consistency, dashboard for monitoring, and gradual degradation under extreme load. Support per-user, per-IP, and per-endpoint rate limiting.
Q12. Design a Distributed Transaction System
Build a system ensuring ACID properties across distributed services. Implement 2-phase commit for synchronous transactions or saga pattern for asynchronous distributed transactions. Handle failure recovery, rollback mechanisms, and maintaining consistency in eventually consistent systems. Support idempotent operations for safe retries.
Q13. Design Expedia: Hotel & Flight Booking Platform
Architect a global travel booking system handling millions of concurrent users searching and booking hotels, flights, car rentals. Components: Search service (Elasticsearch for fast queries with filters: price, ratings, location), Inventory service (hotel availability, room types, prices; flight seat availability, schedules), Booking service (transaction handling, payment processing, confirmation), User service (authentication, profiles, preferences), Recommendation engine (personalized suggestions based on history), Notification service (confirmation emails, updates), Analytics pipeline (user behavior tracking, conversion metrics). Database: write to primary database (relational for ACID transactions), read replicas for search queries. Caching: Redis for frequently searched routes/properties, CDN for static images. Message queue (Kafka) for asynchronous operations (sending notifications, updating analytics). Real-time inventory sync across multiple data centers. Surge pricing during peak seasons. Search: property filters (price range, amenities, reviews), sorting (relevance, price, rating), pagination. Booking workflow: reservation (holds inventory for 15 minutes), payment processing, confirmation. Payment processing: PCI compliance, fraud detection, multiple payment methods. Scalability: horizontal scaling of microservices, database sharding by geography/user, load balancing. Disaster recovery: multi-region replication, failover mechanisms.
Q14. Design a Real-Time Ride-Sharing Platform (Uber Scale)
Build distributed system for ride matching and management at scale. Core services: User service (driver/passenger profiles, authentication), Location service (real-time GPS tracking using Redis geohashing for spatial indexing), Matching service (intelligent driver-to-passenger matching using proximity, ratings, preferences), Trip service (manages active trips, routes, status), Payment service (fare calculation, surge pricing, payments), Rating service (user ratings and reviews), Notification service (real-time updates). Matching algorithm: geographic clustering (divide city into zones), find available drivers near passenger (Redis sorted set by distance), predict driver earnings for optimal incentives, surge pricing during high demand. Real-time updates: WebSockets for live location tracking, ETA calculation, push notifications for acceptance/cancellation. Database: NoSQL for driver locations (frequent updates), relational for user/trip data. Caching: cache driver availability in specific zones, fare matrices. Message queue: async notifications, analytics events. Concurrency: handle simultaneous ride requests in same zone without conflicts. Fault tolerance: driver offline handling, connection loss recovery. Payment: at-trip-end processing with fraud detection. Scalability: consistent hashing for driver sharding, multi-region expansion.
Q15. Design YouTube: Video Streaming Platform
Create scalable platform for video uploading, processing, and streaming. Upload pipeline: receive video, validate format, queue for processing, generate thumbnail. Processing: transcode to multiple resolutions/codecs (480p, 720p, 1080p, 4K), create adaptive bitrate streams (DASH/HLS for quality selection), extract metadata. Storage: videos stored in distributed object storage (S3, GCS) across regions, replicated for redundancy. CDN integration: cache videos at edge locations, serve from nearest CDN node. Streaming: adaptive bitrate selection based on bandwidth, buffer availability. Search service: Elasticsearch index videos by title/description/tags, autocomplete. Recommendation engine: collaborative filtering, content-based filtering combining watch history, likes, user demographics. Database: NoSQL for video metadata (high write throughput), relational for user data. Messaging: queue for video processing jobs, encoding farm of servers. Monitoring: playback metrics (buffering events, quality selection), upload success rates. Scalability: sharded databases by user/video, multi-region replicas. Live streaming: real-time encoding, low-latency delivery (RTMP ingestion, HLS output). Analytics: track views, engagement, recommendations impact.
Q16. Design WhatsApp: Real-Time Messaging Platform
Build end-to-end encrypted messaging system with groups, files, status, calls. Message delivery: Web Sockets for real-time communication, message queue (Kafka) for durability if recipient offline. Encryption: end-to-end encryption with keys exchanged using Signal protocol, messages encrypted on client before transmission. Storage: messages stored in database only for offline delivery, deleted after delivery to ensure privacy. User service: manage accounts, phone number verification, status (online/offline). Group management: add/remove members, admin roles, group settings. Presence service: track online status, update broadcast to contacts using pub-sub. File transfer: upload files to object storage, generate encrypted links, download via CDN. Database: NoSQL for message queues (fast writes), relational for user relationships. Caching: cache user status, group membership. Consistency: eventual consistency for presence, strong consistency for messages. Scalability: partition users by geography, message routing based on user location, connection pooling. Media: images/videos uploaded to CDN, indexed by hash for deduplication. Calls: WebRTC for peer-to-peer communication, TURN servers for NAT traversal. Monitoring: message delivery rate, latency SLA (99th percentile < 100ms).
Q17. Design Twitter/X: Social Media Feed
Create platform for posting, following, and real-time feed distribution. Components: Post service (create, delete, quote tweets), User service (profiles, follow relationships), Feed service (personalize and rank feed), Engagement service (likes, retweets, replies), Search service, Analytics. Feed generation: two approaches – pull (user requests, aggregate followed user posts) or push (precompute feed, update on new post). Push model: maintain feed cache for each user in Redis, when user posts, push to all followers’ feeds (scalability issue with celebrities). Hybrid: celebrities use pull model, regular users push. Ranking: algorithm combines recency, engagement (likes/retweets), user interest match, diversity. Database: NoSQL for posts (high throughput), relational for user relationships. Caching: Redis for timeline cache, frequent posts, trending topics. Indexing: Elasticsearch for full-text search on tweets, hashtags. Consistency: eventual consistency for feed (accept slight delay), strong consistency for follower counts. Scalability: sharded storage by user hash, timeline cache by user, search replicas. Trending: analyze tweets in real-time, maintain trending list with 1-minute granularity. Replication: replicate across regions, handle network partition. Monitoring: feed staleness, engagement metrics, latency percentiles.
Q18. Design Netflix: Video Streaming at Scale
Architect system streaming video to millions of users with adaptive quality. Components: Content service (catalog, metadata), Encoding service (process videos into multiple resolutions), CDN (distributed cache), Recommendation engine (personalization), User service (profiles, history), Payment/Billing, Analytics. Video encoding: original content in 4K, transcode to 1080p, 720p, 480p, 360p, 240p using GPU accelerators, generate subtitles in multiple languages. Storage: master copy in cloud storage, replicated across regions. Delivery: push content to CDN edge caches in advance, based on popularity predictions, peaking patterns. Streaming protocol: DASH/HLS, client-side adaptive bitrate selection (ABSD algorithm), handles network fluctuations, device capabilities. Recommendation: machine learning model ingesting view history, ratings, similar user preferences, content similarity, trending. Caching strategy: popular content cached at all edges, regional content at regional CDN nodes. Database: NoSQL for user history (sequential writes), relational for subscription/billing. Payment: recurring subscription billing, fraud detection, chargebacks. Quality of Experience (QoE): metrics for buffering ratio, startup delay, bitrate switches, monitoring playback interruptions. Scalability: multi-region deployment, CDN with 200+ nodes worldwide. Monitoring: real-time dashboards for stream quality, user engagement, system health. Content protection: DRM (Digital Rights Management), token-based access control.
Q19. Design Google Search: Search Engine Architecture
Build system indexing web, processing queries, ranking results. Components: Web crawler (crawl websites), Indexer (build inverted index), Query processor (parse and process), Ranking engine (PageRank and beyond), Results service. Crawling: distributed crawlers respecting robots.txt, DNS resolution, handle redirects, extract links, queue-based (Kafka) crawling schedule prioritizing fresh content. Indexing: build inverted index (term → documents), store term statistics (TF-IDF), handle sharding across many machines (64-way). Query processing: tokenization, spell checking, synonyms, parsing queries into terms, handle special queries (maps, weather, calculator). Ranking: PageRank (link analysis), relevance (TF-IDF, BM25), freshness, user signals (CTR), personalization (search history, location). Storage: distributed file system (GFS) for index shards, cache hot queries in memory. Database: NoSQL for query logs, user click data. Machine learning: ranking model trained on click-through data, neural networks. Scalability: index sharding by term range, query distribution to shards, result merging. Latency: target < 200ms p99, caching of frequent queries. Freshness: crawl frequency by page importance, real-time indexing for news. Quality: search quality metrics (precision, recall), A/B testing for algorithm changes. Monitoring: query latency, index freshness, ranking model performance.
Q20. Design Slack: Enterprise Communication Platform
Create platform for team messaging, file sharing, integration with external tools. Components: Messaging service (real-time chat), User/Team service (authentication, authorization, organization), Channel service (topic-based conversations), File service (upload, storage, sharing), Integration service (webhooks, APIs), Notification service, Search service. Messaging: WebSocket connections for real-time delivery, message queue for offline users, per-channel message history. Channel types: public (browsable, anyone join), private (invite-only), direct messages. File sharing: upload to object storage, generate preview/thumbnails, virus scanning, access control per file. Integrations: webhooks for incoming messages from external services (GitHub, Jira), bots for automations, API for third-party apps. Search: full-text search on messages (Elasticsearch) and files, search results filtered by permission. Presence: track user online status, display in UI. Notification: desktop, mobile, email notifications (batched to reduce spam), Do Not Disturb hours. Permissions: role-based access control (admin, member, guest), workspace-level and channel-level permissions. Database: NoSQL for messages (sequential writes per channel), relational for users/teams. Caching: active channels and users cached in Redis, presence in memory. Scalability: channel sharding by ID, WebSocket connection handling with load balancers. Compliance: data retention, HIPAA/GDPR compliance for enterprise customers. Analytics: track usage (messages, files), team engagement metrics. Disaster recovery: message replication across data centers, backup to cold storage.
Q22. Design Amazon: E-Commerce Platform
Build scalable online shopping platform managing product catalog, shopping carts, orders, payments. Components: Product service (catalog, search, recommendations), Cart service (manage shopping carts), Order service (manage orders, fulfillment), Payment service (process payments), Inventory service (track stock levels), Shipping service (logistics, tracking), User service (accounts, addresses, preferences), Review/Rating service. Product search: Elasticsearch with filters (price, category, brand, ratings, availability), faceted search, autocomplete suggestions. Recommendation engine: collaborative filtering (users who bought similar items), content-based (product similarity), personalized homepage based on browsing/purchase history. Cart management: persistent across sessions, saved for later, item price changes, stock availability at checkout. Checkout flow: shopping cart → address selection → shipping method → payment → order confirmation. Payment processing: integrate multiple payment gateways (credit card, digital wallets), PCI compliance, fraud detection, retry logic. Inventory management: track warehouse stock levels, reserved inventory for orders, low stock alerts, reorder triggers. Order fulfillment: order routing to nearest fulfillment center, picking, packing, shipping label generation. Shipping: integrate with carriers (UPS, FedEx), real-time tracking, delivery estimates. Database: NoSQL for product catalog (read-heavy), relational for orders (transactional), separate analytics database. Caching: product details cached in CDN, popular items in Redis, user preferences. Scalability: product sharding by category, order service sharding by user or order date. Monitoring: order success rate, payment failure rate, inventory accuracy, shipment on-time delivery rate.
Q23. Design Airbnb: Property Rental Platform
Create system for listing properties, managing bookings, payments, reviews. Components: Listing service (host properties, photos, descriptions), Search service (search by location, dates, price), Booking service (reserve properties), Calendar service (manage availability), Payment service (host payouts), Review/Rating service, User service (hosts and guests). Listing: hosts create listing with photos, description, amenities, pricing, house rules. Search: index by location (geohash for location queries), filter by date availability, price range, property type, amenities. Availability: calendar per property, mark booked dates, handle cancellations. Booking: guest selects dates, checks availability, triggers payment, generates confirmation. Payment: guest pays Airbnb, Airbnb holds funds during stay, releases to host after checkout (minus fees). Reviews: guests and hosts rate each other after stay, impact trust scores. Dispute resolution: handle cancellation disputes, damage claims, refunds. Database: NoSQL for listing data (read-heavy searches), relational for bookings (transactional), search index (Elasticsearch). Caching: popular listings cached, availability calendar in Redis. Scalability: geographic sharding (North America, Europe, Asia regions), search replicas. Fraud detection: detect suspicious bookings, cancel if needed, host/guest verification. Analytics: track bookings, cancellations, revenue, user acquisition funnel. Consistency: booking consistency critical (prevent double-booking), strong consistency with transactions. Trust: verified ID, phone verification, first-time booking approval by hosts.
Q24. Design Dropbox: Cloud Storage System
Architect scalable file storage, sync, and collaboration platform. Components: Auth service (authentication), File service (upload, download, delete), Sync service (sync files across devices), Sharing service (share files/folders with others), Database (metadata), Object storage (file content). File upload: client splits file into chunks (4MB), uploads chunks, computes hash, deduplicates by content hash (same file across users stored once). Versioning: maintain multiple versions of files, allow rollback. Sync: monitor local changes, upload to server, download remote changes, handle conflicts (keep both versions). Sharing: generate share links with expiration, set permissions (view-only, edit, comment), revoke access. Collaboration: real-time collaboration on documents (like Google Docs), operational transformation for conflict resolution. Database: metadata stored in relational DB (hierarchical structure), NoSQL for file attributes. Object storage: distributed blob storage (S3-like), replicated across regions, erasure coding for efficiency. Caching: metadata cache, popular files cached at edge. Scalability: user sharding by hash, file sharding by hash, independent auth/sync/sharing services. Consistency: strong consistency for metadata, eventual consistency for file content. Bandwidth optimization: compression, delta sync (send only changes), bandwidth throttling. Monitoring: storage utilization, sync latency, upload/download speeds.
Q25. Design Instagram: Photo Sharing Social Network
Build system for photo upload, feed distribution, messaging, stories. Components: User service (profiles, authentication), Photo service (upload, processing), Feed service (timeline generation), Engagement service (likes, comments, follows), Messaging service (DMs), Stories service (temporary photos), Search service, Notification service. Photo upload: client uploads photo, resizing to multiple sizes (thumbnail, small, medium, large), generate AVIF/WebP for modern browsers, store in CDN. Feed: followers see user’s photos, timeline combines followed users’ photos ranked by recency and engagement. Comments and likes: real-time updates using WebSockets. Messaging: direct messages between users, encrypted, read receipts. Stories: photos visible for 24 hours, view tracking, analytics on story views. Search: search users, hashtags, locations using Elasticsearch. Hashtag indexing: track trending hashtags, search performance. Notifications: like/comment notifications, follow notifications. Caching: user timeline in Redis, popular photos, user profiles. Database: NoSQL for photos metadata, relational for relationships. Scalability: photo sharding by user, feed generation parallelized. Personalization: machine learning ranking feed items based on engagement patterns. Analytics: track post reach, engagement rate, story performance, user growth. Monitoring: photo upload latency, feed generation time, real-time message delivery.
Q26. Design a Distributed Transaction System (Payment Processing)
Build reliable system processing financial transactions with ACID guarantees across services. Components: Transaction coordinator (manages transaction flow), Payment service (processes payments), Account service (manages balances), Ledger service (audit trail), Settlement service (batch settlement), Fraud detection service. Two-phase commit protocol: prepare phase (validate all services), commit phase (finalize transaction). Alternatively, saga pattern: choreography (services listen to events) or orchestration (coordinator directs each service). Idempotency: unique transaction IDs prevent duplicate processing on retries. Consistency: strong consistency for financial transactions (ACID requirements). Durability: transaction logs persist before committing, recovery from failure. Ledger: immutable append-only log of all transactions for audit. Settlement: batch processing of transactions, reconciliation with banks. Fraud detection: machine learning model detecting suspicious patterns (unusual amounts, locations, velocity), real-time alerts. Monitoring: transaction success rate, latency (p99 < 500ms), failure investigation. Scalability: transaction sharding by user/account. Compliance: PCI-DSS for payment handling, SOX for financial reporting.
Q27. Design LinkedIn: Professional Network
Create platform for professional networking, job posting, messaging. Components: User service (profiles, education, experience), Connection service (manage connections), Post/Activity service (updates, articles), Job service (job listings, applications), Messaging service (InMail), Search service (full-text search), Recommendation service (people you may know, job recommendations). Profile: user education, work experience, skills, endorsements, recommendations. Connections: send/accept connection requests, track relationship graph (first, second, third degree). Feed: show posts from connections, articles from followed publishers, job updates. Job listings: companies post jobs, users apply, recruiters message candidates. Recommendation engine: suggest connections (mutual friends, same school/company), job recommendations (skill match, experience level). Search: search people, jobs, companies, articles (Elasticsearch). Messaging: InMail for job recruiter messages, direct messaging. Database: graph database for connection relationships (efficient traversals), relational for user data, NoSQL for posts. Caching: user profiles, recommendation cache. Analytics: job application pipeline, user engagement, network growth. Scalability: user sharding, connection graph partitioning. Compliance: privacy (control profile visibility), GDPR. Monitoring: message delivery, feed generation latency, recommendation click-through rate.
Q28. Design Twitch: Live Streaming Platform
Build system for live video streaming, chat, and interactive features. Components: Stream ingestion (RTMP/HLS ingestion), Transcoding service (multiple bitrates), Streaming delivery (CDN distribution), Chat service (real-time chat), User service (streamers and viewers), Moderation service. Stream ingestion: streamer uses OBS/Streamlabs to broadcast, RTMP server receives stream, validates encoder settings. Transcoding: encode stream to multiple resolutions/bitrates (1080p60, 720p60, 480p, 360p) on GPUs, generate HLS segments (3-second segments). Delivery: HLS manifest updated with new segments, viewers download segments from CDN edges, adaptive bitrate selection based on bandwidth. Chat: WebSocket connections for real-time messages, message filtering for spam/moderation, emote rendering. Viewer experience: join stream, watch live, chat, follow streamer, subscribe (paid channel access). Features: raids (send viewers to another stream), host (embed stream on channel), clips (extract interesting moments). Database: NoSQL for chat messages (high write throughput), relational for user/stream data. Caching: active streams, top streamers, chat messages. Scalability: ingest service sharding per region, transcoding farm with auto-scaling, chat servers by stream. Monitoring: stream uptime, viewer count, transcoding latency, chat latency, concurrent viewers. Quality: video quality metrics (bitrate, resolution, frame rate), audio synchronization.
Q29. Design Salesforce: CRM Platform
Create multi-tenant cloud platform for managing customer relationships. Components: Authentication/Authorization (tenant isolation), Data service (manage customer data), Business logic service (opportunities, deals, forecasts), Integration service (connect external systems), Analytics service (dashboards, reports), Workflow engine (automation). Multi-tenancy: each customer has own data, strict isolation, separate databases per customer or logical isolation. Data model: accounts (companies), contacts (people), opportunities (deals), activities (calls/emails), custom objects. Workflow automation: trigger actions based on conditions (send email when deal stage changes, create task, update fields). Reports and dashboards: query builder for custom reports, drag-drop dashboard builder, scheduled reports via email. Integration: connect to Slack, Jira, ERP systems via APIs, data synchronization. Customization: custom fields, custom objects, custom validation rules, extension through Apex code. Scalability: multi-tenancy allows resource sharing, still need per-customer sharding for data. Consistency: transactional for operations on single customer, eventual consistency for cross-tenant analytics. Security: role-based access control, field-level security, encryption at rest and in transit. Monitoring: per-tenant resource usage, query performance, API rate limits. Compliance: HIPAA, GDPR, SOC 2. Licensing: different feature tiers (Essentials, Professional, Enterprise), seat-based pricing.
Q30. Design Google Maps: Navigation & Location Service
Build real-time mapping platform with directions, traffic, location services. Components: Map data (base map), Routing engine (calculate routes), Traffic service (real-time traffic data), Geocoding service (address to coordinates), Places service (search nearby places), Directions API (alternative routes), Navigation (turn-by-turn). Map data: topographic data (roads, buildings, parks), tile-based rendering, vector tiles for different zoom levels. Geocoding: convert address to latitude/longitude, reverse geocoding (coordinates to address), handle multiple addresses. Routing: calculate shortest path (Dijkstra, A* algorithms), consider real-time traffic, alternative routes with different criteria (fastest, shortest, avoid highways). Traffic: aggregate location data from phones (anonymized), model traffic patterns, predict future traffic, update users periodically. Directions API: return step-by-step directions, estimated time, distance, toll costs. Navigation: voice-guided turn-by-turn directions, re-route on traffic, lane guidance on highways. Places: search nearby restaurants/gas/hotels, ratings, hours, navigation to place. Scalability: map data sharded by geographic region (quadtree), routing replicas per region, traffic data aggregation pipeline. Caching: popular routes cached, tiles cached on client, traffic predictions cached. Real-time: traffic updates every 1-5 minutes, live location sharing between users. Accuracy: continuously improve maps from satellite imagery, user feedback, Street View. Privacy: anonymize location data, aggregate before storing.
Q31. Design Stripe: Payment Processing Platform
Create infrastructure for accepting payments at scale. Components: Payments API (charge cards, wallets), Webhooks (event notifications), Dashboard (manage account), Fraud detection, Settlement (fund transfers), Reporting. Payments API: simple integration, handle multiple payment methods (card, bank transfer, wallets), recurring charges for subscriptions. PCI compliance: Stripe handles sensitive data, merchants only receive tokens. Card processing: validate card, tokenize, send to payment networks (Visa/MasterCard/Amex), handle 3D Secure. Webhooks: notify merchant of payment events (charge.succeeded, charge.failed), retry failed webhooks, idempotent webhook processing. Dashboard: view transactions, manage refunds, manage customers, payment analytics. Fraud detection: machine learning model detecting fraud (card not present, high-risk country, unusual amount), challenge with 3D Secure, manual review. Settlement: batch process transactions daily, fund merchant account within 1-2 days, accounting reconciliation. Reporting: transaction reports, revenue reports, tax reports, PCI compliance documentation. Scalability: handle millions of transactions daily, multi-region processing, redundancy for high availability. Rate limiting: per-merchant rate limits to prevent abuse. Database: financial transactions in relational DB (ACID), event log in append-only store. Monitoring: payment success rate, fraud rate, settlement timing. Compliance: PCI-DSS level 1 (highest), GDPR, various payment regulations by country.
Q32. Design Medium: Content Publishing Platform
Build platform for writers to publish articles and readers to discover content. Components: User service (profiles, followers), Article service (publish, edit), Discovery service (recommendations, trending), Engagement service (claps, highlights, responses), Payment service (subscription, payouts), Search service. Article publishing: markdown editor, publish workflow, version history, scheduled publishing. Discovery: homepage feeds personalized by interests, topics, publications (aggregated feeds from writers), trending articles, recommendations. Engagement: readers highlight text, write responses to articles, clap (like) articles, follow writers. Monetization: paywall (premium articles), subscription model ($5/month for unlimited), payout to writers from subscription pool. Search: full-text search of articles, filters by topic, publication, author. Database: NoSQL for articles (immutable published versions, mutable drafts), relational for user data. Caching: popular articles, trending list, user feed. Analytics: read time, engagement metrics, writer performance. Scalability: article sharding by writer, feed generation distributed. Quality: editorial review process for featured articles, community guidelines enforcement. Recommendation algorithm: content-based (similar topics), collaborative filtering (users reading similar content), user interests. Monitoring: publishing latency, feed generation time, reader engagement metrics.
Q32. Design a Food Delivery Platform (DoorDash/Zomato)
Create system connecting restaurants, delivery drivers, and customers. Components: Restaurant service (menu, orders), Order service (manage orders), Driver service (availability, location), Matching service (assign driver to order), Tracking service (real-time location), Payment service, Rating service, Notification service. Order flow: customer browses restaurants, selects items, checkout, payment, order sent to restaurant, driver assigned, driver picks up order, customer tracks delivery. Driver matching: available drivers near restaurant, estimated delivery time, assign closest driver or by rating. Real-time tracking: driver location updated, customer sees ETA, notifications on delivery progress. Surge pricing: peak hours (lunch, dinner) increase delivery fees and incentivize drivers. Restaurant management: update menu, see incoming orders, mark order ready for pickup, handle cancellations. Driver app: receive orders, navigate to restaurant then customer, complete delivery. Payment: split between customer payment, restaurant payment, Zomato commission, driver payment. Ratings: customer rates restaurant and driver, driver rates customer (tip, cleanliness of address), impacts future matching. Scalability: sharded by geography (city), matching service per city, order queuing with load balancing. Consistency: avoid double assignment (two drivers accepting same order), use distributed locks. Monitoring: delivery time from order to delivery, acceptance rate, cancellation rate, customer satisfaction. Optimization: predict demand for pre-positioning drivers, dynamically adjust prices, restaurant prep time accuracy.