Airbnb logo

Airbnb Interview Questions

50 practice questions for Airbnb technical interviews

Airbnb software engineer interviews cover algorithms, data structures, system design, and coding problems drawn from real interview rounds.

Software Engineer Backend Engineer Frontend Engineer Full Stack Engineer Mobile Engineer Data Engineer Data Scientist ML Engineer DevOps Engineer DevOps Engineer Product Manager SRE Security Engineer Engineering Manager Data Analyst UX/UI Designer QA Engineer
coding Hard Verified Question #1

1. Best Service For Rental Properties


Category: Graph coding problem
You are helping users find the most cost-effective way to get all the services they want for their rental property. You are given: - A list of...
Input: Graph (nodes and edges)
Output: Computed result
Want to practise this one?
Create a free account to open the full question and practise Airbnb questions with AI.
Sign up free
coding Hard Verified Question #2

2. Best Ski Route


Category: Graph coding problem

Question You are skiing down from the top of a mountain and want to maximize your score when you reach the finish. There are multiple routes you...

Input: Graph (nodes and edges)
Output: Computed result
coding Medium Verified Question #3

3. Design A Queue


Category: Array coding problem
Design a queue data structure that mimics memory allocation patterns. The queue must store elements in fixed-size blocks (arrays), where each...
Input: Array
Output: Computed result
coding Hard Verified Question #4

4. Menu Order Equaling Target Sum


Category: Algorithm coding problem
You are given a menu containing prices of individual items. Given a target amount of money, find all possible combinations of menu items that...
Input: Integer(s)
Output: Integer
coding Hard Verified Question #5

5. Most Cost Effective Menu Order


Category: Dynamic programming coding problem
You are building an app that helps users determine the most cost-effective order they can place at a restaurant for the food items they want. You...
Input: List
Output: Computed result
coding Medium Verified Question #6

6. Best Way To Split Stay


Category: Graph coding problem
You are building a property recommendation system for vacation rentals. Given a list of available properties, you need to find the optimal...
Input: Graph (nodes and edges)
Output: Integer
coding Medium Verified Question #7

7. Maximize Task Points


Category: Algorithm coding problem
You are given a set of tasks, each with a deadline and a reward (profit) for completing it. Each task takes exactly one day to complete, and only...
Input: Given input
Output: Computed result
coding Hard Verified Question #8

8. Collatz Sequence


Category: Algorithm coding problem
The Collatz conjecture is a famous unsolved problem in mathematics. For any positive integer n, the sequence is defined as follows: - If n is...
Input: Integer(s)
Output: Computed result
coding Medium Verified Question #9

9. Shortest Maze Path


Category: Grid/matrix coding problem

Question You are in a maze that is represented as a grid of cells, where each cell is either empty (O) or blocked (X). You can move up, down,...

Input: 2D grid
Output:** Integer
coding Hard Verified Question #10

10. Implement Refunds


Category: Algorithm coding problem

Question AirBnB has a need to support refunds for our customers in case of booking changes or cancellations.

Input: List
Output: Array
coding Hard dynamic programming #1

1. [AI Enabled Coding] Neighborhood Group Booking Optimizer


Scenario
Airbnb's group-trip planner needs to suggest a collection of available listings in one neighborhood that can accommodate everyone traveling together. Travelers want as little unused capacity as possible and, secondarily, fewer separate properties to coordinate. You may use an AI assistant while implementing the optimizer, but you should explain its correctness and computational limits.
Part 1 — Find the smallest suitable collection
  • Each property record contains id, neighborhood, host_id, capacity, and nightly_price. All keys and values are strings; prices are dollar amounts with exactly two decimal places.

  • Only properties whose neighborhood exactly equals the requested neighborhood are eligible. All input properties are already available for the requested dates, and each may be selected at most once.

  • Select properties with total capacity at least group_size. Minimize total capacity first, then the number of selected properties, then the lexicographically smallest sorted list of property IDs.

  • Return selected IDs in ascending lexicographic order. If no selection can accommodate the group, return an empty selection. Prices and hosts do not affect eligibility or ranking in Part 1.

  • Implement optimize_properties(properties: list[dict[str, str]], neighborhood: str, group_size: int). The return type is up to the candidate; Example 1 uses a JSON array of IDs as its reference representation.


