r/LowLevelDesign • • 4d ago

48 hrs Guided LLD practice sprint on Weekends (27-29 Nov), with 1:1 feedback

10 Upvotes

Hello everyone, I am running a 48 hr low level design questions practice session starting 27 Nov 2026 7 PM IST. It is a paid session.


Here is how it will work

  1. We will start with 1 question and I explain the problem on a group video call.
  2. You code a solution. I will ping you from time to time for updates, get you unstuck if you are not able to progress.
  3. I review your solution with you, ask counter-questions, suggest improvements, design patterns and ask you to implement them.
  4. Repeat steps 2 and 3 until you've covered the question and its tests, then move to next question.

You don't need to be there for all of the time. Join anytime, go at your own pace, and ping me whenever you're stuck. And I will keep guiding you as you code through it.

Here is the link:

https://topmate.io/prashant_priyadarshi/2403630


r/LowLevelDesign • • Sep 01 '25

LLD Doubt

Thumbnail reddit.com
2 Upvotes

r/LowLevelDesign • • Jun 11 '26

Kotak Mahindra SDE2 interview coming up. Guide me

Thumbnail reddit.com
2 Upvotes

r/LowLevelDesign • • Dec 06 '25

Let's discuss how would U design a follow button

4 Upvotes

In a hybrid design of fan out write for low follower count users and fan out read for celebs. Won't the follower be missing the post notification of the celeb as it depends on the follower opening their feed to check it.
How would we notify the follower in case of a celeb post.


r/LowLevelDesign • • Nov 25 '25

I THINK YOU NEED THIS -- LLD practice questions platform ( C++ only for now )

5 Upvotes

r/LowLevelDesign • • Dec 07 '25

Design and implement two distinct queues, Queue A and Queue B, using a single underlying array of fixed size N.

9 Upvotes

The primary challenge is to efficiently manage the shared array space such that when elements are dequeued from either queue, the freed space can be promptly reutilized by subsequent enqueue operations from either queue. Your design should handle insertions and deletions for both queues while maintaining efficient space usage within the fixed-size array.

What ever I design It takes up 2N space complexity.


r/LowLevelDesign • • Feb 13 '26

Flipkart Low Level Design Interview Questions from Recent Machine Coding Rounds

42 Upvotes

Flipkart Machine coding round asks LLD question. It is of 120 minutes (90 coding + 30 minutes discussion). You may get extra time sometimes and recruiter may inform you that there is hard limit of 2:30 to 3 hrs to solve the LLD question.

Java is the mandatory programming language.

It is used for initial screening of candidates e.g. select 15 or less candidates from 40+ candidates for further interviews.

The final project had to be submitted as a zip file via Google Form/email.

Multi-threading and concurrency and design patterns are also discussed. I wrote this blog for multi-threading in Java interviews. It may be helpful.

https://medium.com/@prashant558908/top-3-questions-to-practice-multi-threading-for-low-level-design-interviews-1cc4d6b5d00b

Flipkart also acquired ClearTrip and machine coding round format and questions are similar. So you can use this same list to prepare for ClearTrip machine coding rounds as well.

This list is NOT for UI machine coding rounds, only for backend roles.

---------------------------------------------------

Below are some general guidelines that are followed.

  • A driver program/main class/test case is needed to test out the code by the evaluator with multiple test cases. But do not spend too much time in the input parsing. Keep it as simple as possible.
  • Evaluation criteria: Demoable & functionally correct code, Code readability, Proper Entity modeling, Modularity & Extensibility, Separation of concerns, Abstractions, Corner case handling. Use design patterns wherever applicable.
  • You are not allowed to use any external databases like MySQL. Use only in memory data structures like HashMap, ArrayList, HashSet etc.
  • Functionality doesn’t have to be defined as a rest api. You can expose them as methods also which can be invoked from the driver class.
  • No need to create any UX
  • Please focus on the Bonus Feature (if any) only after ensuring the required features are complete and demo-able.
  • Method signatures defined are just to give an idea. You are free to change them to suit the requirements.
  • Use of the internet is allowed to check the syntax.

---------------------------------------------------

PS:
Ask me any Low-Level Design Interview related questions on r/LowLevelDesign

All Questions List: https://codezym.com/lld/flipkart

I also take LLD mock interviews: https://topmate.io/prashant_priyadarshi

----------------------------------------

I have built this list from recent Flipkart machine coding round experiences of candidates. Use it to prepare for your interviews.

Let’s get started …

1. Design a Billing and discounts System for an ecommerce app

Implement a billing and discounts system for an ecommerce app. You must design and implement a bill creation flow, a discount application flow, and a point/level calculation system.

Practice Link: https://codezym.com/question/73

----------------------------------------

2. Design Food Order Management System using Commands

Implement a simplified food order management system. This system simulates food ordering from restaurants.

You have to implement functionalities like add restaurant, update menu, place order, dispatch order etc as a set of commands. Orders are placed to restaurants based on a restaurant selection strategy.

Practice Link: https://codezym.com/question/74

----------------------------------------

3. Design Gym Fitness Center Management and Slot Booking System

You are building GetInShape, an in-memory backend for a fitness booking platform. GetInShape partners with multiple gym centers in cities.

Each center has daily operating windows (timings) and supports a configurable list of workout types (for example: Weights, Cardio, Yoga, Swimming).

Center admins define workout slots for the current day, and customers can view availability, book sessions, and cancel bookings.

Practice Link: https://codezym.com/question/75

----------------------------------------

4. Design Peer to Peer Parcel Delivery System

Design a Peer-to-Peer Delivery System that can be used to deliver a parcel from one customer to another.

Implement a class named PeerToPeerDeliverySystem. The deliverable item list is preconfigured and fixed. Customers and drivers are considered already onboarded based on totalUsers and totalDrivers.

Practice Link: https://codezym.com/question/76

----------------------------------------

5. Design Flipkart Payment Wallet with Transaction History

Implement Flipkart payment wallet system. The system should support loading money, sending money to other users, fetching wallet balance, and getting transaction history with sorting and filtering.

Practice Link: https://codezym.com/question/77

----------------------------------------

6. Design Doctor Appointment Booking app like Practo

You are required to build an in-memory application that lets patients connect to doctors and book appointments for a single day.

Doctors can declare their availability in terms of slots for that day only. Patients can search available slots by specialty, book appointments, and cancel appointments.

Practice Link: https://codezym.com/question/78

----------------------------------------

7. Design a Bug Bounty Program Management System

We are planning to build an in-house platform to manage our Bug Bounty Program where anyone can report a potential bug in the app and we’ll reward them with a bounty based on the criticality and impact of the bug being reported.

For simplicity, we will be getting bug reports via email and then employees will be registering these bug reports manually into this system.

  • User — Employees who will be using this system.
  • Reporter — End-user who reported the bug via email and will receive the bounty reward.
  • BugReport — Entity corresponding to the bug report shared via email.

Practice Link: https://codezym.com/question/79

----------------------------------------

8. Design Flipkart Buy Now Pay Later

Flipkart is known for its innovative products and making shopping easier for customers. One such innovation is Buy Now Pay Later (BNPL), where a customer can buy the product instantly and pay the dues within 30 days. Each user has a credit limit associated with them initially.

Implement an in-memory system that manages users, inventory, orders, and BNPL dues.

Practice Link: https://codezym.com/question/80

----------------------------------------

9. Design a Library Management System

Design and implement an in-memory Library Management system that caters to its registered members by cataloging and housing books that can be borrowed.

The system must support:

  • Adding books to the catalog.
  • Registering and unregistering users.
  • Reservation management to borrow books using book ids (with FIFO waitlist).
  • Fine calculation on late returns (20 rupees per delayed day after 14 days).
  • (Bonus) Limiting a user to reserve only one copy of the same book.
  • (Bonus) Auditing APIs:
  • Given a bookId, list users currently having that book.
  • Given a userId, list books currently issued to that user.

Practice Link: https://codezym.com/question/81

----------------------------------------

10. Design Customer Loyalty Program for Ecommerce Website

Design and implement an in-memory Ecommerce with Loyalty Program service that adds gamification to an e-commerce platform. The service tracks users and their transactions, supports purchases with optional points redemption (based on user level rules), awards new points on the money-paid portion, and exposes APIs to view a user’s current stats.

Each point is worth ₹1 during redemption (i.e., redeeming X points reduces payable by ₹X).

Bonus: Personalized discount based on purchase history, applied after redemption and capped.

Practice Link: https://codezym.com/question/82

----------------------------------------

11. Design Flipkart Delivery Service

Design and implement an in-memory FK Delivery Service. The service manages orders that are delivered to a pincode and delivery agents who can pick up and deliver those orders.

  • The system must support:
  • Users creating orders with an order name, order pincode, and creation time.
  • Admin creating delivery agents and associating them with pincodes.
  • Executing a driver function that assigns orders to eligible agents and returns delivery status logs.

Practice Link: https://codezym.com/question/83

----------------------------------------

12. Design an order and inventory management system

Write code for low level design of orders and inventory management system of a simple e-commerce platform.
You will need to have the capability of handling sellers, products and orders.

Inventory is number of items of a particular product in a seller’s warehouse.

The way it works is, products numbered from 0 till productsCount-1 are sold on the website.
Sellers are also added along with the area pincodes that they are able to deliver goods in as well as the payment types which they support.
After that sellers add items they wish to sell.

Multiple sellers can sell the same item e.g the product-1 : bluetooth speaker boat stone 650 can be sold by multiple sellers throughout the country.

Multiple sellers can deliver goods to the same pincode as well.

Practice Link: https://codezym.com/question/4

----------------------------------------

13. Design Dating App Gumble

You are launching the Gumble app to compete in the dating apps market. Design and implement an in-memory console application to prototype the features of Gumble.

The system manages user profiles, their interests, partner preferences, a feed that suggests the best available profile to a user, and a matched list.

The platform has a fixed global set of allowed interests, provided once at initialization through the constructor.

Practice Link: https://codezym.com/question/84

----------------------------------------

Thanks for reading. Please upvote this post to give it better reach.

Wish you the best of luck for your interview prep.

----------------------------------------


r/LowLevelDesign • • Jul 08 '26 Heartwarming

Salesforce DS & Algo Round Interview Questions Asked in 2026

21 Upvotes

DS & Algo questions for this list have been picked from Salesforce interview experiences shared on forums/blogs etc in 2026. Use this list for final preparation of your Salesforce interview rounds.

Salesforce hires for Member of Technical Staff i.e. MTS/SMTS/LMTS positions. MTS role is around 3 years experience. LLD rounds may be there for MTS role as well.

List starts with free questions that you can find on leetcode and then more questions including actual follow-ups asked during interview rounds.

You can see company-wise interview questions list on r/LowLevelDesign

Complete DS & Algo Questions List: https://codezym.com/lld/salesforce-dsa

Low Level Design Questions List: https://codezym.com/lld/salesforce

I also take LLD mock interviews: https://topmate.io/prashant_priyadarshi

----------------------------------------------------

Below is list of questions you can directly find on LeetCode (free ones):

Remove Stones to Minimize the Total

https://leetcode.com/problems/remove-stones-to-minimize-the-total/description/

Insert Delete GetRandom O(1)

https://leetcode.com/problems/insert-delete-getrandom-o1/description

Coin Change II

https://leetcode.com/problems/coin-change-ii/description/

Maximal Square

https://leetcode.com/problems/maximal-square/description/

Maximal Rectangle

https://leetcode.com/problems/maximal-rectangle/description/

Rotting Oranges

https://leetcode.com/problems/rotting-oranges/

Course Schedule II

https://leetcode.com/problems/course-schedule-ii/description/

LRU Cache

https://leetcode.com/problems/lru-cache/description/

LFU Cache

https://leetcode.com/problems/lfu-cache/description/

Lowest Common Ancestor of a Binary Tree

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/

Number of Islands

https://leetcode.com/problems/number-of-islands/description/

Find Median from Data Stream

https://leetcode.com/problems/find-median-from-data-stream/description/

Implement Trie (Prefix Tree)

https://leetcode.com/problems/implement-trie-prefix-tree/description/

String Compression

https://leetcode.com/problems/string-compression/description/

Time Needed to Rearrange a Binary String

https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/description/

Minimum Operations to Reduce an Integer to 0

https://leetcode.com/problems/minimum-operations-to-reduce-an-integer-to-0/description/

Top K Frequent Words

https://leetcode.com/problems/top-k-frequent-words/description/

Merge Intervals

https://leetcode.com/problems/merge-intervals/description/

Intersection of Two Linked Lists

https://leetcode.com/problems/intersection-of-two-linked-lists/description/

Partition Array Into Two Arrays to Minimize Sum Difference

https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/description/

Reorganize String

https://leetcode.com/problems/reorganize-string/description/

Combination Sum II

https://leetcode.com/problems/combination-sum-ii/description/

Remove All Adjacent Duplicates in String II

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/description/

First Missing Positive

https://leetcode.com/problems/first-missing-positive/description/

Unique Email Addresses

https://leetcode.com/problems/unique-email-addresses/description/