Example 1:
Input:
{
  "properties": [
    {"id": "A", "neighborhood": "Mission", "host_id": "h1", "capacity": "4", "nightly_price": "70.00"},
    {"id": "B", "neighborhood": "Mission", "host_id": "h2", "capacity": "3", "nightly_price": "50.00"},
    {"id": "C", "neighborhood": "Mission", "host_id": "h3", "capacity": "7", "nightly_price": "150.00"},
    {"id": "D", "neighborhood": "Sunset", "host_id": "h4", "capacity": "7", "nightly_price": "120.00"},
    {"id": "E", "neighborhood": "Mission", "host_id": "h5", "capacity": "8", "nightly_price": "100.00"}
  ],
  "neighborhood": "Mission",
  "group_size": 7
}

Output:
["C"]

Explanation: A + B and C both provide exactly 7 places, but C uses one property instead of two. E provides 8 places, and D is ineligible because its neighborhood differs. Price is not an objective.
Part 2 — Add traveler-supplied booking policies
The trip planner now accepts policy records supplied by other product teams. Extend Part 1 without replacing its ranking or neighborhood filtering, and make the approach flexible enough to support future resource-cap policies. Discuss how the return type changes before implementing this extension.
  • Implement optimize_with_policies(properties: list[dict[str, str]], neighborhood: str, group_size: int, policies: list[dict[str, str]]). The return type remains your choice; the examples use a summary object.

  • Support {"type": "nightly_budget", "limit": "120.00"}: the sum of selected nightly prices must be less than or equal to the limit. Use exact cents, not floating-point arithmetic.

  • Support {"type": "host_limit", "limit": "1"}: select at most the specified number of properties from each host. This is a per-host limit, not a limit on the number of distinct hosts.

  • Every supplied policy must hold. An omitted policy imposes no restriction. There is at most one policy of each type; reject an unknown type with ValueError.

  • The optimization order remains total capacity, property count, then sorted IDs. A lower price does not break ties or outrank better capacity utilization.

  • A successful summary contains status: "OK", sorted property_ids, integer total_capacity, and total_nightly_price formatted with two decimal places. An impossible result contains status: "IMPOSSIBLE", an empty ID list, capacity 0, and price "0.00".


Example 2:
Input:
{
  "properties": [
    {"id": "A", "neighborhood": "Mission", "host_id": "h1", "capacity": "4", "nightly_price": "70.00"},
    {"id": "B", "neighborhood": "Mission", "host_id": "h2", "capacity": "3", "nightly_price": "50.00"},
    {"id": "C", "neighborhood": "Mission", "host_id": "h3", "capacity": "7", "nightly_price": "150.00"},
    {"id": "D", "neighborhood": "Sunset", "host_id": "h4", "capacity": "7", "nightly_price": "120.00"},
    {"id": "E", "neighborhood": "Mission", "host_id": "h5", "capacity": "8", "nightly_price": "100.00"}
  ],
  "neighborhood": "Mission",
  "group_size": 7,
  "policies": [
    {"type": "nightly_budget", "limit": "120.00"},
    {"type": "host_limit", "limit": "1"}
  ]
}

Output:
{
  "status": "OK",
  "property_ids": ["A", "B"],
  "total_capacity": 7,
  "total_nightly_price": "120.00"
}

Explanation: A + B provides 4 + 3 = 7 places for 70.00 + 50.00 = 120.00, exactly the budget. Each selected host contributes one property, satisfying the host limit. C exceeds the budget by 30.00. E costs less but provides 8 places, so it loses on the primary objective.
Example 3:
Input:
{
  "properties": [
    {"id": "P", "neighborhood": "Mission", "host_id": "h1", "capacity": "4", "nightly_price": "60.00"},
    {"id": "Q", "neighborhood": "Mission", "host_id": "h1", "capacity": "3", "nightly_price": "40.00"},
    {"id": "R", "neighborhood": "Mission", "host_id": "h2", "capacity": "7", "nightly_price": "130.00"},
    {"id": "S", "neighborhood": "Mission", "host_id": "h3", "capacity": "8", "nightly_price": "101.00"}
  ],
  "neighborhood": "Mission",
  "group_size": 7,
  "policies": [
    {"type": "nightly_budget", "limit": "100.00"},
    {"type": "host_limit", "limit": "1"}
  ]
}

Output:
{
  "status": "IMPOSSIBLE",
  "property_ids": [],
  "total_capacity": 0,
  "total_nightly_price": "0.00"
}

Explanation: P + Q provides 4 + 3 = 7 places for exactly 100.00, but selects two properties from h1, exceeding the limit of 1. R and S individually exceed the budget by 30.00 and 1.00. Adding either to another selection cannot reduce its cost. The selection P + Q + R breaks both policies: its price is 230.00 and its h1 count is 2. The only remaining feasible nonempty selections are P and Q, neither of which accommodates 7 guests.
Notes:
  • There are at most 22 properties, with unique nonempty ASCII IDs; each capacity is an integer from 1 to 20, and group_size is from 1 to 440. Exact optimization is required; explain why greedy selection is insufficient.

  • Prices and budget limits range from "0.00" to "10000.00"; a host limit is an integer string from "0" to "22". Except for unknown policy types, inputs satisfy the stated schema.

  • Prices are nightly totals for the property; ignore taxes, fees, date changes, and simultaneous inventory updates. Future policies supported by your extension mechanism should have hashable sufficient state and irreversible cap violations as properties are added.
Want to practise this one?
Create a free account to open the full question and practise Airbnb questions with AI.
Sign up free
coding Hard dynamic programming #2

2. [Dynamic Programming] — Optimize a group booking across Airbnb properties


Background
Airbnb group-trip planning can require multiple properties when a party cannot fit into one listing. A booking optimizer should select properties in the requested neighborhood while avoiding unnecessary unused capacity and minimizing the number of separate properties travelers must coordinate.
Problem statement
You are given a list of properties, each represented by a record containing a unique integer id, a string neighborhood, and a positive integer capacity. All properties are available for the requested dates, and each property can be selected at most once.
Select a subset of properties in target_neighborhood whose combined capacity is at least group_size. Optimize the selection in this order:
1. Minimize total capacity while accommodating the entire group.
2. Among selections with the same total capacity, minimize the number of properties.
Return the selected property IDs in ascending order. If multiple selections remain tied on both objectives, any tied selection is accepted. Return an empty list if no feasible selection exists, or if group_size is zero. Neighborhood matching is case-sensitive, and travelers may be divided among selected properties without any additional restrictions.
Function or class signature
  • optimize_booking(properties: list[Property], target_neighborhood: str, group_size: int) -> list[int]

  • Property has fields id: int, neighborhood: str, and capacity: int.


Example 1:
Input:
{
  "properties": [
    {"id": 101, "neighborhood": "SoMa", "capacity": 6},
    {"id": 102, "neighborhood": "SoMa", "capacity": 4},
    {"id": 103, "neighborhood": "SoMa", "capacity": 10},
    {"id": 104, "neighborhood": "SoMa", "capacity": 5},
    {"id": 105, "neighborhood": "Mission", "capacity": 10}
  ],
  "target_neighborhood": "SoMa",
  "group_size": 10
}
Output:
[103]
Explanation: Both [101, 102] and [103] provide exactly 10 spaces. Property 103 wins because it uses one property instead of two. Property 105 is in the wrong neighborhood.
Example 2:
Input:
{
  "properties": [
    {"id": 201, "neighborhood": "Mission", "capacity": 6},
    {"id": 202, "neighborhood": "Mission", "capacity": 5},
    {"id": 203, "neighborhood": "Mission", "capacity": 4},
    {"id": 204, "neighborhood": "SoMa", "capacity": 8}
  ],
  "target_neighborhood": "Mission",
  "group_size": 8
}
Output:
[202, 203]
Explanation: No eligible selection has total capacity 8. Properties 202 and 203 provide 9 spaces, which is better than the other feasible totals of 10, 11, and 15.
Constraints:
  • 0 <= len(properties) <= 2000.

  • At most 36 properties belong to target_neighborhood.

  • Property IDs are distinct integers in [1, 10^9].

  • 1 <= capacity <= 10^9.

  • 0 <= group_size <= 10^12.

  • Neighborhood names and target_neighborhood are strings of length 1 through 100.

  • Capacity values are too large for a dynamic-programming table indexed by total capacity.


Follow-up:
Suppose up to 500 properties match the neighborhood, but each capacity is at most 100. How would you replace your algorithm with capacity-indexed dynamic programming while preserving both optimization objectives and reconstructing the selected IDs?
coding Medium hash map #3

3. Coding — Find the Most Booked Property