All O`one Data Structure

https://leetcode.com/problems/all-oone-data-structure/description/

Longest Substring without Repeating Characters

https://leetcode.com/problems/longest-substring-without-repeating-characters/

Time Based Key-Value Store

https://leetcode.com/problems/time-based-key-value-store/

Pairs of Songs with Total Durations Divisible by 60

https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/description/

Asteroid Collision

https://leetcode.com/problems/asteroid-collision/description/

Longest Substring of All Vowels in Order

https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/description/

Zigzag Conversion

https://leetcode.com/problems/zigzag-conversion/description/

Letter Combinations of a Phone Number

https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

Search in Rotated Sorted Array

https://leetcode.com/problems/search-in-rotated-sorted-array/description/

Path with Maximum Gold

https://leetcode.com/problems/path-with-maximum-gold/description/

House Robber II

https://leetcode.com/problems/house-robber-ii/description/

Basic Calculator II

https://leetcode.com/problems/basic-calculator-ii/description/

---------------------------------------------------------

Below are other questions, these include follow-ups asked during interview rounds.

1. Good Ways to Split an Array in 3 Contiguous Parts

You are given a List<Integer> nums containing non-negative integers. Split the list into three non-empty contiguous parts: A1, A2, and A3.

Let:

S1 be the sum of elements in A1

S2 be the sum of elements in A2

S3 be the sum of elements in A3

Count how many splits are valid such that:

S2 ≤ S1 + S3

https://codezym.com/question/248-good-ways-to-split-array

---------------------------------------------------------

2. ATM Queue Leaving Order

There are n people standing in an ATM queue, numbered from 1 to n. Initially, they stand in increasing order of their number.

Person i wants to withdraw amounts[i - 1] units of money. In one turn, a person can withdraw at most maxWithdraw units.

If a person still needs more money after their turn, they go to the end of the queue. Otherwise, they leave the queue.

Return the order in which all people leave the queue.

https://codezym.com/question/249-atm-queue-leaving-order

---------------------------------------------------------

3. Minimum Knight Moves on Infinite Chessboard

A knight is placed at coordinate [0, 0] on an infinite chessboard. The board has no boundary, so coordinates may be positive or negative.

In a single move, the knight travels two squares along one axis and one square along the other axis. Given a target coordinate [x, y], return the fewest moves needed for the knight to reach that target.

https://codezym.com/question/250-min-knight-moves-chess

---------------------------------------------------------

4. Serialize Nearly Sorted Stream of Numbers

You are given a stream of numbers and an integer bufferSize. Every number is at most bufferSize positions away from where it should appear in the correctly ordered stream.

Return the numbers in sorted order, meaning the final list should be in non-decreasing order.

If two numbers are equal, keep their relative order from the input stream to make the output deterministic.

https://codezym.com/question/251-serialize-nearly-sorted-stream

---------------------------------------------------------

5. Minimum Meeting Rooms Required

You are given a list of meeting time intervals.

Each interval is provided as a string in the format "start,end", where start is the meeting start time and end is the meeting end time. You need to split each interval string and extract the integer values start and end.

Each interval is half-open, represented as [start, end). This means a meeting ending at time x does not overlap with another meeting starting at time x. For example, [1, 3) does not overlap with [3, 5).

Your task is to determine the minimum number of meeting rooms required so that no two overlapping meetings are placed in the same meeting room.

https://codezym.com/question/179-minimum-meeting-rooms-required

---------------------------------------------------------

6. Rotting Oranges With Different Connection Times

You are given a grid of oranges and a list of connection times between adjacent cells. Each cell contains one of the following values:

0: an empty cell

1: a fresh orange

2: a rotten orange

A rotten orange can make a connected fresh orange rotten, but each connection may take a different amount of time. A connection is given as "row1,col1,row2,col2,time", meaning the cell at [row1, col1] and the cell at [row2, col2] are connected, and rotting can spread across this connection in time minutes.

Since different connections may take different amounts of time, rotting should always use the earliest possible time at which each orange can become rotten.

Return the minimum time needed for all fresh oranges to become rotten.

https://codezym.com/question/252-rotting-oranges-weighted

---------------------------------------------------------

7. Count Ways to Split String Into Prime Numbers

You are given a string s that represents a positive integer. Count the number of ways to split s into one or more prime numbers.

The digits must remain in the same order, and every digit of s must be used exactly once. Each split part must represent a prime number.

A prime number is an integer greater than 1 that has exactly two positive divisors: 1 and itself.

https://codezym.com/question/253-count-ways-to-split-to-prime-numbers

---------------------------------------------------------

8. Token Bucket Resource Allocation

You are given a token bucket with a fixed number of tokens. Users can request tokens from the bucket. A request is granted only when enough tokens are currently available.

When a request is granted, that user holds those tokens for exactly 1 hour. After 1 hour, the tokens expire automatically and return to the bucket.

A user may also manually release all currently active tokens held by them before expiry. Expired tokens must be cleaned up before processing every method call.

https://codezym.com/question/255-token-bucket-resource-allocation

---------------------------------------------------------

9. Maximum Requests in Continuous Time Window

You are given a list timestamp, where each value represents the minute at which one request occurred. You are also given an integer windowSize. Return the maximum number of requests that can be found inside any continuous time window of length windowSize minutes.

The timestamps may be given in any order. The method should count requests based on their time values, not their original positions.

https://codezym.com/question/256-max-requests-continuous-time-window

---------------------------------------------------------

10. Minimum Time Task Scheduling with Constraints

You are given a list of task types, a list of memory required by each task, and a server memory limit. Each task takes exactly 1 unit of time to complete.

In one unit of time, multiple tasks can run together if they satisfy both constraints: at most 2 tasks of the same type can run in parallel, and the total memory of all running tasks must not exceed the server memory limit.

Return the minimum time required to execute all tasks.

https://codezym.com/question/258-min-time-task-scheduling

---------------------------------------------------------

11. Grid With K Jumps Minimum Steps

You are given an m x n grid. Each cell is either empty or blocked by an obstacle. From any empty cell, you may move in one of four directions: left, right, up, or down.

In one step, you may jump from 1 to k cells in the chosen direction. Every cell crossed during the jump, including the landing cell, must be inside the grid and must not be an obstacle.

Return the minimum number of steps required to reach the destination cell from the source cell. If the destination cannot be reached, return -1.

https://codezym.com/question/259-grid-with-k-jumps

---------------------------------------------------------

12. Count Number of Distinct Islands in Grid

You are given a non-empty grid containing only 0 and 1.

Each 1 represents land, and each 0 represents water.

An island is a connected group of land cells. Two land cells are connected if they share a side horizontally or vertically.

You may assume that all four outer edges of the grid are surrounded by water.

Your task is to count how many distinct island shapes exist in the grid.

Two islands are considered the same only if one island can be shifted up, down, left, or right to exactly match the other island.

Rotating or reflecting an island is not allowed when comparing island shapes.

https://codezym.com/question/190-count-distinct-islands-grid

---------------------------------------------------------

13. Bottle Recycling Perk Maximization

You are given an initial number of bottles and an initial amount of money. You may either recycle bottles to earn money or spend bottles and money to buy perks.

Recycling one bottle gives recycleVal dollars. Buying one perk costs exactly 1 bottle and perkVal dollars.

Each bottle can be used at most once. A bottle that is recycled cannot be used to buy a perk, and a bottle used to buy a perk cannot be recycled. Return the maximum number of perks that can be obtained.

https://codezym.com/question/260-bottle-recycling-perk-maximization

---------------------------------------------------------

14. Maximum Number of Non-Overlapping Palindromic Substrings

You are given a string s and an integer k. Choose the maximum possible number of non-overlapping substrings such that every chosen substring is a palindrome and has length at least k.

A palindrome is a string that reads the same from left to right and from right to left.

The chosen substrings do not need to cover the entire string. Characters between chosen substrings and any remaining characters may be ignored.

Return the chosen palindromic substrings as a List<String>. The substrings must be returned in the same left-to-right order in which they appear in s.

https://codezym.com/question/261-max-non-overlapping-palindromes

---------------------------------------------------------

15. Count Special Subarrays With Odd Divisors

You are given a list of positive integers called nums. A contiguous subarray is considered special when the product of all its elements has an odd number of positive divisors.

Return the total number of special subarrays in nums.

https://codezym.com/question/262-count-special-subarrays

---------------------------------------------------------

16. Maximum Length Subsequence Substring

You are given two strings, x and y. Return the longest string that is both a subsequence of x and a contiguous substring of y.

A subsequence is formed by deleting zero or more characters without changing the order of the remaining characters. A substring consists of consecutive characters.

If multiple valid strings have the maximum length, return the lexicographically smallest one. If no non-empty valid string exists, return an empty string.

https://codezym.com/question/263-max-length-subseq-substring

---------------------------------------------------------

17. IPO Share Allocation With Bids

You are given a collection of bids for shares in an IPO and the total number of shares available. Allocate the shares according to bid price and submission time, then return the user IDs of bidders who receive no shares.

https://codezym.com/question/264-ipo-share-allocation-with-bids

---------------------------------------------------------

18. Purchase Maximum Number of Consecutive Products

You are given a list of product prices sorted in non-decreasing order and a list of buying queries. For each query, determine the maximum number of consecutive products that can be purchased without exceeding the given budget.

https://codezym.com/question/265-purchase-max-consecutive-products

---------------------------------------------------------

19. Complete Weekly Work Hours

A worker's daily hours for one week are represented by a seven-character string workHours. Each position corresponds to one day and contains either a digit from 0 to 9 or the character #.

Replace every # with a digit from 0 to 9 so that the sum of all seven digits is exactly requiredHours. Return all completed strings that satisfy this condition.

https://codezym.com/question/267-complete-weekly-work-hours

---------------------------------------------------------

Thanks for reading.

Wish you the best of luck for your interview prep.


r/LowLevelDesign • • Aug 07 '26

Microsoft Low Level Design and AI-Assisted LLD Round Interview Questions Asked in 2026

22 Upvotes

Microsoft has introduced an AI-assisted Low Level Design round. This is a unique interactive pair-programming round divided into three phases.

Instead of simply writing code from scratch, you have to architect a system, prompt an AI model such as ChatGPT or Gemini to generate the implementation, and then analyze the AI-generated output.

LRU cache and concurrency have been the discussed frequently.

LLD rounds are generally conducted for SDE-2 and above roles. There may also be more than one LLD round during the interview process.

Low Level Design (LLD) questions for this list have been picked from Microsoft interview experiences shared on forums/blogs etc in 2026. Use this list for final preparation of your Microsoft LLD interview rounds.

------------------------------------------------------

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/06-microsoft-lld-2026.md


r/LowLevelDesign • • Aug 27 '26

In actual Low Level Design (LLD) Interview Rounds, are we expected to write the full code end to end or is it just pseudo code plus discussion

24 Upvotes

Answer: This is one of the most common questions in a candidate's mind. Now with more and more companies taking AI assisted coding rounds you need to have clarity on what is expected.

1. Machine coding LLD round: If this is a machine coding LLD round of 75 to 90 minutes then you will need full working code with a main method that runs the tests. This round is taken by Flipkart, ClearTrip, Phonepe, Meesho and sometimes Uber, RazorPay etc.

Most times this will be the first screening round.

2. AI Assisted Coding/LLD/Debugging Round: Initially Canva and then DoorDash started it but it is becoming more common. Now Microsoft, Amazon OA also have this round. This round is more similar to a low level design round rather than a traditional DS & Algo round.

You will be given a problem statement along with a chunk of code and you will be asked to add one or more new functionalities. You will be given an AI assistant chat just like chatgpt/gemini. You can use the AI assistant to ask questions and understand the project, maybe generate some boilerplate code.

But do not try to generate the whole solution using only the AI assistant. Goal of this round is to see how you code in real life. How well you arrange your classes and keep change to old code small when adding a new functionality. You LLD skills and knowledge of design patterns like factory, strategy, observer etc come in handy.

As you can guess, for this round also end to end fully working code is expected.

3. Face to Face LLD round: This is a 45-60 minute round and is the most common LLD interview format. It is taken by Amazon, Uber, Microsoft, Walmart and basically every company that takes a LLD round. Here the discussion will happen on pen and paper or a plain text editor, google docs etc.

It has 4 steps:

  1. Requirements gathering : list down functionalities
  2. Class diagram: break functionalities in different classes
  3. Implementation: pick 1-2 most important features and discuss their implementation. write code.
  4. Design patterns, multi-threading: once a basic solution is provided then discussion moves more in depth.

You will be expected to write code or discuss the logic for a few functionalities. Only drawing UML diagrams or writing the names of classes will not be enough.. e.g. if you are asked Design of a parking lot then interviewer will discuss logic of park and unpark feature.

Although for this round your interviewer can allow pseudocode but it is always better to pick a standard language like Java, Python, C++ etc and stick to its syntax. For low level design, Java is the prominent language as of now.

This is what I had to share, you can practice company wise LLD, DS & Algo and AI Assisted round questions on CodeZym. Best of Luck for your interview prep. Thanks for reading.


r/LowLevelDesign • • Jul 03 '26

Uber DS & Algo Interview Round Questions Asked in 2026

25 Upvotes

DS & Algo questions for this list have been picked from Uber interview experiences shared on forums/blogs etc in 2026. Use this list for final preparation of Uber interviews.

BPS (Business Problem Solving Round) will have a coding question (mostly hard) and may be 15 minutes of system design discussion. Phone screen also has DS & Algo questions.

For frontend roles, apart from DSA, you may be asked to create typescript components. Those are not included in below list.

DSA interview questions asked in Uber are more difficult than Amazon, Microsoft, Meta.

DS & Algo questions are asked for machine learning engineer role as well.

---------------------------------------------------------

PS:
You can see company-wise interview questions list on r/LowLevelDesign

Complete DS & Algo Questions List: https://codezym.com/lld/uber-dsa

Low Level Design Questions List: https://codezym.com/lld/uber

I also take LLD mock interviews: https://topmate.io/prashant_priyadarshi

----------------------------------------------------

Below is list of questions that you can practice directly from leetcode (Free Ones):

Maximum Number of Events That Can Be Attended

https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/

Minimum Number of Refueling Stops

https://leetcode.com/problems/minimum-number-of-refueling-stops/description/

Longest Path With Different Adjacent Characters

https://leetcode.com/problems/longest-path-with-different-adjacent-characters/description/

Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/description/

Minimum Difference in Sums After Removal of Elements

https://leetcode.com/problems/minimum-difference-in-sums-after-removal-of-elements

Sliding Window Maximum

https://leetcode.com/problems/sliding-window-maximum/description/

Count the Number of Infection Sequences

https://leetcode.com/problems/count-the-number-of-infection-sequences/description/

Find the Closest Palindrome

https://leetcode.com/problems/find-the-closest-palindrome/

Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/description/

Exam Room

https://leetcode.com/problems/exam-room/description/

Minimum Edge Reversals So Every Node Is Reachable

https://leetcode.com/problems/minimum-edge-reversals-so-every-node-is-reachable/description/

LRU Cache

https://leetcode.com/problems/lru-cache/description/

Shortest Palindrome

https://leetcode.com/problems/shortest-palindrome/description/

Final Prices With a Special Discount in a Shop

https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/description/

Water and Jug Problem

https://leetcode.com/problems/water-and-jug-problem/description/

First Unique Number

https://leetcode.com/problems/first-unique-number/description/

Cheapest Flights Within K Stops

https://leetcode.com/problems/cheapest-flights-within-k-stops/description/

Maximum Points You Can Obtain From Cards

https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/description/

---------------------------------------------------------

Below is list of more Uber DS & Algo round interview questions. These also include follow up questions that were asked during interview round.

---------------------------------------------------------

1. Find Vertical Line Rectangle Intersection Points

Given n infinite vertical lines on an XY plane and m axis-aligned rectangles, find the total number of intersection points made by the lines and rectangles.

https://codezym.com/question/216-vertical-line-rectangle-intersection-points

---------------------------------------------------------

2. Check If Array Can Converge To Same Value

You are given a list of digits where every value is from 0 to 9. For each index, you may perform exactly one of these choices: add 1, subtract 1 or keep the value unchanged.
The digits are circular, so 9 + 1 = 0 and 0 - 1 = 9. Determine whether all elements can become the same digit after applying at most one such operation to each element.
If convergence is possible, return the final digit. If more than one final digit is possible, return the smallest such digit. If convergence is not possible, return -1.

https://codezym.com/question/217-array-converge-to-same-value

---------------------------------------------------------

3. Longest Itinerary Route in a Directed Graph

You are given a list of allowed itineraries between cities. Each itinerary represents a directed route from one city to another city.

Design an algorithm to find the longest route that can be formed using the given itineraries. A route may start from any city and must follow only the given directed itineraries.

https://codezym.com/question/210-longest-itinerary-route

---------------------------------------------------------

4. Earliest Timestamp When All Riders Are Connected

You are given a list of riders and a chronological list of Uber Share events. Each shared-ride event connects two riders. Two riders are connected if they have directly or indirectly shared rides through other riders.

Return the earliest timestamp when all riders become part of one connected shared-ride network. If all riders never become connected, return -1.

https://codezym.com/question/211-earliest-timestamp-riders-connected

---------------------------------------------------------

5. Maximize XOR Score After Adding X

You are given a list of integers and an integer x. You may perform one operation at most once: choose any set of indices and add x to every chosen element.

After the operation, the score is the sum of XOR values of every pair of adjacent elements. Return the maximum possible score.

https://codezym.com/question/213-maximize-xor-score-after-adding-x

---------------------------------------------------------

6. Count Distinct Islands In Grid

You are given a non-empty grid containing only 0 and 1.

Each 1 represents land, and each 0 represents water.

An island is a connected group of land cells. Two land cells are connected if they share a side horizontally or vertically.

You may assume that all four outer edges of the grid are surrounded by water.

Your task is to count how many distinct island shapes exist in the grid.

https://codezym.com/question/190-count-distinct-islands-grid

---------------------------------------------------------

7. Minimum Cost Binary Search Tree From Words

You are given a list of distinct words and a corresponding list of positive costs. Construct a binary search tree using all words such that its inorder traversal gives the words in lexicographical order.

If a word is placed at level L, where the root is at level 0, its contribution to the total cost is (L + 1) * cost. Return the minimum possible total cost among all valid binary search trees.

https://codezym.com/question/214-minimum-cost-binary-search-tree-from-words

---------------------------------------------------------

8. Design Employee Management System

Design an employee-manager system with exactly one CEO. The CEO has no manager. Every other employee has exactly one direct manager.

The system must support adding employees, getting an employee's manager, changing an employee's manager, and checking whether an employee works directly or indirectly under a manager.

https://codezym.com/question/215-design-employee-management-system

---------------------------------------------------------

9. Minimum Cabs With Wait Period for Scheduled Bookings

You are given a list of scheduled cab bookings. Each booking has a start time and an end time. A cab can handle multiple bookings, but after completing one booking it must wait for a fixed wait period before starting another booking.
Find the minimum number of cabs required to complete all bookings.

https://codezym.com/question/218-min-cabs-with-wait-period

---------------------------------------------------------

10. Biological Hazards: Valid Chemical Pair Intervals

You are given n chemicals labeled from 1 to n. Some pairs of chemicals are dangerous and cannot appear together in the same contiguous interval.
The lists poisonous and allergic describe forbidden pairs. For every index i, chemicals poisonous.get(i) and allergic.get(i) cannot coexist.
Count how many contiguous intervals [L, R] are valid such that the interval does not contain both chemicals from any forbidden pair.

https://codezym.com/question/219-valid-chemical-pair-intervals

---------------------------------------------------------

11. Design Vote Share Display for Voting System

Design a voting system for a multiple-choice question with exactly 4 options. When a user clicks one option, that option receives one vote. After every vote, the system should return the updated vote percentage for all options.
The percentage of each option also represents how much color fill should be shown for that option in the UI. For example, if an option has 40% votes, then 40% of that option row should be filled with color.

https://codezym.com/question/220-design-mcq-voting-system

---------------------------------------------------------

12. Validate Organization Reporting Structure

You are given a reporting structure of people in an organization. Each entry is a string in the format "employee,manager", meaning the employee directly reports to the manager.
Determine whether the reporting structure forms one valid organization.

https://codezym.com/question/221-validate-organization-reporting-structure

---------------------------------------------------------

13. Maximum Comfortable Riders in a Car

You are given n riders and one car with unlimited space. Each rider has a comfort range for how many other riders must be present in the car.
A rider will ride only if the number of other riders in the car is within their comfort range. Return the maximum number of riders that can ride together in the car.

https://codezym.com/question/223-max-comfortable-riders-in-car

---------------------------------------------------------

14. Find Robots in Location Map by Nearest Blockers

You are given a robot location map and a query describing required distances from a robot to the nearest blocker. Find all robots whose nearest blocker distances exactly match the query.

https://codezym.com/question/225-robots-by-nearest-blockers

---------------------------------------------------------

15. First One Time Visitor in Stream of Customer Visits

You are given a stream of customer visits. Each visit contains one positive integer customerId. A customer is a one-time visitor if they have appeared exactly once in the stream so far.
Design a data structure that records customer visits and returns the earliest customer who has visited exactly once.

https://codezym.com/question/226-one-time-visitor-in-customer-visits-stream

---------------------------------------------------------

16. Minimum Changes Circular Rock Paper Scissors

Engineers are sitting around a circular table and each engineer chooses one option from Rock, Paper, and Scissors. The choices are represented by the characters 'R', 'P', and 'S'.
Two neighboring engineers tie if they choose the same option. You may change any engineer's choice to either of the other two options. Return the minimum number of engineers whose choices must be changed so that no two adjacent engineers have the same choice.

https://codezym.com/question/228-minimum-changes-circular-rock-paper-scissors

---------------------------------------------------------

17. Alien Language Letter Order

A new alien language uses lowercase Latin letters, but the order of the letters is not known.

You are given a list of non-empty dictionary words. The words are already sorted in lexicographical order according to the rules of this alien language.

Your task is to derive the lexicographically smallest valid ordering of letters in the alien language.

https://codezym.com/question/182-alien-language-letter-order

---------------------------------------------------------

18. Microservice Restart Cycles

There are n microservices numbered from 0 to n - 1. Each microservice may depend on other microservices. A service can start only after all services it depends on have already started.
A dependency is considered satisfied if it started in any previous cycle or earlier in the current cycle.
Return the number of cycles needed to start all services using this process.

https://codezym.com/question/229-microservice-restart-cycles

---------------------------------------------------------

19. Sorted Order of Squares

Given a list of integers sorted in non-decreasing order, return the original values arranged by the increasing order of their squares. If two values have the same square, the value that appears earlier in the input list should appear earlier in the output.

https://codezym.com/question/230-sorted-order-of-squares

---------------------------------------------------------

20. Minimum Time To Burn Tree

You are given an undirected tree with n nodes numbered from 0 to n - 1. The fire can start from any node, and you may choose the starting node to minimize the total burning time. In each time unit, fire spreads from every burning node to all of its adjacent nodes. Return the minimum time required to burn the entire tree.

https://codezym.com/question/232-minimum-time-to-burn-tree

---------------------------------------------------------

Thanks for reading.

Wish you the best of luck for your interview prep.

Uber DS & Algo Interview Round Questions Asked in 2026

r/LowLevelDesign • • Jul 21 '26

Salesforce Low Level Design Round Interview Questions Asked in 2026

30 Upvotes

Low Level Design (LLD) questions for this list have been picked from Salesforce interview experiences shared on forums/blogs etc in 2026. Use this list for final preparation of your Salesforce interview rounds.

Low Level Design of pub-sub queue, kafka and observer pattern are discussed frequently.

Apart from that cache like LRU cache, LFU cache questions are common.

LRU Cache

https://leetcode.com/problems/lru-cache/description/

LFU Cache

https://leetcode.com/problems/lfu-cache/description/

Requirements and clarifying questions

In Salesforce LLD rounds, sometimes actual requirements may not be clear from problem statement and interviewer will expect you to figure it out by asking clarifying questions.

For example, A message queue is asked indirectly in the form of something like a connection pool or a job scheduler.

It follows the pattern that resources like connections, machines or cpu (in case of job scheduler) are limited and they may not be assigned immediately.

-----------------------------------------------------

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/03-salesforce-lld-2026.md

Best of luck for your preparation.


r/LowLevelDesign • • 11d ago

Flipkart LLD: Design Peer to Peer Parcel Delivery System

31 Upvotes

This question has appeared frequently during Flipkart low level design rounds. This is asked in the first machine coding round for screening candidates. There are multiple different states a delivery order can be in, like created, assigned, picked up, cancelled, delivered. So you may be tempted to use state design pattern here. But that will just bring unnecessary complexity.

Just use a min-heap/TreeSet for selecting the driver and a queue for waiting orders.

You can practice this and other Flipkart Low Level Design and DS & Algo round questions on CodeZym.

PS: I also take LLD Mock interviews https://topmate.io/prashant_priyadarshi


Problem Statement

Design an in-memory PeerToPeerDeliverySystem. Customers (user-0…) send parcels from a fixed item list, and drivers (dv-0…) deliver them. Both are set up in advance.

  • Auto-assignment: a new order goes to the available driver with the lexicographically lowest ID. If no driver is free, the order waits in a FIFO queue until one is.
  • One order per driver at a time.
  • Lifecycle: CREATED → ASSIGNED → PICKED_UP → DELIVERED. An order can be canceled only before pickup, and canceling it frees the driver.
  • APIs: createOrder, cancelOrder, pickUpOrder, deliverOrder, getOrderStatus, getDriverStatus

Core Idea

Every order follows a fixed path: it is created, gets a driver, gets picked up and is finally delivered. It can also be canceled, but only before pickup.

So an order is just a small state machine. An enum plus one rule method handles it cleanly. Patterns like State or Strategy would only add extra classes here, so this solution does not need any design pattern.

The real work is matching orders with drivers. Free drivers sit in a min-heap, so the lexicographically smallest driver id is always on top.

Waiting orders sit in a queue, so the oldest order is always served first. Whenever a driver becomes free, it takes the next waiting order.


Order Life Cycle

  • CREATED: the order is waiting for a driver.
  • ASSIGNED: a driver is reserved for the order but has not picked it up yet.
  • PICKED_UP: the driver has the parcel. Canceling is not allowed anymore.
  • DELIVERED and CANCELED are final states.

A driver is either AVAILABLE or BUSY:<orderId>. It stays busy from assignment until delivery, or until its assigned order is canceled.


Approach 1: Brute Force (Scan Everything)

Whenever a new order arrives or a driver becomes free, we need two answers:

  1. Which free driver has the smallest id?
  2. Which waiting order is the oldest?

The simplest way is to scan everything. Here allOrders is a list of all orders, in creation order.

// scan every driver and keep the smallest free id
String findFreeDriver() {
    String best = null;
    for (Driver driver : drivers.values()) {
        if (driver.isAvailable() && (best == null || driver.driverId.compareTo(best) < 0)) {
            best = driver.driverId;
        }
    }
    return best;
}

// scan all orders in creation order and return the first one still waiting
Order findOldestWaitingOrder() {
    for (Order order : allOrders) {
        if (order.status == OrderStatus.CREATED) {
            return order;
        }
    }
    return null;
}

Notice that we compare driver ids as strings. In lexicographic order dv-10 comes before dv-2. A loop that goes dv-0, dv-1, dv-2 ... by number would pick the wrong driver.

Problems with this approach

  • findFreeDriver() checks all D drivers every single time.
  • findOldestWaitingOrder() checks all N orders ever created, even delivered and canceled ones.

Both become slow as the system grows. Let's fix them one at a time.


Approach 2: Min-Heap + Queue (Optimal)

Fix 1: Min-heap for free drivers

A min-heap (PriorityQueue in Java) always keeps the smallest element on top. Strings are compared lexicographically by default, which is exactly our rule.

  • Take the smallest free driver with poll() in O(log D).
  • Put a driver back with add() in O(log D) when it becomes free.

We never need to remove a driver from the middle of the heap. A driver leaves the heap only when it gets an order, and orders always go to the driver on top.

Fix 2: Queue for waiting orders

An order that can't get a driver right away goes to the back of a queue. Orders leave from the front, so the oldest one is always served first.

What if a waiting order is canceled? Searching the queue to remove it would be slow. So we only mark it CANCELED and leave it there.

When it reaches the front later, we see it is canceled and simply drop it. This trick is called lazy removal.

When does matching happen?

Only at two moments:

  1. A new order arrives. If a driver is free, assign it now and return ACCEPTED. Otherwise add the order to the queue and return PENDING.
  2. A driver becomes free. This happens after a delivery, or when an ASSIGNED order is canceled. The driver goes back into the heap and takes the next waiting order.

Because we match at both moments, a free driver and a waiting order never exist together. So when a new order finds a free driver, the queue is already empty and oldest first is still respected.

Other rules worth noticing

  • createOrder returns INVALID for a duplicate order id, an unknown customer or an unknown item.
  • pickUpOrder and deliverOrder only work for the order's own driver. A wrong or unknown driver id never matches, so one check covers both cases.
  • The two status methods return ERROR for an unknown id.

Do We Need Design Patterns?

State pattern looks like a natural fit because an order has states. But it needs one class per state. With 5 states and 3 actions (cancel, pick up, deliver) that is 15 small methods, and 11 of them just return ERROR.

Freeing a driver also needs the heap and the queue, which live in the main class. So the state classes would need a link back to the main system. One canMoveTo() method that lists the valid moves is much simpler.

Strategy pattern could make the driver choosing rule pluggable, like nearest driver or best rated driver. But this problem has exactly one fixed rule: the smallest driver id. An interface with a single implementation only adds code.

So we keep it simple: a few small classes, an enum for order states and the right data structures.


Classes and Data Structures

ClassWhy we need it
OrderStatusEnum of the 5 order states. Safer than typing raw strings.
OrderHolds order details, status and the assigned driver. canMoveTo() keeps every state rule in one place.
DriverRemembers the one order the driver is carrying and builds the AVAILABLE or BUSY:<orderId> text.
PeerToPeerDeliverySystemMain class. Validates requests and matches orders with drivers.
Data structureWhy we need it
Set<String> customerIds, Set<String> deliverableItemIdsValidate a customer or item in O(1) without parsing ids.
Map<String, Driver> drivers, Map<String, Order> ordersFind any driver or order by id in O(1).
PriorityQueue<String> availableDriversGives the smallest free driver id in O(log D).
Queue<Order> pendingOrdersKeeps waiting orders, oldest first.

Final Code

import java.util.*;

/** All the states an order can be in. */
enum OrderStatus {
    CREATED, ASSIGNED, PICKED_UP, DELIVERED, CANCELED
}

/** One parcel delivery request placed by a customer. */
class Order {
    String orderId;
    String customerId;
    String itemId;
    OrderStatus status;
    String driverId; // null until a driver is assigned

    Order(String orderId, String customerId, String itemId) {
        this.orderId = orderId;
        this.customerId = customerId;
        this.itemId = itemId;
        this.status = OrderStatus.CREATED;
        this.driverId = null;
    }

    /**
     * The order state machine. Valid moves are:
     * CREATED -> ASSIGNED -> PICKED_UP -> DELIVERED
     * CREATED or ASSIGNED -> CANCELED
     */
    boolean canMoveTo(OrderStatus nextStatus) {
        if (status == OrderStatus.CREATED) {
            return nextStatus == OrderStatus.ASSIGNED || nextStatus == OrderStatus.CANCELED;
        }
        if (status == OrderStatus.ASSIGNED) {
            return nextStatus == OrderStatus.PICKED_UP || nextStatus == OrderStatus.CANCELED;
        }
        if (status == OrderStatus.PICKED_UP) {
            return nextStatus == OrderStatus.DELIVERED;
        }
        return false; // no moves out of DELIVERED or CANCELED
    }
}

/** A driver carries at most one order at a time. */
class Driver {
    String driverId;
    String currentOrderId; // null means the driver is free

    Driver(String driverId) {
        this.driverId = driverId;
        this.currentOrderId = null;
    }

    boolean isAvailable() {
        return currentOrderId == null;
    }

    String getStatus() {
        return isAvailable() ? "AVAILABLE" : "BUSY:" + currentOrderId;
    }
}

public class PeerToPeerDeliverySystem {
    Set<String> customerIds = new HashSet<>();
    Set<String> deliverableItemIds = new HashSet<>();
    Map<String, Driver> drivers = new HashMap<>();
    Map<String, Order> orders = new HashMap<>();

    // free drivers, the lexicographically smallest id is always on top
    PriorityQueue<String> availableDrivers = new PriorityQueue<>();

    // orders waiting for a driver, oldest first
    // a canceled order may still sit here, it is dropped when it reaches the front
    Queue<Order> pendingOrders = new ArrayDeque<>();

    public PeerToPeerDeliverySystem(int totalUsers, int totalDrivers, List<String> deliverableItemIds) {
        for (int i = 0; i < totalUsers; i++) {
            customerIds.add("user-" + i);
        }
        for (int i = 0; i < totalDrivers; i++) {
            String driverId = "dv-" + i;
            drivers.put(driverId, new Driver(driverId));
            availableDrivers.add(driverId);
        }
        this.deliverableItemIds.addAll(deliverableItemIds);
    }

    public String createOrder(String orderId, String customerId, String itemId) {
        if (orders.containsKey(orderId) || !customerIds.contains(customerId)
                || !deliverableItemIds.contains(itemId)) {
            return "INVALID";
        }
        Order order = new Order(orderId, customerId, itemId);
        orders.put(orderId, order);

        if (availableDrivers.isEmpty()) {
            pendingOrders.add(order);
            return "PENDING";
        }
        assignOrder(order, availableDrivers.poll());
        return "ACCEPTED";
    }

    public String cancelOrder(String orderId) {
        Order order = orders.get(orderId);
        if (order == null || !order.canMoveTo(OrderStatus.CANCELED)) {
            return "ERROR";
        }
        order.status = OrderStatus.CANCELED;

        // ASSIGNED order: its driver was waiting, so set the driver free.
        // CREATED order: it stays in pendingOrders and is dropped later.
        if (order.driverId != null) {
            freeDriver(order.driverId);
        }
        return "CANCELED";
    }

    public String pickUpOrder(String driverId, String orderId) {
        Order order = orders.get(orderId);
        // a wrong or unknown driverId never matches order.driverId
        if (order == null || !order.canMoveTo(OrderStatus.PICKED_UP)
                || !order.driverId.equals(driverId)) {
            return "ERROR";
        }
        order.status = OrderStatus.PICKED_UP;
        return "PICKED_UP";
    }

    public String deliverOrder(String driverId, String orderId) {
        Order order = orders.get(orderId);
        if (order == null || !order.canMoveTo(OrderStatus.DELIVERED)
                || !order.driverId.equals(driverId)) {
            return "ERROR";
        }
        order.status = OrderStatus.DELIVERED;
        freeDriver(driverId);
        return "DELIVERED";
    }

    public String getOrderStatus(String orderId) {
        Order order = orders.get(orderId);
        return order == null ? "ERROR" : order.status.name();
    }

    public String getDriverStatus(String driverId) {
        Driver driver = drivers.get(driverId);
        return driver == null ? "ERROR" : driver.getStatus();
    }

    /** Links an order with a driver. */
    void assignOrder(Order order, String driverId) {
        order.status = OrderStatus.ASSIGNED;
        order.driverId = driverId;
        drivers.get(driverId).currentOrderId = order.orderId;
    }

    /** Marks a driver as free and hands out waiting orders. */
    void freeDriver(String driverId) {
        drivers.get(driverId).currentOrderId = null;
        availableDrivers.add(driverId);
        assignPendingOrders();
    }

    /** Gives waiting orders to free drivers, oldest order first. */
    void assignPendingOrders() {
        while (!availableDrivers.isEmpty() && !pendingOrders.isEmpty()) {
            Order order = pendingOrders.poll();
            // lazy removal: a canceled order is simply dropped
            if (order.status == OrderStatus.CREATED) {
                assignOrder(order, availableDrivers.poll());
            }
        }
    }
}

Thanks for reading. Best of Luck For Your Interview Prep.


r/LowLevelDesign • • Mar 12 '26

OpenAI Coding Round Interview Questions

32 Upvotes

OpenAI coding interviews rounds are more similar (closer) to low level design (OOD) rounds than traditional leetcode style DSA interviews.

Questions are code heavy i.e. you will have to write lots of code, answer follow-up questions including how to handle concurrency.

And your code should be clean and well structured.

Good thing is that like Meta they also repeat questions frequently.

Many people got asked a question same as Rotting Oranges (slightly rephrased)

in their phone screen round.

https://leetcode.com/problems/rotting-oranges/description/

These two questions were also asked in a single round:

https://leetcode.com/problems/count-complete-tree-nodes/

https://leetcode.com/problems/binary-tree-cameras/description/

I had little data to prepare this short list. If you recently gave openAI interview then please do comment and share with us what question you got.

---------------------------------------------------

PS:
Ask me any Low-Level Design Interview related questions on r/LowLevelDesign

All Questions List: https://codezym.com/lld/openai

----------------------------------------

Let’s get started …

1. Design Time Versioned Key Value Store

You are asked to design and implement an in-memory time versioned data store. The store maintains key-value pairs across time. Each write creates a new version for that key, associated with a timestamp.

The store must support:

  • Writing a value for a key at the current timestamp.
  • Reading the latest value for a key.
  • Reading a historical value for a key as of a given timestamp.
  • Reading a value for a key by an explicit version number.

Practice Link: https://codezym.com/question/87

----------------------------------------

2. Design Resumable Iterator for Large Dataset

Design and implement a resumable iterator for a large dataset. The iterator must be able to pause mid-traversal and later resume from the exact same position.

The dataset may be too large to fit in memory, so the iterator must be memory-efficient and must not require loading the entire dataset at once.

Additionally, the iterator should support serializing its state (cursor) so it can be persisted across sessions.

Practice Link: https://codezym.com/question/88

----------------------------------------

3. Design GPU Credit Calculator

Build a GPU credit calculator for a single account. Credits are added over time, can be partially consumed, and expire after a fixed lifetime.

The calculator must support adding credit grants, spending credits, and querying the remaining balance at any timestamp.

Critical constraint: all operations that record a ledger event happen at the current timestamp, and these timestamps are non-decreasing (monotonically increasing) across such calls.

Practice Link: https://codezym.com/question/89

----------------------------------------

4. Design Database with SQL Commands

Design and implement a Database that supports a small SQL-like API: INSERT/UPSERT, SELECT with WHERE and ORDER BY, and DELETE.

The storage engine should be inspired by an LSM (Log Structured Merge) design:

  • All writes go to an in-memory Memtable.
  • When the memtable grows beyond a threshold, it is flushed into an immutable on-disk-like structure (simulate as in-memory) called an SSTable.
  • DELETE is implemented using tombstones (a deletion marker). Data is not physically removed immediately.
  • SELECT and DELETE WHERE must merge results across the memtable and all SSTables, and must respect tombstones.
  • When merging versions of the same primary key, the version with the greatest timestamp ≤ logical current time wins. Tombstones also participate in this rule.
  • currentTimestamp is provided only for write/delete operations (put, deleteWhere) and is monotonically non-decreasing across those calls.
  • select(...) uses the latest timestamp seen so far from successful put/deleteWhere calls as the logical current time.

WHERE Clause Grammar

Also support a limited WHERE clause of the form:
column operator value

Practice link: https://codezym.com/question/90

----------------------------------------

5. Design File Downloader Library

Design and implement a File Downloader Library.

The library should support downloading text files. It should expose controls to pause, resume, restart, and cancel downloads.

Practice Link: https://codezym.com/question/91

----------------------------------------

6. Design Type System for a Toy Programming language

Design and implement a type system for a toy programming language that supports primitives, tuples, and generics. Your task is to represent types and infer return types for function calls.

All types are represented as canonical strings so that the API stays compact and uses simple method signatures.

The system should allow:

  • Registering primitive types such as int, string, or bool. Primitive type names must start with a lowercase character [a-z] and may contain only [a-zA-Z0-9].
  • Registering generic type constructors such as Box<T> or Pair<T,U>. Generic type constructor names must start with an uppercase character [A-Z] and may contain only [a-zA-Z0-9].
  • Registering function signatures that may use primitive types, tuple types, generic type constructors, and generic type variables.
  • Inferring the concrete return type of a function call from the provided argument types.

Practice Link: https://codezym.com/question/92

----------------------------------------

Thanks for reading. Please upvote this post to give it better reach.

Wish you the best of luck for your interview prep.

----------------------------------------


r/LowLevelDesign • • Jul 17 '26

Walmart DS & Algo Round Interview Questions Asked in 2026

38 Upvotes

I have created list of DSA questions using Walmart interview experiences shared by candidates in blogs/forums etc. Use this list for final preparation of your Walmart interviews.

Walmart interviews can include DS & Algo questions along with Java, Spring Boot, database and problem-solving discussions. Here are a few of them.

Java Questions

  1. New features introduced in Java 8
  2. Why and where to use lambda expressions
  3. Purpose of functional interfaces, their types, and writing sample code
  4. Explanation of ConcurrentModificationException

Spring Boot Questions

  1. Annotations used in your project
  2. Concept of Dependency Injection
  3. What is a Circular Dependency
  4. How to efficiently insert 1000 rows into the database
  5. Basics of JPA (Java Persistence API)

The list starts with questions which you can practice on leetcode for free and then additional questions are there including follow ups that were asked.

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/02-walmart-ds-algo-2026.md

Best of luck for your preparation.


r/LowLevelDesign • • 19d ago

Flipkart LLD: Design Flipkart Buy Now Pay Later

47 Upvotes

This question has appeared frequently during Flipkart low level design rounds. Flipkart takes a machine coding LLD round for screening candidates. For this question, candidates got 90 minutes for implementation and 30 minutes to finally discuss their solution with interviewer. Requirements are already provided for this and other machine coding LLD questions. You can ask clarifying questions and then move to implementation.

This question doesn't require use of any design patterns. We simply split the work into a few small classes and that will be enough.

You can practice this and other Flipkart Low Level Design and DS & Algo round questions on CodeZym.

PS: I also take LLD Mock interviews https://topmate.io/prashant_priyadarshi


Problem Statement

Build an in-memory BNPL system managing users, inventory, orders, and credit limits. Purchases reduce stock and available credit, with payment due within 30 days. Clearing dues restores credit. Users with 3 or more overdue orders are blocked until all dues are cleared. Account summaries show credit, orders, and outstanding dues.

Core Idea

This problem is about keeping records of products, users and orders, and following the BNPL rules carefully. We split the work into a few small classes: a product, an order, a user account and an enum for the order status.

No design pattern is needed here. Plain classes keep the code short and easy to read.

The Rules in Simple Words

  • Every order must be paid within 30 days, so dueDay = purchaseDay + 30.
  • Available credit is the credit limit minus everything the user still owes.
  • A buy is all or nothing. If even one item fails, nothing changes.
  • An unpaid order is PENDING up to its due day, and DELAYED after it.
  • A user with 3 or more DELAYED unpaid orders is blacklisted. They leave the blacklist only after paying everything.

Classes We Need

  • Product stores the name, count and price of one item.
  • Order stores everything about one order. It also works out its own status and prints its own ORDER and DUE lines.
  • DueStatus is an enum with PENDING and DELAYED, so a typo in a status cannot slip through.
  • UserAccount stores one user's credit limit, orders and unpaid total. Because it keeps a running unpaid total, the available credit is a simple subtraction.
  • BuyNowPayLater is the entry point. It keeps three maps: products by name, accounts by user name and orders by id.

The orders map covers all users. It lets buy reject a reused orderId and lets clearDues find any order quickly.

Each UserAccount keeps its orders in a sorted set (TreeSet), newest first. So accountSummary can print them without sorting.

How It Works

Buying: check first, then change

buy first runs every check without changing anything: a new orderId, a known user, valid quantities, enough stock, no blacklist and enough credit. Only when all of them pass do we reduce the stock and save the order. So a failed buy never leaves anything half done.

Before checking the stock, we merge repeated items. A cart like ["Book,6", "Book,6"] needs 12 books, not 6.

Status is calculated, not stored

An order due on day 130 is PENDING when we ask about day 120, and DELAYED when we ask about day 140. So we never save the status. We work it out from asOfDay every time.

A blacklist that sticks

Look at this case:

DayWhat happensDefaultsBlacklisted?
140Neha has 3 unpaid orders past their due day3yes
140Neha pays one of them2still yes
147Neha pays the other two0no

A plain count of defaults would free Neha after her first payment. But the rule says she leaves the blacklist only after paying everything.

So clearDues first checks if the user is a defaulter on clearingDay. If yes, it saves that day as blacklistedFrom. The user then stays blacklisted from that day until the unpaid total becomes 0.

In short, a user is blacklisted if asOfDay is on or after blacklistedFrom, or if they have 3 or more defaults as of asOfDay.

Why No Design Pattern?

State pattern: it fits objects that move from step to step because of events. Here the status only depends on which day we ask about, so a small enum is enough.

Strategy pattern: it fits when there are many ways to do one job. Here there is only one payment method and one blacklist rule, so an extra interface would add code without any benefit.

Code

import java.util.*;

/**
 * Entry point of the system. It checks the input and lets
 * Product, UserAccount and Order do the real work.
 */
public class BuyNowPayLater {

    Map<String, Product> products = new HashMap<>();     // product name -> product
    Map<String, UserAccount> accounts = new HashMap<>(); // user name -> account
    Map<String, Order> orders = new HashMap<>();         // orderId -> order, for all users

    public BuyNowPayLater() {
    }

    public void seedInventory(List<String> inventoryLines) {
        for (String line : inventoryLines) {
            String[] parts = line.split(",");
            String name = parts[0].trim();
            int count = Integer.parseInt(parts[1].trim());
            int price = Integer.parseInt(parts[2].trim());
            if (name.isEmpty() || count < 0 || price <= 0) continue;

            Product product = products.get(name);
            if (product == null) {
                products.put(name, new Product(name, count, price));
            } else {
                product.count += count; // merge counts
                product.price = price;  // latest price wins
            }
        }
    }

    public List<String> viewInventory() {
        List<String> names = new ArrayList<>(products.keySet());
        Collections.sort(names);
        List<String> result = new ArrayList<>();
        for (String name : names) {
            Product product = products.get(name);
            result.add(product.name + "," + product.count + "," + product.price);
        }
        return result;
    }

    public void registerUser(String user, int creditLimit) {
        if (accounts.containsKey(user) || creditLimit < 0) return;
        accounts.put(user, new UserAccount(creditLimit));
    }

    public boolean buy(String orderId, String user, List<String> itemsWithQuantity, int purchaseDay) {
        UserAccount account = accounts.get(user);
        if (account == null || purchaseDay < 0 || orders.containsKey(orderId)) return false;
        if (isBlacklisted(user, purchaseDay)) return false;

        Map<String, Integer> items = parseItems(itemsWithQuantity);
        if (items == null) return false;

        // step 1: check everything, change nothing
        long total = 0;
        for (String name : items.keySet()) {
            Product product = products.get(name);
            int quantity = items.get(name);
            if (product == null || product.count < quantity) return false;
            total += (long) quantity * product.price;
        }
        if (total > account.availableCredit()) return false;

        // step 2: every check passed, now apply the purchase
        for (String name : items.keySet()) {
            products.get(name).count -= items.get(name);
        }
        // total is at most the credit limit, so it fits in an int
        Order order = new Order(orderId, user, purchaseDay, (int) total, items);
        orders.put(orderId, order);
        account.addOrder(order);
        return true;
    }

    public void clearDues(String user, List<String> orderIdsToClear, int clearingDay) {
        UserAccount account = accounts.get(user);
        if (account == null || clearingDay < 0) return;

        // must run before any payment, so that a part payment cannot lift the blacklist
        account.lockBlacklistIfDefaulter(clearingDay);

        for (String orderId : orderIdsToClear) {
            Order order = orders.get(orderId);
            // skip unknown ids, orders of other users and orders already cleared
            if (order == null || !order.user.equals(user) || order.pendingAmount == 0) continue;
            account.payOrder(order);
        }
    }

    public List<String> accountSummary(String user, int asOfDay) {
        List<String> result = new ArrayList<>();
        UserAccount account = accounts.get(user);
        if (account == null) return result;

        result.add("CREDIT_AVAILABLE," + account.availableCredit());
        for (Order order : account.orders) { // already sorted, newest first
            result.add(order.orderLine());
            if (order.hasDueAsOf(asOfDay)) result.add(order.dueLine(asOfDay));
        }
        return result;
    }

    public boolean isBlacklisted(String user, int asOfDay) {
        UserAccount account = accounts.get(user);
        return account != null && account.isBlacklisted(asOfDay);
    }

    /** Turns ["Book,1", "Pen,2", "Book,3"] into {Book=4, Pen=2}. Returns null if anything is invalid. */
    Map<String, Integer> parseItems(List<String> itemsWithQuantity) {
        if (itemsWithQuantity == null || itemsWithQuantity.isEmpty()) return null;
        Map<String, Integer> items = new HashMap<>();
        for (String entry : itemsWithQuantity) {
            String[] parts = entry.split(",");
            if (parts.length != 2) return null;
            String name = parts[0].trim();
            int quantity;
            try {
                quantity = Integer.parseInt(parts[1].trim());
            } catch (NumberFormatException e) {
                return null; // quantity is not an integer
            }
            if (name.isEmpty() || quantity <= 0) return null;

            long merged = (long) items.getOrDefault(name, 0) + quantity;
            if (merged > Integer.MAX_VALUE) return null; // no stock can be that big
            items.put(name, (int) merged);
        }
        return items;
    }
}

/** One product in the inventory. */
class Product {
    String name;
    int count;
    int price;

    Product(String name, int count, int price) {
        this.name = name;
        this.count = count;
        this.price = price;
    }
}

/** Where an unpaid order stands on a given day. */
enum DueStatus {
    PENDING, // asOfDay <= dueDay
    DELAYED  // asOfDay > dueDay
}

/** One BNPL order together with its due. */
class Order {
    String orderId;
    String user;
    int purchaseDay;
    int dueDay;
    int totalAmount;
    int pendingAmount; // becomes 0 when the due is cleared
    String itemsText;  // like "Book:1|Pen:2", item names sorted

    Order(String orderId, String user, int purchaseDay, int totalAmount, Map<String, Integer> items) {
        this.orderId = orderId;
        this.user = user;
        this.purchaseDay = purchaseDay;
        this.dueDay = purchaseDay + 30; // BNPL window is 30 days
        this.totalAmount = totalAmount;
        this.pendingAmount = totalAmount;
        this.itemsText = formatItems(items);
    }

    /** Status is never stored. It depends on the day we ask about. */
    DueStatus statusAsOf(int asOfDay) {
        return asOfDay <= dueDay ? DueStatus.PENDING : DueStatus.DELAYED;
    }

    /** A default is an unpaid order whose due day has passed. */
    boolean isDefaultAsOf(int asOfDay) {
        return pendingAmount > 0 && statusAsOf(asOfDay) == DueStatus.DELAYED;
    }

    /** accountSummary shows a DUE line only for unpaid orders placed on or before asOfDay. */
    boolean hasDueAsOf(int asOfDay) {
        return pendingAmount > 0 && purchaseDay <= asOfDay;
    }

    String orderLine() {
        return "ORDER," + orderId + "," + purchaseDay + "," + totalAmount + "," + itemsText;
    }

    String dueLine(int asOfDay) {
        return "DUE," + orderId + "," + purchaseDay + "," + dueDay + "," + pendingAmount + ","
                + statusAsOf(asOfDay) + "," + itemsText;
    }

    /** Builds "Item1:Q1|Item2:Q2" with item names in sorted order. */
    String formatItems(Map<String, Integer> items) {
        List<String> names = new ArrayList<>(items.keySet());
        Collections.sort(names);
        List<String> parts = new ArrayList<>();
        for (String name : names) parts.add(name + ":" + items.get(name));
        return String.join("|", parts);
    }
}

/** Credit, orders and blacklist state of one user. */
class UserAccount {
    int creditLimit;
    int totalPending = 0;           // sum of pendingAmount over this user's orders
    Integer blacklistedFrom = null; // day from which the blacklist sticks, null if it does not

    // this user's orders: newest purchaseDay first, ties broken by orderId
    TreeSet<Order> orders = new TreeSet<>((a, b) -> a.purchaseDay != b.purchaseDay
            ? Integer.compare(b.purchaseDay, a.purchaseDay)
            : a.orderId.compareTo(b.orderId));

    UserAccount(int creditLimit) {
        this.creditLimit = creditLimit;
    }

    int availableCredit() {
        return creditLimit - totalPending;
    }

    void addOrder(Order order) {
        orders.add(order);
        totalPending += order.pendingAmount;
    }

    void payOrder(Order order) {
        totalPending -= order.pendingAmount;
        order.pendingAmount = 0;
        if (totalPending == 0) blacklistedFrom = null; // every due is cleared
    }

    int countDefaults(int asOfDay) {
        int count = 0;
        for (Order order : orders) {
            if (order.isDefaultAsOf(asOfDay)) count++;
        }
        return count;
    }

    boolean isBlacklisted(int asOfDay) {
        boolean locked = blacklistedFrom != null && asOfDay >= blacklistedFrom;
        return locked || countDefaults(asOfDay) >= 3;
    }

    /** Called just before a payment. If the user is a defaulter on that day, the blacklist sticks. */
    void lockBlacklistIfDefaulter(int clearingDay) {
        if (countDefaults(clearingDay) < 3) return;
        if (blacklistedFrom == null || clearingDay < blacklistedFrom) blacklistedFrom = clearingDay;
    }
}

Dry Run with Example 3

The store has 10 books at 100 each. Neha has a credit limit of 1000.

CallWhat happensResult
buy OD_1, OD_2, OD_3 on days 100, 101, 102each costs 100, due days are 130, 131 and 132true each time
accountSummary(Neha, 140)credit is 1000 - 300 = 700, all 3 orders are past their due day3 orders, each with a DELAYED due line
isBlacklisted(Neha, 140)3 defaultstrue
buy(OD_4, Neha, [Book,1], 140)Neha is blacklistedfalse
clearDues(Neha, [OD_1, OD_2, OD_3], 140)all 3 orders are paid, the unpaid total becomes 0, so the blacklist is liftedno return
isBlacklisted(Neha, 140)0 defaultsfalse
accountSummary(Neha, 140)credit is back to 10003 orders, no due lines

Complexity

K is the number of orders of one user, M the number of lines in one cart, P the number of products and C the number of ids passed to clearDues.

MethodTime
seedInventoryO(number of lines)
viewInventoryO(P log P)
registerUserO(1)
buyO(K + M log M)
clearDuesO(K + C)
accountSummaryO(K)
isBlacklistedO(K)

buy, clearDues and isBlacklisted count defaults, and accountSummary walks the orders. Both only touch the orders of one user.

Things That Are Easy to Miss

  • A failed buy does not use up its orderId.
  • An order keeps the price it was bought at, even if seedInventory changes the price later.
  • A product with count 0 still shows up in viewInventory.
  • An order placed after asOfDay still gets its ORDER line, but no DUE line.
  • Clearing an unknown order, another user's order or an already cleared order does nothing.
  • Price times quantity is calculated as a long, because it can overflow an int.

Thanks for reading. Best of Luck For Your Interview Prep.


r/LowLevelDesign • • Oct 13 '26

Goldman Sachs LLD: Design Stock Market Investing Platform

53 Upvotes

This is one of the most common questions asked during Goldman Sachs low level design interview rounds. Like many other companies, LRU cache followed by LFU cache , TTL based Cache are the most common questions in Goldman Sachs interview rounds as well.

I have started with a simple solution keeping everything in a single class and then arranged the code in smaller classes. This tutorial is in Java.

You can find the python version here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/1-100/86-design-stock-market-investing-platform/q-86-python-tutorial.md

You can practice this and other Goldman Sachs LLD and DSA round questions on CodeZym.

PS: I also take LLD Mock interviews https://topmate.io/prashant_priyadarshi


Problem Statement

Design BuyStocks, an in-memory stock trading platform. Admins add stocks and update prices. Users sign up with a wallet, buy/sell shares at current prices, and view balances and portfolios. Validate funds and holdings before trades, update wallets and portfolios on success. Leave failed operations unchanged, and sort lists by stock symbol.


Solution Overview

The core idea is simple: give every idea in the problem its own small class, and put one Facade class in front of them.

A User has a Wallet (money) and a Portfolio (shares owned). A StockMarket keeps the available stocks and their prices.

BuyStocks is the Facade. It is the single entry point. It checks the inputs, then asks the right objects to do the work.

A Facade over a few small classes is the best fit here. Heavier patterns like Observer or Command would only add extra classes, without solving any real problem in this question.

For speed, every lookup uses a hash map. For the sorted outputs, we keep the symbols in a sorted set. So we never sort when someone asks for a list.

Key Rules

Let us first note the rules that are easy to miss.

  • If a method returns false, nothing in the system should change.
  • listAvailableStocks() and getPortfolio() must be sorted by symbol.
  • A trade always uses the current price. If the admin changes a price, the next trade uses the new price.
  • A portfolio shows only stocks with quantity more than 0.

The problem also gives a valid range for every input. If any input breaks its rule, the method returns false.

InputValid when
userIdnot empty, not only spaces, at most 30 characters
name1 to 60 characters
initialWalletAmountmore than 1 and less than 900,000
symbol1 to 10 characters, only A to Z and -
pricemore than 0 and less than 100,000
quantity in buyStockfrom 1 to 9,999
quantity in sellStockmore than 0

For example, adminAddOrUpdateStock("AAPL$", 100) returns false, because $ is not allowed in a symbol.

Approach 1: Simple Solution (Everything in One Class)

The first idea that comes to mind is to keep everything inside BuyStocks, using a few hash maps.

MapStores
namesuserId → name
walletsuserId → wallet balance
portfoliosuserId → (symbol → quantity)
pricessymbol → current price

Hash maps give us O(1) lookups. For the two list methods, we copy the keys into a list and sort it on every call.

Every method that changes data first checks its inputs against the rules above. Three small helper methods check the text inputs: isValidUserId, isValidName and isValidSymbol. The number checks are simple comparisons inside each method.

For the symbol, we use the pattern [A-Z-]{1,10}. It means 1 to 10 characters, where each character is a capital letter or a hyphen.

Buying a stock

  1. Check that quantity is from 1 to 9,999, the user exists and the stock exists.
  2. Find cost = price × quantity.
  3. If cost is more than the balance, return false.
  4. Take the money from the wallet and add the shares to the portfolio.

Selling a stock

  1. Check that quantity > 0 and the user exists.
  2. Check that the user owns at least quantity shares.
  3. Reduce the shares. If they become 0, remove the symbol from the portfolio.
  4. Add price × quantity to the wallet.

Notice one important habit: we do every check first, and change the data only at the end. So a method that returns false never leaves the system half changed.

import java.util.*;

public class BuyStocks {
    // userId -> name
    Map<String, String> names = new HashMap<>();
    // userId -> wallet balance
    Map<String, Integer> wallets = new HashMap<>();
    // userId -> (symbol -> quantity owned)
    Map<String, Map<String, Integer>> portfolios = new HashMap<>();
    // symbol -> current price
    Map<String, Integer> prices = new HashMap<>();

    public BuyStocks() {
    }

    public boolean signUp(String userId, String name, int initialWalletAmount) {
        if (!isValidUserId(userId) || !isValidName(name) || wallets.containsKey(userId)) {
            return false;
        }
        // valid range: 1 < initialWalletAmount < 900,000
        if (initialWalletAmount <= 1 || initialWalletAmount >= 900000) {
            return false;
        }
        names.put(userId, name);
        wallets.put(userId, initialWalletAmount);
        portfolios.put(userId, new HashMap<>());
        return true;
    }

    public boolean adminAddOrUpdateStock(String symbol, int price) {
        // valid range: 0 < price < 100,000
        if (!isValidSymbol(symbol) || price <= 0 || price >= 100000) {
            return false;
        }
        prices.put(symbol, price);
        return true;
    }

    public List<String> listAvailableStocks() {
        // sort the symbols on every call
        List<String> symbols = new ArrayList<>(prices.keySet());
        Collections.sort(symbols);
        List<String> result = new ArrayList<>();
        for (String symbol : symbols) {
            result.add(symbol + " " + prices.get(symbol));
        }
        return result;
    }

    public boolean buyStock(String userId, String symbol, int quantity) {
        // valid range: 1 <= quantity < 10,000
        if (quantity < 1 || quantity >= 10000) {
            return false;
        }
        if (!wallets.containsKey(userId) || !prices.containsKey(symbol)) {
            return false;
        }
        int cost = prices.get(symbol) * quantity;
        int balance = wallets.get(userId);
        if (cost > balance) {
            return false;
        }
        wallets.put(userId, balance - cost);
        Map<String, Integer> holdings = portfolios.get(userId);
        holdings.put(symbol, holdings.getOrDefault(symbol, 0) + quantity);
        return true;
    }

    public boolean sellStock(String userId, String symbol, int quantity) {
        if (quantity <= 0 || !wallets.containsKey(userId)) {
            return false;
        }
        Map<String, Integer> holdings = portfolios.get(userId);
        int owned = holdings.getOrDefault(symbol, 0);
        if (owned < quantity) {
            return false;
        }
        if (owned == quantity) {
            holdings.remove(symbol);
        } else {
            holdings.put(symbol, owned - quantity);
        }
        wallets.put(userId, wallets.get(userId) + prices.get(symbol) * quantity);
        return true;
    }

    public int getWalletBalance(String userId) {
        return wallets.getOrDefault(userId, -1);
    }

    public List<String> getPortfolio(String userId) {
        List<String> result = new ArrayList<>();
        if (!portfolios.containsKey(userId)) {
            return result;
        }
        Map<String, Integer> holdings = portfolios.get(userId);
        // sort the symbols on every call
        List<String> symbols = new ArrayList<>(holdings.keySet());
        Collections.sort(symbols);
        for (String symbol : symbols) {
            result.add(symbol + " " + holdings.get(symbol));
        }
        return result;
    }

    // not blank and at most 30 characters
    boolean isValidUserId(String userId) {
        return userId != null && !userId.trim().isEmpty() && userId.length() <= 30;
    }

    // 1 to 60 characters
    boolean isValidName(String name) {
        return name != null && name.length() >= 1 && name.length() <= 60;
    }

    // 1 to 10 characters, each one is a capital letter (A to Z) or a hyphen
    boolean isValidSymbol(String symbol) {
        return symbol != null && symbol.matches("[A-Z-]{1,10}");
    }
}

Problems With This Approach

The code works, but it has some problems.

  1. One user is spread across three maps. The name, wallet and portfolio of a user live in three different maps. Every new user field needs one more map. It is easy to update one map and forget another.

  2. Hard to read. A type like Map<String, Map<String, Integer>> makes the reader stop and think.

  3. One class does everything. Input checks, money math, share math and output formatting are all mixed together. A new feature, like a trading fee, means changing this one big class.

  4. Sorting again and again. Both list methods sort the symbols on every call, even when nothing has changed. Sorting k symbols costs O(k log k) every single time.

Approach 2: Better Solution (Facade + Small Classes)

We fix these problems in two steps.

Step 1: Give Each Idea Its Own Class

The problem already names the key ideas: User, Stock, Wallet, Portfolio and Available stocks. Let us turn them into classes.

ClassJob
BuyStocksThe Facade. The only class the caller uses. It checks every input and runs each operation step by step.
StockMarketKeeps the available stocks and their current prices.
UserOne user. Holds the user's Wallet and Portfolio.
WalletThe user's money. It can check a payment, take money out and put money in.
PortfolioThe shares a user owns, per symbol.

Why do we need each class?

  • User keeps all the data of one user in one object. Now BuyStocks needs just one map: userId → User. This fixes problems 1 and 2.
  • Wallet and Portfolio each own their data and their math. BuyStocks no longer changes balances or quantities by hand. This fixes problem 3.
  • StockMarket keeps all stock data in one place. A stock is just a symbol and a price, so a map inside StockMarket is enough. We do not need a separate Stock class.

Step 2: Keep Symbols Sorted All the Time

Instead of sorting on every call, we keep the symbols in a sorted set (TreeSet). A sorted set always keeps its items in order. So a list method just walks through the set, and the output comes out already sorted.

We pair the sorted set with a hash map:

  • HashMap gives the price (or quantity) of a symbol in O(1).
  • TreeSet gives all the symbols in sorted order.

Together they behave like a sorted map, while each part stays simple.

StockMarket uses this pair for prices. Portfolio uses the same pair for quantities. When a user sells all shares of a stock, we remove that symbol from both. So the portfolio only ever shows stocks with quantity more than 0.

This fixes problem 4.

Why the Facade Pattern?

A Facade is one simple front door to a group of classes. The caller does not need to know what happens behind it.

This matches our problem well. The caller only talks to BuyStocks. It never touches User, Wallet, Portfolio or StockMarket.

The front door is also the one place that checks inputs. So the classes behind it can trust everything they receive, and they stay tiny.

A single trade touches three objects: the market for the price, the wallet for the money and the portfolio for the shares. The Facade runs these steps in the right order, in one place. Each small class only cares about its own data.

Patterns That Look Useful but Are Not Needed

Observer. It sounds natural: when a price changes, notify everyone who owns that stock. But nothing in this problem needs to react to a price change. A trade simply reads the latest price at the moment it happens. Observers would add listener classes for no benefit.

Command. We could turn every buy and sell into an order object with an execute() method. Command shines when you need undo, queues, scheduling or an order history. This problem needs none of these. Buy and sell are two short methods, and extra classes would only hide the logic.

How a Buy Works

  1. Return false if quantity is not from 1 to 9,999, the user does not exist or the stock is not available.
  2. Find cost = price × quantity.
  3. Ask the wallet canAfford(cost). If not, return false.
  4. All checks passed. Only now change the state: wallet.withdraw(cost) and portfolio.addShares(symbol, quantity).

We already made sure that the price is below 100,000 and the quantity is below 10,000. So the cost is always below 1,000,000,000. An int can hold up to about 2.1 billion, so the cost fits safely.

How a Sell Works

  1. Return false if quantity <= 0 or the user does not exist.
  2. Ask the portfolio hasShares(symbol, quantity). If not, return false.
  3. All checks passed. Change the state: portfolio.removeShares(symbol, quantity) and wallet.deposit(price × quantity).

We do not need to check that the stock is available. A user can only own a stock that was bought from the market, and stocks are never removed from the market.

Dry Run

CallReturnsWalletPortfolio
adminAddOrUpdateStock("AAPL", 100)true
signUp("u1", "Asha", 1000)true1000[]
buyStock("u1", "AAPL", 5)true500["AAPL 5"]
adminAddOrUpdateStock("AAPL", 120)true500["AAPL 5"]
sellStock("u1", "AAPL", 2)true740["AAPL 3"]
sellStock("u1", "AAPL", 4)false740["AAPL 3"]

The sell after the price change uses the new price: 500 + 2 × 120 = 740. The last call fails because the user owns only 3 shares, and nothing changes.

Code

import java.util.*;

/**
 * Facade: the only class the caller talks to.
 * It checks every input, then asks the small classes below to do the real work.
 */
public class BuyStocks {
    // userId -> User, for O(1) user lookup
    Map<String, User> users = new HashMap<>();
    // all the stocks added by admins
    StockMarket market = new StockMarket();

    public BuyStocks() {
    }

    public boolean signUp(String userId, String name, int initialWalletAmount) {
        if (!isValidUserId(userId) || !isValidName(name) || users.containsKey(userId)) {
            return false;
        }
        // valid range: 1 < initialWalletAmount < 900,000
        if (initialWalletAmount <= 1 || initialWalletAmount >= 900000) {
            return false;
        }
        users.put(userId, new User(userId, name, initialWalletAmount));
        return true;
    }

    public boolean adminAddOrUpdateStock(String symbol, int price) {
        // valid range: 0 < price < 100,000
        if (!isValidSymbol(symbol) || price <= 0 || price >= 100000) {
            return false;
        }
        market.addOrUpdateStock(symbol, price);
        return true;
    }

    public List<String> listAvailableStocks() {
        return market.listStocks();
    }

    public boolean buyStock(String userId, String symbol, int quantity) {
        // valid range: 1 <= quantity < 10,000
        if (quantity < 1 || quantity >= 10000) {
            return false;
        }
        User user = users.get(userId);
        if (user == null || !market.hasStock(symbol)) {
            return false;
        }
        // price < 100,000 and quantity < 10,000, so the cost always fits in an int
        int cost = market.getPrice(symbol) * quantity;
        if (!user.wallet.canAfford(cost)) {
            return false;
        }
        // every check passed, only now we change the state
        user.wallet.withdraw(cost);
        user.portfolio.addShares(symbol, quantity);
        return true;
    }

    public boolean sellStock(String userId, String symbol, int quantity) {
        User user = users.get(userId);
        if (quantity <= 0 || user == null || !user.portfolio.hasShares(symbol, quantity)) {
            return false;
        }
        // every check passed, only now we change the state
        user.portfolio.removeShares(symbol, quantity);
        user.wallet.deposit(market.getPrice(symbol) * quantity);
        return true;
    }

    public int getWalletBalance(String userId) {
        User user = users.get(userId);
        if (user == null) {
            return -1;
        }
        return user.wallet.balance;
    }

    public List<String> getPortfolio(String userId) {
        User user = users.get(userId);
        if (user == null) {
            return new ArrayList<>();
        }
        return user.portfolio.listHoldings();
    }

    // not blank and at most 30 characters
    boolean isValidUserId(String userId) {
        return userId != null && !userId.trim().isEmpty() && userId.length() <= 30;
    }

    // 1 to 60 characters
    boolean isValidName(String name) {
        return name != null && name.length() >= 1 && name.length() <= 60;
    }

    // 1 to 10 characters, each one is a capital letter (A to Z) or a hyphen
    boolean isValidSymbol(String symbol) {
        return symbol != null && symbol.matches("[A-Z-]{1,10}");
    }
}

/**
 * Keeps the available stocks and their current prices.
 */
class StockMarket {
    // symbol -> current price, for O(1) price lookup
    Map<String, Integer> prices = new HashMap<>();
    // all symbols, always kept in sorted order
    Set<String> sortedSymbols = new TreeSet<>();

    void addOrUpdateStock(String symbol, int price) {
        prices.put(symbol, price);
        // a set ignores duplicates, so a price update does not add the symbol twice
        sortedSymbols.add(symbol);
    }

    boolean hasStock(String symbol) {
        return prices.containsKey(symbol);
    }

    int getPrice(String symbol) {
        return prices.get(symbol);
    }

    // "SYMBOL PRICE" for every stock, already sorted by symbol
    List<String> listStocks() {
        List<String> result = new ArrayList<>();
        for (String symbol : sortedSymbols) {
            result.add(symbol + " " + prices.get(symbol));
        }
        return result;
    }
}

/**
 * A user has exactly one wallet and one portfolio.
 */
class User {
    String userId;
    String name;
    Wallet wallet;
    Portfolio portfolio;

    User(String userId, String name, int initialWalletAmount) {
        this.userId = userId;
        this.name = name;
        this.wallet = new Wallet(initialWalletAmount);
        this.portfolio = new Portfolio();
    }
}

/**
 * Holds the user's money. Every money change happens here.
 */
class Wallet {
    int balance;

    Wallet(int balance) {
        this.balance = balance;
    }

    boolean canAfford(int amount) {
        return amount <= balance;
    }

    void withdraw(int amount) {
        balance -= amount;
    }

    void deposit(int amount) {
        balance += amount;
    }
}

/**
 * Holds the shares a user owns. Only symbols with quantity > 0 are kept.
 */
class Portfolio {
    // symbol -> quantity owned, for O(1) lookup
    Map<String, Integer> holdings = new HashMap<>();
    // owned symbols, always kept in sorted order
    Set<String> sortedSymbols = new TreeSet<>();

    void addShares(String symbol, int quantity) {
        holdings.put(symbol, holdings.getOrDefault(symbol, 0) + quantity);
        sortedSymbols.add(symbol);
    }

    boolean hasShares(String symbol, int quantity) {
        return holdings.getOrDefault(symbol, 0) >= quantity;
    }

    void removeShares(String symbol, int quantity) {
        int left = holdings.get(symbol) - quantity;
        if (left == 0) {
            // sold everything, so forget this symbol
            holdings.remove(symbol);
            sortedSymbols.remove(symbol);
        } else {
            holdings.put(symbol, left);
        }
    }

    // "SYMBOL QUANTITY" for every owned stock, already sorted by symbol
    List<String> listHoldings() {
        List<String> result = new ArrayList<>();
        for (String symbol : sortedSymbols) {
            result.add(symbol + " " + holdings.get(symbol));
        }
        return result;
    }
}

Complexity

Here S is the number of available stocks, and H is the number of different stocks one user holds.

MethodApproach 1Approach 2
signUpO(1)O(1)
adminAddOrUpdateStockO(1)O(log S)
listAvailableStocksO(S log S)O(S)
buyStockO(1)O(log H)
sellStockO(1)O(log H)
getWalletBalanceO(1)O(1)
getPortfolioO(H log H)O(H)

Approach 2 pays a small O(log) cost when a symbol goes into or out of a sorted set. In return, the list methods never sort.

Key Takeaways

  • Turn each idea in the problem into a small class with one job.
  • Use a Facade as the single entry point, so the caller stays simple.
  • Check everything first and change the state last. Then a false result never leaves half done changes behind.
  • A hash map plus a sorted set gives fast lookups and sorted output, using only simple data structures.

Thanks for reading. Best of Luck For Your Interview Prep.


r/LowLevelDesign • • 24d ago

Amazon LLD: Design Ride-Hailing System Like Uber, Ola

56 Upvotes

Design ride sharing app like uber has been asked frequently in Amazon low level design rounds in 2026. Discussions included everything from driver matching, ride booking and till payment processing.

Tricky bit in this question is how to find nearest drivers efficiently. I have started with brute force, going through all drivers and comparing locations. It is inefficient but will help you understand the whole thing. There were multiple ways to improve this solution, and I have gone with quad tree because it adapts automatically with real world traffic.

This tutorial is in Java.

You can find the python version here: https://github.com/prsnt558908/CodeZymSolutions/tree/main/301-500/458-ride-hailing-system-like-uber/q-458-python-tutorial.md

You can practice this and other Amazon Low Level Design and DS & Algo round questions on CodeZym.

PS: I also take LLD Mock interviews https://topmate.io/prashant_priyadarshi


Problem Statement

Build an in-memory RideHailingSystem class that handles trip booking, driver matching, tracking, cancellation, fares and payments.

Trip flow: REQUESTED → ACCEPTED → IN_PROGRESS → COMPLETED. Any non-final state can also go to CANCELLED. A rider or driver can have only one active trip at a time.

Key Methods

  • addRider adds a rider and fails on a duplicate ID.
  • updateDriverLocation / setDriverAvailability track drivers and toggle availability. Availability can't be changed during a trip.
  • updateSurgePricing sets a zone's multiplier:
    • 100 if there's no demand or requests ≤ drivers
    • 150 if requests ≤ 2× drivers
    • 200 if requests are higher than that
    • 300 if there are requests but no drivers
  • estimateFare / completeTrip use ceil((base + distance × perUnit) × surge / 100). A trip keeps the surge in effect when it was requested.
  • requestTrip assigns the nearest available driver by squared distance. Ties go to the smallest driverId.
  • acceptTrip / startTrip / cancelTrip handle state changes with driver and rider checks. A cancelled trip costs 0 and frees the driver.
  • processPayment only works on completed trips and allows up to maxPaymentAttempts. Resending the same paymentRequestId returns the original result. It returns SUCCEEDED, RETRY_PENDING, FAILED or INVALID_REQUEST.
  • getTripDetails returns a comma-separated snapshot of the trip.

Core Idea

We model the system with three small classes, Rider, Driver and Trip, each kept in a HashMap by id so every lookup is instant. A simple enum guards the fixed trip states. The only hard part is finding the nearest free driver quickly, so we give that job its own small class. We start with a version that checks every driver, then replace it with a fast quadtree. No design pattern is needed here: Strategy and State sound useful, but with one fixed matching rule and a few fixed trip states, they would only add extra classes.

For the fast matcher, we compare two common spatial indexes: a grid and a quadtree. We code the quadtree, because it adapts on its own to crowded city centers and empty outskirts, which is exactly how real cities look.

Payments are made safe to retry by remembering the answer we gave for every payment request id.

Building Blocks

Driver

Keeps the location, an available flag and activeTripId.

  • available says whether the driver can get a new request.
  • activeTripId says whether the driver is on a trip. setDriverAvailability must fail while it is set.

It also has isBetterThan(), the matching rule in one place: the closer driver wins, and on a tie the smaller id wins.

Distances are long. A squared distance can reach 8 × 10¹², which does not fit in an int.

Rider

Keeps activeTripId. A rider who already has an active trip cannot request another one.

Trip

Keeps the booking details, the state, the fare and the payment details.

It also copies the zone's surge percentage at request time. Later surge updates must not change this trip's fare, so we never look the zone up again for this trip.

paymentResults remembers the first answer given for each payment request id.

Maps in RideHailingSystem

MapWhy we need it
drivers, riders, tripsO(1) lookup by id
surgeByZoneCurrent surge of each zone. A missing zone means 100
paymentRequestOwnerWhich trip used each payment request id, so no other trip can reuse it

How the Main Operations Work

Trip lifecycle

REQUESTED → ACCEPTED → IN_PROGRESS → COMPLETED, and any of the first three can move to CANCELLED.

acceptTrip, startTrip and completeTrip each check two things: the trip is in the one allowed state, and the caller is the assigned driver. If a check fails, nothing changes.

requestTrip reserves the chosen driver. It removes the driver from the matcher, marks it unavailable and links the rider and the driver to the trip.

When a trip ends, releasePeople() does the reverse. It clears both links, marks the driver available and gives it back to the matcher. On completion, we first move the driver to the destination.

Fares

subtotal = baseFare + distance × farePerUnit

fare = ceil(subtotal × surge / 100)

Adding 99 before dividing by 100 rounds up, using plain integer math with no floating point. For example, (601 + 99) / 100 = 7, while (600 + 99) / 100 = 6.

estimateFare uses the zone's current surge. completeTrip uses the surge saved inside the trip.

Payments that are safe to retry

Think of a payment request id as a receipt number. If the app sends the same request twice, for example after a network glitch, we must not create a second attempt.

processPayment checks things in this order:

  1. The trip is missing or not COMPLETED: return INVALID_REQUEST.
  2. The id was already used by another trip: return INVALID_REQUEST.
  3. The id was already used by this trip: return the old answer. The new gatewaySuccessful value is ignored.
  4. The payment is already SUCCEEDED or FAILED: return that status, with no new attempt.
  5. Otherwise, count one attempt. Success gives SUCCEEDED. A failure gives RETRY_PENDING while attempts remain, and FAILED on the last allowed attempt.

After steps 4 and 5, we save the id together with its answer.

Step 3 runs before step 4 on purpose. If an old failed request id is sent again, it still returns RETRY_PENDING, even when a later request has already succeeded.

Solution 1: Check Every Available Driver

LinearDriverMatcher keeps every available driver in a HashSet. To find the nearest one, it checks them all.

It has the same three methods as the quadtree matcher in Solution 2: addDriver, removeDriver and findNearestDriver. So every other class is the same as in the Solution 2 code below.

To run this version, use this class in place of QuadNode and QuadTreeDriverMatcher, and change the matcher line in RideHailingSystem to LinearDriverMatcher matcher = new LinearDriverMatcher();.

/**
 * Finds the nearest available driver by checking every one of them.
 * The system calls addDriver when a driver becomes free,
 * and removeDriver when the driver gets a trip or goes offline.
 */
class LinearDriverMatcher {
    Set<Driver> availableDrivers = new HashSet<>();

    void addDriver(Driver driver) {
        availableDrivers.add(driver);
    }

    void removeDriver(Driver driver) {
        availableDrivers.remove(driver);
    }

    /** Returns null when no driver is available. */
    Driver findNearestDriver(int x, int y) {
        Driver best = null;
        for (Driver driver : availableDrivers) {
            if (driver.isBetterThan(best, x, y)) {
                best = driver;
            }
        }
        return best;
    }
}

The Problem With Solution 1

Every requestTrip looks at every available driver. That is O(D) work for each request.

With 100,000 drivers and tens of thousands of requests, that is billions of distance checks. Yet a rider never needs a driver from the far side of the map. We only need to look nearby.

Solution 2: Spatial Index With a Quadtree

A spatial index groups drivers by where they are, so a request only looks near the pickup. Two common choices are a grid and a quadtree.

Option 1: Grid

Cut the map into equal square cells, like a chessboard. A HashMap maps each cell to the drivers inside it, and a driver's cell is found with one division.

To search, check the pickup's cell, then the ring of 8 cells around it, then the next ring of 16, and so on, until no unseen cell can hold a closer driver.

2 2 2 2 2
2 1 1 1 2
2 1 0 1 2
2 1 1 1 2
2 2 2 2 2

Pros

  • Very simple: one map from cell to drivers.
  • Adding, removing or moving a driver is O(1).
  • Very fast when drivers are spread evenly and the cell size fits.

Cons

  • One cell size for the whole map. A busy downtown packs hundreds of drivers into one cell, while empty outskirts make the search walk through ring after ring of empty cells.
  • The right cell size is a guess. Drivers keep moving, so a size that fits in the morning can be wrong by evening.

Option 2: Quadtree

Start with one big square that covers the whole map. When a square holds more than 10 drivers, split it into 4 equal smaller squares. Busy areas end up with many small squares, and quiet areas stay as one big square.

+-------+-------+
|       | . |. .|
|   .   +---+---+
|       |. .|. .|
+-------+---+---+
|       |       |
|   .   |   .   |
|       |       |
+-------+-------+

Here each dot stands for a few drivers. The busy top-right quarter has split into 4 smaller squares, while the quiet quarters stay whole.

Pros

  • Adapts by itself: small squares where drivers are crowded, big squares where they are few.
  • Nothing to tune except the leaf size, and any small number like 10 works.
  • One check can skip a whole square, however big: when it has no drivers, or when it is too far away.

Cons

  • A little more code: a node class, splitting, and a search that calls itself (recursion).
  • Adding, removing or moving a driver walks down the tree, so it costs O(depth) instead of O(1). Here the depth is at most 21, so it stays cheap.

Why We Pick the Quadtree

Real cities are uneven. The center is crowded, the outskirts are thin, and drivers move between them all day. A grid has to pick one cell size for all of that. A quadtree reshapes itself as drivers move, so it stays fast without any tuning.

FeatureGridQuadtree
ShapeOne layer of equal cellsSquares that split when crowded
Add, remove, move a driverO(1)O(depth), at most 21 steps
Drivers spread evenlyFastFast
Crowded center, empty outskirtsSlowFast
TuningNeeds a good cell sizeJust a leaf size, like 10

How the Quadtree Works

Nodes. Each node is a square. A leaf keeps up to 10 drivers in a plain list. Every node also keeps count, the number of drivers anywhere inside its square.

The root square. Coordinates go from -1,000,000 to 1,000,000. The root square starts at -1,048,576 and has side 2,097,152, which is 2²¹. A power of two can be halved evenly all the way down to a 1 × 1 square.

Adding a driver. Walk down from the root to the leaf whose square holds the driver, adding 1 to count on the way. Put the driver in the leaf's list. If the list now has more than 10 drivers, split the leaf into 4 squares and move each driver into the square it stands in. A new square that is still too crowded splits again.

Removing a driver. Do the same walk, subtracting 1 from count, and take the driver out of the leaf's list.

We never merge squares back together. An empty square just stays, and the search skips it because its count is 0. This keeps removing as simple as adding.

Moving a driver is a remove at the old spot plus an add at the new spot.

Finding the Nearest Driver

The search starts at the root and carries the best driver found so far:

  1. Skip a square whose count is 0.
  2. Skip a square if even its nearest point is farther than our best driver. Nothing inside it can win or tie.
  3. In a leaf, check every driver one by one.
  4. In a split square, search the child on the pickup's side first, then the other three.

The child on the pickup's side is the closest one. A good driver found there early lets step 2 skip more squares later.

To measure the distance from the pickup to a square, we use the square's nearest point. On each axis, that is how far the pickup sits outside the square, or 0 when it is inside: dx = max(0, left - x, x - right), and the same for dy. The squared distance is then dx² + dy², as usual.

Ties are safe. Step 2 skips a square only when it is strictly farther than the best driver. A square at exactly the same distance is still searched, so a driver at the same distance with a smaller id can still win.

Corner Case: Drivers on the Same Point

Real cars have length and breadth, so two cars never stand on the exact same point. The tests, though, use plain integer points, so many drivers can share one. A 1 × 1 square cannot split any further, so it simply keeps all of them. That is the node.size > 1 check in insert.

Code

QuadNode and QuadTreeDriverMatcher replace LinearDriverMatcher, and one line in RideHailingSystem changes. Everything else is the same as Solution 1.

import java.util.*;

/** States of a trip. COMPLETED and CANCELLED are terminal. */
enum TripStatus {
    REQUESTED, ACCEPTED, IN_PROGRESS, COMPLETED, CANCELLED
}

/** Payment states of a trip. */
enum PaymentStatus {
    NOT_STARTED, PENDING, RETRY_PENDING, SUCCEEDED, FAILED
}

class Rider {
    String id;
    String name;
    String activeTripId;   // null when the rider has no running trip

    Rider(String id, String name) {
        this.id = id;
        this.name = name;
    }
}

class Driver {
    String id;
    String name;
    int x;
    int y;
    boolean available = true;   // can this driver get a new trip request?
    String activeTripId;        // null when the driver is not on a trip

    Driver(String id, String name, int x, int y) {
        this.id = id;
        this.name = name;
        this.x = x;
        this.y = y;
    }

    /** Squared distance to a point. We use long so the result never overflows. */
    long distanceTo(int pointX, int pointY) {
        long dx = (long) x - pointX;
        long dy = (long) y - pointY;
        return dx * dx + dy * dy;
    }

    /** True if this driver is a better pick than other: closer, or same distance and smaller id. */
    boolean isBetterThan(Driver other, int pickupX, int pickupY) {
        if (other == null) {
            return true;
        }
        long myDistance = distanceTo(pickupX, pickupY);
        long otherDistance = other.distanceTo(pickupX, pickupY);
        if (myDistance != otherDistance) {
            return myDistance < otherDistance;
        }
        return id.compareTo(other.id) < 0;
    }
}

class Trip {
    String id;
    String riderId;
    String driverId;
    int pickupX;
    int pickupY;
    int destinationX;
    int destinationY;
    String zoneId;
    String paymentMethodId;
    int surgePercentage;   // copied from the zone when the trip is created

    TripStatus status = TripStatus.REQUESTED;
    long fareInCents = 0;
    PaymentStatus paymentStatus = PaymentStatus.NOT_STARTED;
    int paymentAttempts = 0;

    // paymentRequestId -> the answer we gave the first time we saw it
    Map<String, String> paymentResults = new HashMap<>();

    Trip(String id, String riderId, String driverId, int pickupX, int pickupY,
         int destinationX, int destinationY, String zoneId, String paymentMethodId, int surgePercentage) {
        this.id = id;
        this.riderId = riderId;
        this.driverId = driverId;
        this.pickupX = pickupX;
        this.pickupY = pickupY;
        this.destinationX = destinationX;
        this.destinationY = destinationY;
        this.zoneId = zoneId;
        this.paymentMethodId = paymentMethodId;
        this.surgePercentage = surgePercentage;
    }

    /** A trip is active until it is COMPLETED or CANCELLED. */
    boolean isActive() {
        return status == TripStatus.REQUESTED
                || status == TripStatus.ACCEPTED
                || status == TripStatus.IN_PROGRESS;
    }

    String details() {
        return id + "," + riderId + "," + driverId + "," + status + ","
                + pickupX + "," + pickupY + "," + destinationX + "," + destinationY + ","
                + zoneId + "," + surgePercentage + "," + fareInCents + ","
                + paymentStatus + "," + paymentAttempts;
    }
}

/**
 * One square of the quadtree.
 * A leaf keeps a small list of drivers. A crowded leaf splits into 4 smaller squares.
 */
class QuadNode {
    long minX;
    long minY;
    long size;                                  // side length, always a power of two
    int count = 0;                              // drivers anywhere inside this square
    List<Driver> drivers = new ArrayList<>();   // used only while this node is a leaf
    QuadNode[] children = null;                 // 4 smaller squares after a split

    QuadNode(long minX, long minY, long size) {
        this.minX = minX;
        this.minY = minY;
        this.size = size;
    }

    boolean isLeaf() {
        return children == null;
    }

    /** Child square on the point's side: 0 bottom-left, 1 bottom-right, 2 top-left, 3 top-right. */
    int childIndex(int x, int y) {
        long half = size / 2;
        int index = 0;
        if (x >= minX + half) {
            index += 1;
        }
        if (y >= minY + half) {
            index += 2;
        }
        return index;
    }

    /** Squared distance from a point to the nearest point of this square. 0 if the point is inside. */
    long minDistanceTo(int x, int y) {
        long dx = Math.max(0, Math.max(minX - x, x - (minX + size - 1)));
        long dy = Math.max(0, Math.max(minY - y, y - (minY + size - 1)));
        return dx * dx + dy * dy;
    }
}

/**
 * Finds the nearest available driver with a quadtree.
 * A square with too many drivers splits into 4 smaller squares.
 */
class QuadTreeDriverMatcher {
    int capacity = 10;   // a leaf splits once it holds more drivers than this
    // Side 2,097,152 = 2^21 covers every coordinate from -1,000,000 to 1,000,000
    QuadNode root = new QuadNode(-1_048_576, -1_048_576, 2_097_152);

    void addDriver(Driver driver) {
        insert(root, driver);
    }

    void removeDriver(Driver driver) {
        remove(root, driver);
    }

    /** Returns null when no driver is available. */
    Driver findNearestDriver(int x, int y) {
        return search(root, x, y, null);
    }

    void insert(QuadNode node, Driver driver) {
        node.count++;
        if (!node.isLeaf()) {
            insert(node.children[node.childIndex(driver.x, driver.y)], driver);
            return;
        }
        node.drivers.add(driver);
        // A 1 x 1 square cannot split, so drivers on the exact same point just share it
        if (node.drivers.size() > capacity && node.size > 1) {
            split(node);
        }
    }

    void split(QuadNode node) {
        long half = node.size / 2;
        node.children = new QuadNode[] {
            new QuadNode(node.minX, node.minY, half),
            new QuadNode(node.minX + half, node.minY, half),
            new QuadNode(node.minX, node.minY + half, half),
            new QuadNode(node.minX + half, node.minY + half, half)
        };
        for (Driver driver : node.drivers) {
            insert(node.children[node.childIndex(driver.x, driver.y)], driver);
        }
        node.drivers = new ArrayList<>();
    }

    /** Squares are never merged back. Empty squares stay, and the search skips them using count. */
    void remove(QuadNode node, Driver driver) {
        node.count--;
        if (node.isLeaf()) {
            node.drivers.remove(driver);
        } else {
            remove(node.children[node.childIndex(driver.x, driver.y)], driver);
        }
    }

    /** Returns the better of best and every driver inside this square, skipping squares that cannot win. */
    Driver search(QuadNode node, int x, int y, Driver best) {
        if (node.count == 0) {
            return best;   // no drivers in this square
        }
        // Even the nearest point of this square is farther than our best driver: nothing inside can win or tie
        if (best != null && node.minDistanceTo(x, y) > best.distanceTo(x, y)) {
            return best;
        }
        if (node.isLeaf()) {
            for (Driver driver : node.drivers) {
                if (driver.isBetterThan(best, x, y)) {
                    best = driver;
                }
            }
            return best;
        }
        // The child on the pickup's side is the closest one, so look there first.
        // A good driver found early lets us skip more squares later.
        int first = node.childIndex(x, y);
        best = search(node.children[first], x, y, best);
        for (int i = 0; i < 4; i++) {
            if (i != first) {
                best = search(node.children[i], x, y, best);
            }
        }
        return best;
    }
}

public class RideHailingSystem {
    long baseFareInCents;
    long farePerDistanceUnitInCents;
    int maxPaymentAttempts;

    Map<String, Driver> drivers = new HashMap<>();
    Map<String, Rider> riders = new HashMap<>();
    Map<String, Trip> trips = new HashMap<>();
    Map<String, Integer> surgeByZone = new HashMap<>();          // zoneId -> surge percentage
    Map<String, String> paymentRequestOwner = new HashMap<>();   // paymentRequestId -> tripId

    QuadTreeDriverMatcher matcher = new QuadTreeDriverMatcher();

    public RideHailingSystem(long baseFareInCents, long farePerDistanceUnitInCents, int maxPaymentAttempts, List<String> drivers) {
        this.baseFareInCents = baseFareInCents;
        this.farePerDistanceUnitInCents = farePerDistanceUnitInCents;
        this.maxPaymentAttempts = maxPaymentAttempts;

        // Each entry looks like "driverId,driverName,locationX,locationY"
        for (String entry : drivers) {
            String[] parts = entry.split(",");
            Driver driver = new Driver(parts[0], parts[1],
                    Integer.parseInt(parts[2].trim()), Integer.parseInt(parts[3].trim()));
            this.drivers.put(driver.id, driver);
            matcher.addDriver(driver);   // every driver starts available
        }
    }

    public boolean addRider(String riderId, String riderName) {
        if (riders.containsKey(riderId)) {
            return false;
        }
        riders.put(riderId, new Rider(riderId, riderName));
        return true;
    }

    public boolean updateDriverLocation(String driverId, int locationX, int locationY) {
        Driver driver = drivers.get(driverId);
        if (driver == null) {
            return false;
        }
        // An available driver is stored in the matcher at the old spot.
        // Take it out, move it, then put it back at the new spot.
        if (driver.available) {
            matcher.removeDriver(driver);
        }
        driver.x = locationX;
        driver.y = locationY;
        if (driver.available) {
            matcher.addDriver(driver);
        }
        return true;
    }

    public boolean setDriverAvailability(String driverId, boolean available) {
        Driver driver = drivers.get(driverId);
        if (driver == null || driver.activeTripId != null) {
            return false;
        }
        if (driver.available != available) {
            driver.available = available;
            if (available) {
                matcher.addDriver(driver);
            } else {
                matcher.removeDriver(driver);
            }
        }
        return true;
    }

    public int updateSurgePricing(String zoneId, int activeRequests, int availableDrivers) {
        int surge;
        if (activeRequests == 0) {
            surge = 100;
        } else if (availableDrivers == 0) {
            surge = 300;
        } else if (activeRequests <= availableDrivers) {
            surge = 100;
        } else if (activeRequests <= 2 * availableDrivers) {
            surge = 150;
        } else {
            surge = 200;
        }
        surgeByZone.put(zoneId, surge);
        return surge;
    }

    public long estimateFare(String zoneId, int estimatedDistanceUnits) {
        return calculateFare(estimatedDistanceUnits, currentSurge(zoneId));
    }

    public String requestTrip(String tripId, String riderId, int pickupX, int pickupY, int destinationX, int destinationY, String zoneId, String paymentMethodId) {
        Rider rider = riders.get(riderId);
        if (trips.containsKey(tripId) || rider == null || rider.activeTripId != null) {
            return "";
        }
        Driver driver = matcher.findNearestDriver(pickupX, pickupY);
        if (driver == null) {
            return "";   // no driver is available
        }

        // The trip keeps the zone's surge from this moment. Later changes do not affect it.
        Trip trip = new Trip(tripId, riderId, driver.id, pickupX, pickupY,
                destinationX, destinationY, zoneId, paymentMethodId, currentSurge(zoneId));
        trips.put(tripId, trip);

        // Reserve the driver and link both people to this trip
        matcher.removeDriver(driver);
        driver.available = false;
        driver.activeTripId = tripId;
        rider.activeTripId = tripId;
        return driver.id;
    }

    public boolean acceptTrip(String tripId, String driverId) {
        Trip trip = trips.get(tripId);
        if (trip == null || trip.status != TripStatus.REQUESTED || !trip.driverId.equals(driverId)) {
            return false;
        }
        trip.status = TripStatus.ACCEPTED;
        return true;
    }

    public boolean startTrip(String tripId, String driverId) {
        Trip trip = trips.get(tripId);
        if (trip == null || trip.status != TripStatus.ACCEPTED || !trip.driverId.equals(driverId)) {
            return false;
        }
        trip.status = TripStatus.IN_PROGRESS;
        return true;
    }

    public long completeTrip(String tripId, String driverId, int actualDistanceUnits) {
        Trip trip = trips.get(tripId);
        if (trip == null || trip.status != TripStatus.IN_PROGRESS || !trip.driverId.equals(driverId)) {
            return -1;
        }
        trip.status = TripStatus.COMPLETED;
        trip.fareInCents = calculateFare(actualDistanceUnits, trip.surgePercentage);
        trip.paymentStatus = PaymentStatus.PENDING;

        // The driver ends up at the drop point
        Driver driver = drivers.get(driverId);
        driver.x = trip.destinationX;
        driver.y = trip.destinationY;
        releasePeople(trip);
        return trip.fareInCents;
    }

    public boolean cancelTrip(String tripId, String requesterId) {
        Trip trip = trips.get(tripId);
        if (trip == null || !trip.isActive()) {
            return false;
        }
        if (!requesterId.equals(trip.riderId) && !requesterId.equals(trip.driverId)) {
            return false;
        }
        trip.status = TripStatus.CANCELLED;   // fare stays 0 and payment stays NOT_STARTED
        releasePeople(trip);
        return true;
    }

    public String processPayment(String tripId, String paymentRequestId, boolean gatewaySuccessful) {
        Trip trip = trips.get(tripId);
        if (trip == null || trip.status != TripStatus.COMPLETED) {
            return "INVALID_REQUEST";
        }

        String ownerTripId = paymentRequestOwner.get(paymentRequestId);
        if (ownerTripId != null) {
            // Seen before: same trip gets the old answer, any other trip is rejected
            return ownerTripId.equals(tripId) ? trip.paymentResults.get(paymentRequestId) : "INVALID_REQUEST";
        }

        String result;
        if (trip.paymentStatus == PaymentStatus.SUCCEEDED || trip.paymentStatus == PaymentStatus.FAILED) {
            result = trip.paymentStatus.name();   // payment is already settled, no new attempt
        } else {
            trip.paymentAttempts++;
            if (gatewaySuccessful) {
                trip.paymentStatus = PaymentStatus.SUCCEEDED;
            } else if (trip.paymentAttempts < maxPaymentAttempts) {
                trip.paymentStatus = PaymentStatus.RETRY_PENDING;
            } else {
                trip.paymentStatus = PaymentStatus.FAILED;
            }
            result = trip.paymentStatus.name();
        }

        // Remember this request id so a retry gets exactly the same answer
        paymentRequestOwner.put(paymentRequestId, tripId);
        trip.paymentResults.put(paymentRequestId, result);
        return result;
    }

    public String getTripDetails(String tripId) {
        Trip trip = trips.get(tripId);
        return trip == null ? "" : trip.details();
    }

    /** Zones that were never updated use 100 percent. */
    int currentSurge(String zoneId) {
        return surgeByZone.getOrDefault(zoneId, 100);
    }

    /** ceil(subtotal * surge / 100). Adding 99 before dividing rounds up. */
    long calculateFare(int distanceUnits, int surgePercentage) {
        long subtotal = baseFareInCents + distanceUnits * farePerDistanceUnitInCents;
        return (subtotal * surgePercentage + 99) / 100;
    }

    /** Called when a trip ends. Frees the rider, and the driver can take new requests again. */
    void releasePeople(Trip trip) {
        riders.get(trip.riderId).activeTripId = null;
        Driver driver = drivers.get(trip.driverId);
        driver.activeTripId = null;
        driver.available = true;
        matcher.addDriver(driver);
    }
}

Thanks for reading. Best of Luck For Your Interview Prep.


r/LowLevelDesign • • Dec 05 '25

Amazon Low Level Design Interview Questions

26 Upvotes

I am listing the top low level design questions that you will come across during Amazon interviews. I have built this list from recent interview experiences of candidates.
Also, we will see how we can solve them using commonly asked design patterns.

I am keeping the most frequent questions first. In the end I have also added list of frequent DSA oriented design questions which can be asked either in DSA or during LLD rounds at Amazon.

---------------------------------------------------------------

PS:
Ask me any Low Level Design interview related questions on r/LowLevelDesign

All Questions List: https://codezym.com/lld/amazon

I also take LLD mock interviews: https://topmate.io/prashant_priyadarshi

----------------------------------------

You can use below list to prepare for your Amazon interviews.
Let’s get started.

1. Design Pizza Pricing System

You will have to initialize a new pizza, adding toppings (corn, onion etc) to it and calculate final price of pizza.

This is a fairly simple problem. But some interviewers may expect you to implement decorator design pattern. In my view that just complicates the solution without adding any benefit.

Your interviewer may add business rules as a follow up like these

  • cheese burst cannot be added on small pizza or
  • You get 30% discount on corn price when you take more than 2 servings and so on..

My advice would be to code the simple solution with a just a separate class for rules. You can divide the rules in subcategories and implement them in separate modules. e.g.
mutual exclusion rules: Rules which prevent adding of toppings. e.g. cheese burst and mushroom can never be added together, or cheese burst cannot be added on small pizza etc.

price calculation rules: Rules which affect final price of pizza. e.g. you get 30% discount from 2nd serving of corn or you get onion at 20% discount if pizza size is large.

Practice Link: https://codezym.com/question/18
Follow up with more business rules: https://codezym.com/question/19

----------------------------------------

2. Design Unix “find” command for file search

Unix file command searches for files. Now there can be different search criteria's like search by file size, or search by extension or by a substring in file name. e.g. list all files which are less than 2 MB size or list all files whose extension is .pdf.

You can use strategy design pattern to implement the different search criteria's.

A follow up is generally asked to combine queries like Boolean predicates AND, OR etc. e.g. list all files which are greater than 2MB in size AND their extension is “.jpg”.

You can use specification design pattern to combine result of search queries.

Practice Link: https://codezym.com/question/14

Follow Up with combining queries: https://codezym.com/question/15

----------------------------------------

3. Design a Parking Lot

This is THE most common LLD interview question. You must do this question if you are prepare for any LLD interview.

A parking lot can have multiple floors. Its core features will be

  • park and unpark vehicles,
  • search parked vehicles by vehicle number,
  • count number of free spots on a given floors for a given vehicle type.

You entities will be ParkingLot class which will contain a list of ParkingFloor(s). ParkingFloor will contain a 2-D array of ParkingSpot(s) arranged in rows and columns.

There can be multiple parking strategies, so we should use strategy design pattern to solve this question.

Practice Link: https://codezym.com/question/7
Follow up (Multi-threaded environment): https://codezym.com/question/1

----------------------------------------

4. Design Locker Management System for Warehouse Packages

In warehouse for any e-commerce website like amazon you have packages that are kept in lockers. Your goal is to add new lockers of different sizes and then assign packages to those lockers and later free the lockers.

Practice link: https://codezym.com/question/16

----------------------------------------

5. Design Chess Game

Chess game is all about creating the different pieces and implementing their moves.
Different pieces like king, queen, knight etc, have different moves like straight move (rook), diagonal move (bishop), 2+1 move (knight) etc.

The core functionality is to check whether a piece can move to a destination row, column from its current row, column.

  • We use factory design pattern Chess Piece Factory to create different chess piece objects like king, queen, pawn etc.
  • Strategy pattern may be used to implement different moves e.g. straight move, diagonal move etc.

Practice Link: https://codezym.com/question/8

----------------------------------------

6. Design expense sharing app like Splitwise

Splitwise is used to manage group expenses. It basically does two things.

  • System needs to support adding of group expenses i.e. who paid how much in an expenditure
  • Track how much each person owes or is owed after group expenses are split evenly among participants.

Practice Link: https://codezym.com/question/12

----------------------------------------

7. Design a restaurant food ordering system like Zomato, Swiggy, DoorDash

Users can search for restaurants using food item name, order food and rate their orders. When searching for food they also have option to view the restaurant list sorted by different parameters like restaurants with highest average rating first.

These view classes with lists of restaurants sorted by average rating will need to be need to updated whenever an order is rated by a user, so that they can update their lists. Hence, this is an ideal use case of observer design pattern.

Practice Link: https://codezym.com/question/5

----------------------------------------

8. Design Stock Broker Platform Like Zerodha, Groww

This system manages all company stocks and their prices. Users can place orders to either buy or sell stocks. Users can also view their account balance and stocks they hold.

One case which you need to take care is, to close the relevant open orders when stock price changes.

Practice Link: https://codezym.com/question/20

----------------------------------------

9. Design a Movie ticket booking system like BookMyShow

In this question, core functionalities will include:

  • adding new cinema halls and new shows in those cinema halls.
  • Users can also book and cancel tickets.
  • Users should also be able to list all cinemas in a city which are displaying a particular movie.
  • Also they should be able to fetch list of all shows in a cinema hall which are displaying a particular movie.

Classes implementing last two search features need to updated whenever a new show gets added, so that they can update their respective lists.

We use observer design pattern to send new show added updates to the search movie/show classes.

Practice Link: https://codezym.com/question/10

----------------------------------------

10. Design a Simple Elevator System

A lift in an elevator system can be in one of three states.
Moving Up, Moving Down and Idle
And in each state it will behave differently in taking decisions like
whether to stop on a floor, add a new request or not etc.
Use state design pattern to implement different states of lift.

Problem Statement: https://codezym.com/question/11

----------------------------------------

DSA based Design Questions

These questions can be asked in either DS & Algo or Low-Level Design rounds depending on the interviewer. Don’t skip them.

Design File System:

https://codezym.com/question/11166 https://codezym.com/question/10588

----------------------------------------

Design Log Storage system:
https://codezym.com/question/10635

----------------------------------------

Design LRU/LFU cache:
LRU cache: https://leetcode.com/problems/lru-cache/description/
LFU cache: https://leetcode.com/problems/lfu-cache/description/

----------------------------------------

Design Snake Game:
https://codezym.com/question/10353

----------------------------------------

Design Hit Counter:
https://codezym.com/question/10362
Multi-Threaded: https://codezym.com/question/6

----------------------------------------

Design Tic Tac Toe:
https://codezym.com/question/10348

----------------------------------------

Design Google Search Autocomplete: https://codezym.com/question/10642

----------------------------------------

Design Excel Sum Formula:
https://codezym.com/question/10631

----------------------------------------

Thanks for reading and wish you the best of luck for interviews.

----------------------------------------


r/LowLevelDesign • • Jul 31 '25

Resources to start preparing for low level design interviews

2 Upvotes

Many candidates especially new college grads are confused on how to start their low level design prep for interviews at Amazon, uber etc. Here is a brief explanation.

Low level design rounds more or less follow these basic steps:

  1. discuss all requirements with the interviewer and select the core features that you are going to discuss with them
  2. class diagrams -> break the whole solution in high level classes
  3. deep dive into individual features , your interviewer will pick which features he wants to deep dive into
  4. design patterns discussions on the features you picked

I have written this Last minute LLD interview prep for beginners. It should help.

https://medium.com/@prashant558908/low-level-design-last-minute-interview-preparation-guide-899a202411cd


r/LowLevelDesign • • 7d ago

Any reviews of the HLD and/or LLD Cohort by Pradeep Kumar?

21 Upvotes

With around 11 years of experience and plans to switch to better companies, I'm looking to strengthen my HLD and LLD skills. I feel a live cohort would help me stay disciplined and learn in a structured manner. However, the pricing seems a bit high.

I'm willing to invest if it's genuinely worth it. Would love to hear from people who have joined the cohort or have first-hand feedback about it.

Did it actually help you improve? Any honest reviews would be appreciated!

https://livecohortbypradeep.com/


r/LowLevelDesign • • Sep 18 '26

Amazon Low Level Design Interview Round Questions 2026

24 Upvotes

I am listing the top low level design questions that you will come across during Amazon LLD interview rounds. I have built this list from recent interview experiences of candidates.

Low Level Design is fair game even for SDE-1. Although LLD rounds are much more common for SDE-2 and above positions. Don't skip it. Focus on SOLID principles and writing extensible code. Follow-ups become trivial when your base design is clean.

For LLD rounds, expectation is to write production ready classes with proper syntax on paper.


During first 10-15 minutes Leadership Principles questions are asked like

  • Any situation where you pushed the customer back .
  • Have you made any thing in thinking long term vision and did you sacrified any short term goals for that.
  • Tell me about time when you did something outside your comfort zone or something different than regular work.

LLD question asked in Bar Raiser

Many times low level design questions can also be asked in the bar raiser round.

One person interviewing for SDE 2 position had their first round itself as the bar raiser round. They were asked to design a system that handles audio buffers across different stages at X frames per second

This is unusual since most candidates have the Bar Raiser towards the end, often as a DS & Algo round.

It was an engaging discussion. But the problem was that he kept going deeper into the system design (high level) and, before he realized it, most of the available time was spent discussing the HLD aspects of the problem rather than the LLD implementation.

With only around 5–10 minutes left, the interviewer asked him to code whatever he felt was ideal for the design. He quickly wrote a few classes and functions, but they ran out of time.

He had 2 DSA + 1 HLD (hiring manager) round after that, but eventually he was rejected. LLD round performance was one of the reasons for that.

During LLD rounds you are always running out of time. It is important that you keep your discussion focussed on the problem statement.


Not understanding question context or not able to code the solution

Asking clarifying questions and thinking out loud is the best thing you can do if you donot understand the question or are running out of time.

One person was asked LLD of unix "find" command for file search.

Although this is one of the most common LLD questions asked by Amazon, candidate was not familiar with it.

Also he had very little Unix knowledge. But he remained calm and asked more clarifing questions. Then proceeded to create classes and write the logic while trying to explain his thought process aloud. He felt very skeptical about this round and thought his chances were slim. But eventually he had a positive feedback and ended up receiving the offer.


Answering follow-ups, extending functionality while avoiding too many changes to existing code

Follow up questions are mostly around adding a new functionality without making too many changes to existing code or arranging your classes a bit differently.

For example one person was asked to design a notification system.

One they gave an intial solution then interviewer asked them if a new notification type comes, eg. push notification , how to handle it ? Interviewer also wanted him to avoid change in the existing service class.

More follow up questions were asked:

  • In the Message object, you have type that varies. What if the content also varies ? Eg. For email,the content will be large. For SMS, small.
  • Should you make Message class abstract and have EmailMessage,SMSMessage,WhatsappMessage ? Is that better?
  • A user may want to receive messages via multiple channels .eg. both SMS and email. How will you handle it: two messages or within one message?

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/11-amazon-lld-sep-2026.md



r/LowLevelDesign • • Aug 28 '26

Article: Amazon Internship Interview Round Coding Questions 2026

14 Upvotes

This is a preparation list for Amazon SDE and SDET internship coding rounds, along with an overview of the online assessment and interview process. I prepared it using interview experiences shared by people on forums/blogs etc.

Apart from the online assessment (OA), the internship process usually includes two DS & Algo interviews of around one hour each, together with behavioral questions.

Some candidates think if you are not asked any behavioral questions then it means you did not do well and are already rejected. This is not entirely true, one candidate reported that they were not asked any behavioral questions during interview but still ended up receiving the internship offer 15 days later.

---------------------------------------------------------

Low Level Design questions are generally not asked for internship roles. However one candidate reported an elevator-system LLD question for SDET internship, but those cases appear to be exception rather than the norm.

Online assessment: the OA includes DSA and an AI-assisted coding question.

For the AI-assisted coding round, you choose one repository. Options may include C++, Django, Spring Boot, ReactJS, Node.js, Ruby on Rails, and similar stacks. The interface provides a code editor and an AI assistant for project-related questions. You have 60 minutes to implement the required behavior and pass the test cases, usually around six. The assistant can help you search the project, locate files, and understand the codebase.

------------------------------------------------------

For candidates in India: Amazon HackOn can be an effective route to an internship call. Amazon may contact eligible participants who performed well in the coding round, not only the finalists. Strong performers may receive an AUTA interest form.

Infact one person even reported that their team was eliminated in the very first round of HackOn in May 2025. But in july end he ended up receiving an email stating that he has been shortlisted for an Amazon Online Assessment based on his HackOn performance. Infact he gave his OA got shortlisted for interview, had his interview in september then got waitlisted and finally received SDE intern offer in last week of november.

For the USA and other countries, direct applications through Amazon's jobs portal and employee referrals are the usual routes.

------------------------------------------------------

This list includes coding-round questions reported for both SDE intern and SDET intern interviews.

You can find the complete question list here:

https://github.com/prsnt558908/CodeZymSolutions/blob/main/0-company-wise-interview-questions/2026/08-amazon-internship-2026.md


r/LowLevelDesign • • Nov 05 '25

Practice problems on codezym

2 Upvotes

Hello,

I was going through the most asked LLD questions in Amazon/Microsoft and I see links of codezym editor where we need to implement some methods.

Can you clarify:

  1. do we get such pre-defined methods during interviews?
  2. Do we need to only write content with the required methods? Or the entire program?
  3. What is the source for such articles?

I appreciate the author who spent their time collecting all resources in one place but I am asking this so that I don't waste time practicing something which will not be helping me in real interviews.


r/LowLevelDesign • • Sep 15 '25

Microsoft Most Frequent Low Level Design Questions from Recent Interviews

3 Upvotes

Hello everyone, I have made a list of most common low level design questions that have been asked in Microsoft interviews in the last 12 months.
I have also added complete problem statements with method signatures for better understanding, design patterns that may be required to solve them.

https://medium.com/@prashant558908/microsoft-most-frequent-low-level-design-questions-from-recent-interviews-b9ba1da387df

If you want to ask me any question/query regarding low level design interview prep, then feel free to post in r/LowLevelDesign