1. Background: Airbnb displays several rental listings for travelers, and understanding the popularity of these properties helps hosts maximize their bookings and visibility. This problem involves analyzing booking data to identify which property has been booked the most.
2. Problem statement: Given a list of bookings, where each booking is represented as a tuple (property_id, user_id), write a function that returns the property_id of the property that has the most bookings. If there are ties, return the property with the smallest property_id.
3. Function/class signature:
- def most_booked_property(bookings: List[Tuple[int, int]]) -> int:
4. Example 1:
- Input: [(1, 101), (2, 102), (1, 103), (3, 104), (2, 105), (1, 106)]
- Output: 1
- Explanation: Property 1 is booked by users 101, 103, and 106 (3 bookings), while properties 2 and 3 are booked 2 and 1 times respectively.
5. Example 2:
- Input: [(1, 101), (2, 102), (3, 103), (2, 104), (1, 105), (3, 106), (1, 107)]
- Output: 1
- Explanation: Property 1 is booked 3 times, while properties 2 and 3 are tied with 2 bookings each but we choose 1 because it has the most.
6. Constraints:
- 1 <= len(bookings) <= 10^6
- 1 <= property_id, user_id <= 10^9
coding Medium database #4

4. DATABASE — Count Underperforming Listings

1. Background: Airbnb constantly seeks to optimize its platform for hosts and guests. A key metric in this optimization is identifying underperforming listings. This approach directly affects overall customer satisfaction and revenue.
2. Problem statement: Given a list of listings with associated views, bookings, and ratings, determine how many listings are considered underperforming. A listing is classified as underperforming if it has fewer than min_views AND fewer than min_bookings AND a rating lower than min_rating.
3. Function signature: def count_underperforming_listings(listings: List[Tuple[int, int, float]], min_views: int, min_bookings: int, min_rating: float) -> int
4. Example 1:
Input: listings = [(100, 5, 4.5), (50, 3, 4.0), (20, 0, 3.5)], min_views = 30, min_bookings = 2, min_rating = 4.0
Output: 2
Explanation: The last two listings are underperforming as they either have less than 30 views, less than 2 bookings, or a rating below 4.0.
5. Example 2:
Input: listings = [(200, 15, 4.8), (150, 10, 3.0), (40, 1, 2.5)], min_views = 50, min_bookings = 5, min_rating = 3.5
Output: 1
Explanation: Only the last listing is underperforming based on the conditions specified.
6. Constraints:
- The listings array can contain between 1 and 10^4 entries.
- Each entry's views and bookings are non-negative integers.
- Ratings are floats ranging from 0.0 to 5.0.
coding Medium hash map #5

5. Hash Map — Count Listings Based on Reviews

Background: Airbnb has a vast number of listings, each with varying numbers of reviews. Understanding review distributions helps improve listing quality and user satisfaction.
Problem statement: Given a list of reviews represented as strings where each review contains the listing_id, return a hash map (dictionary) that counts the number of reviews for each listing. Each review is structured as "listing_id: review content". The output should be a dictionary where the keys are listing_id and the values are the counts of reviews for that listing.
Function/class signature:
  • def count_reviews(reviews: List[str]) -> Dict[str, int]:


Example 1:
  • Input: reviews = ["1: Great stay!", "1: Loved it!", "2: Not bad.", "1: Would come again."]

  • Output: {'1': 3, '2': 1}

  • Explanation: Listing 1 has three reviews while listing 2 has one.


Example 2:
  • Input: reviews = ["3: Awesome experience!", "3: Best place ever!", "2: Clean and nice."]

  • Output: {'3': 2, '2': 1}

  • Explanation: Listing 3 has two reviews while listing 2 has one.


Constraints:
  • The number of reviews will be at most 10^5.

  • Each review will consist of a valid listing_id followed by text (up to 200 characters).
coding Medium caching #6

6. Caching Underperforming Listings: Identify and cache underperforming listings on Airbnb


Background: Underperforming listings can significantly impact hosts' revenue and guest experiences. Identifying these listings allows Airbnb to provide tailored insights to hosts, enhancing their visibility and ultimately improving booking rates.
Problem statement: You are given a list of listings, where each listing contains its ID, average reviews over the past month, and number of views. Define a function that identifies listings which have received lower than average views compared to the total views of all listings and caches these listings for quick access.
Define the following method:
  • List[int] identify_underperforming_listings(listings: List[Tuple[int, int, int]]) -> List[int]


Example 1:
Input: listings = [(1, 5, 100), (2, 4, 50), (3, 3, 75)]
Output: [2, 3]
Explanation: Listing 2 has 50 views, which is under the average of (100 + 50 + 75) / 3 = 75, and Listing 3 has 75 views, also under average.
Example 2:
Input: listings = [(1, 4, 200), (2, 3, 200), (3, 5, 300)]
Output: []
Explanation: All listings have views equal to or above the average.
Constraints:
  • For listings, 1 ≤ number of listings ≤ 1000

  • Each listing has a unique ID that is an integer from 1 to 10^6

  • Review score is an integer from 1 to 5

  • View count is a non-negative integer up to 10000


coding Medium hash map #7

7. Hash Map — Finding Underperforming Listings

Background: Airbnb depends on optimizing the performance of property listings to enhance user experiences and maximize revenue. Identifying underperforming listings can significantly aid in improving the marketplace.
Problem statement: Given a list of listings where each listing is a dictionary containing id, views, and bookings, implement a function to find listings that are considered *underperforming*. A listing is *underperforming* if its ratio of bookings to views is below a given threshold (e.g., 0.1). Return the IDs of the underperforming listings in ascending order.
Function/class signature:
  • def find_underperforming_listings(listings: List[Dict[str, int]], threshold: float) -> List[int]:

Example 1:
Input: find_underperforming_listings([{ 'id': 1, 'views': 100, 'bookings': 5 }, { 'id': 2, 'views': 200, 'bookings': 1 }, { 'id': 3, 'views': 50, 'bookings': 8 }], 0.1)
Output: [2]
Explanation: Listing 2 has a bookings/views ratio of 0.005 which is below the threshold 0.1.
Example 2:
Input: find_underperforming_listings([{ 'id': 1, 'views': 300, 'bookings': 30 }, { 'id': 2, 'views': 150, 'bookings': 20 }], 0.1)
Output: []
Explanation: Both listings meet the threshold for performance.
Constraints:
  • 1 <= len(listings) <= 10^4

  • 0 <= views, bookings <= 10000

  • 0 < threshold <= 1
coding Medium hash map #8

8. Hash Map — Detect underperforming listings based on rating and booking counts

Background: Airbnb relies on accurate metrics to enhance user experiences and optimize listings' visibility. Identifying underperforming listings can help improve the offerings and marketing strategies.
Problem statement: You are tasked with determining the underperforming listings given a dataset of listings. Each listing has associated ratings and booking counts. A listing is considered underperforming if its average rating is less than 4.0 and it has fewer than 10 bookings. You must implement a function that evaluates this and returns a list of listing IDs that meet these criteria.
Function/class signature:
  • def detect_underperforming_listings(listings: List[Dict[str, Union[int, float]]]) -> List[int]:

Example 1:
Input: listings = [{'id': 1, 'rating': 3.5, 'bookings': 8}, {'id': 2, 'rating': 4.5, 'bookings': 15}, {'id': 3, 'rating': 3.9, 'bookings': 5}]
Output: [1, 3]
Explanation: Listing IDs 1 and 3 are underperforming based on their ratings and booking counts.
Example 2:
Input: listings = [{'id': 4, 'rating': 4.2, 'bookings': 12}, {'id': 5, 'rating': 3.9, 'bookings': 10}, {'id': 6, 'rating': 3.8, 'bookings': 9}]
Output: [5, 6]
Explanation: Listing IDs 5 and 6 do not reach the minimum criteria for ratings or bookings.
Constraints:
  • 1 <= Listings <= 1000

  • Each listing ID is a unique integer.

  • 0 <= bookings <= 1000

  • 0.0 <= rating <= 5.0
coding Medium graph #9

9. Graph — Identify and evaluate underperforming listings

Background: In Airbnb's marketplace, listings that fail to meet certain performance criteria can impact overall business health. Identifying and evaluating these listings are crucial for improving customer satisfaction and optimizing earnings for hosts.
Problem statement: Write a function evaluate_underperforming_listings that takes a list of listings in the form of a dictionary and evaluates them against predefined performance metrics. A listing is considered underperforming if it has a rating below 4.0 or has fewer than 5 bookings. The function should return a list of listing IDs that are underperforming.
Function/class signature:
  • def evaluate_underperforming_listings(listings: List[Dict[str, Union[int, float]]]) -> List[int]:


Example 1:
Input:
[
    {"id": 1, "rating": 4.5, "bookings": 10},
    {"id": 2, "rating": 3.8, "bookings": 2},
    {"id": 3, "rating": 4.0, "bookings": 0}
]

Output:
[2, 3]

Explanation: Listing 2 has a rating below 4.0 and Listing 3 has fewer than 5 bookings, hence both are underperforming.
Example 2:
Input:
[
    {"id": 1, "rating": 4.2, "bookings": 12},
    {"id": 2, "rating": 4.4, "bookings": 5},
    {"id": 3, "rating": 3.9, "bookings": 4}
]

Output:
[3]

Explanation: Only Listing 3 is underperforming based on the given metrics.
Constraints:
  • 1 <= len(listings) <= 1000

  • Each listing contains a unique id with a rating as a float and bookings as an integer.

  • 0 <= bookings <= 100

  • 0.0 <= rating <= 5.0
coding Hard sliding window #10

10. [OA] Sliding Window — Implement search function for Airbnb rentals based on dates

Users often look for homes to rent on specific datetime ranges, and it's essential to efficiently check if the rental is available for the requested dates.
Problem statement: Given a list of rental_id with their corresponding availability ranges in the form of pairs (start_date, end_date) and a queried date range, return a list of rental IDs that are available during the entire period of the query.
  • def search_available_rentals(rentals: List[Tuple[int, Tuple[int, int]]], query: Tuple[int, int]) -> List[int]: - Returns rental IDs that are available for the entire query date range.


Example 1:
Input: rentals = [(1, (1, 5)), (2, (2, 6)), (3, (5, 10))], query = (3, 4)
Output: [1, 3]
Explanation: Rentals 1 (1 to 5) and 3 (5 to 10) are available in the range of 3 to 4.
Example 2:
Input: rentals = [(1, (1, 5)), (2, (6, 10)), (3, (5, 10))], query = (2, 4)
Output: [1]
Explanation: Only Rental 1 is available during the queried dates.
Constraints:
  • 1 <= rentals.length <= 10^4

  • 1 <= rental_id <= 10^6

  • 1 <= start_date < end_date <= 10^6

  • 1 <= query[0] < query[1] <= 10^6
coding Hard graph #11

11. [OA] Graph Traversal — Implement a neighbor-finding feature for Airbnb properties

In a platform like Airbnb, it's crucial to find neighboring properties efficiently to help users browse similar options. This will enhance the user experience by showing related listings when a user views a particular property.
Problem statement: You need to implement a function that takes a list of properties represented as nodes in a graph and returns a list of all neighboring properties within a certain distance. Each node has a property_id and a list of neighbors (i.e., directly connected properties).
  • def find_neighbors(properties: List[Property], id: int, distance: int) -> List[int]: - Returns the list of property identifiers of neighboring properties within the specified distance.


Example 1:
Input: properties = [[1, [2, 3]], [2, [1, 4]], [3, [1]], [4, [2]]], id = 1, distance = 1
Output: [2, 3]
Explanation: Property 1 is directly connected to properties 2 and 3.
Example 2:
Input: properties = [[1, [2, 3]], [2, [1, 4]], [3, [1]], [4, [2]]], id = 1, distance = 2
Output: [2, 3, 4]
Explanation: Property 1 is connected to properties 2 and 3 directly, and property 2 connects to property 4.
Constraints:
  • 1 <= properties.length <= 1000

  • 1 <= property_id <= 10^6

  • 0 <= distance <= 50
system design Senior caching #12

12. [OA] LRU Cache — Implement caching for Airbnb property listings

Airbnb needs to optimize its API by implementing a caching mechanism for property listings to reduce database load and improve response time.
Problem statement: Implement an LRU (Least Recently Used) cache with a specified capacity. The cache should support get(key) and put(key, value) operations.
  • class LRUCache:

  • def __init__(self, capacity: int): - Initializes the LRUCache with the maximum capacity.

  • def get(self, key: int) -> int: - Returns the value of the key if the key exists in the cache, otherwise return -1.

  • def put(self, key: int, value: int): - Update the value of the key if it exists, otherwise add the key-value pair to the cache. When the cache reaches its capacity, it should invalidate the least recently used item before inserting a new item.


Example 1:
Input:
cache = LRUCache(2)
cache.put(1, 1)
cache.put(2, 2)
cache.get(1) // returns 1
cache.put(3, 3) // evicts key 2
cache.get(2) // returns -1 (not found)
Example 2:
Input:
cache.put(4, 4) // evicts key 1
cache.get(1) // returns -1 (not found)
cache.get(3) // returns 3
cache.get(4) // returns 4
Constraints:
  • 1 <= capacity <= 3000

  • 0 <= key <= 10^4

  • 0 <= value <= 10^4

Start practicing Airbnb questions

Sign up for free to access walkthroughs, AI-generated questions, and more.

Get Started Free