Microsoft logo

Microsoft Interview Questions

48 practice questions for Microsoft technical interviews

Microsoft 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
12
Coding
1
System Design
coding Medium Verified Question #1

1. Design Rate Limiter


Category: Sliding window coding problem

Design Rate Limiter Design a rate limiter system that controls the number of requests allowed within a specified time window. The rate limiter is...

Input: String
Output: Computed result
Want to practise this one?
Create a free account to open the full question and practise Microsoft questions with AI.
Sign up free
coding Medium Verified Question #2

2. Object Oriented Design - Idempotent Receipt Sending


Category: Trie-based coding problem
Input: String
Output: Computed result
coding Medium Verified Question #3

3. Object Oriented Design - Notification Service


Category: Trie-based coding problem

Problem Statement Design a notification service that supports sending notifications through multiple channels (SMS, Email) and is architected to...

Input: Number(s)
Output: Computed result
coding Medium Verified Question #4

4. Shortest Substring with N Unique Characters


Category: String coding problem

Shortest Substring with N Unique Characters *This is a variation of the leetcode problem* Given a string s and an integer n, find the length of...

Input: String
Output: Computed result
coding Hard Verified Question #5

5. Rate Limiter


Category: Sliding window coding problem
Design a rate limiter that tracks API requests per client and enforces limits using a sliding time window. Your system must support: - hit(key,...
Input: Given input
Output:** Computed result
coding Hard Verified Question #6

6. Non-Adjacent Team Selection


Category: Tree coding problem

Question You are given n people labeled from 0 to n - 1. Some pairs of people know each other directly. These relationships are given as a...

Input: List
Output: Computed result
coding Medium Verified Question #7

7. Bounded Repeat Substring


Category: String coding problem
A sensor data stream is represented as a string of characters. A contiguous segment of the stream is considered valid if it contains no three...
Input: String
Output: Computed result
coding Medium Verified Question #8

8. OA [CodeSignal] Prime Jumps


Category: Algorithm coding problem

OA [CodeSignal] Prime Jumps A game is played with the following rules: - A player starts at cell 0 with a score of 0. - There is a row of n cells...

Input: Number(s)
Output: Computed result
coding Hard Verified Question #9

9. Combine N-ary Trees


Category: Tree coding problem
You are given the roots of two N-ary organization charts, each representing a hierarchical department structure. Every node has an integer...
Input: List
Output: Computed result
coding Medium Verified Question #10

10. Digit Replacement Maximizer


Category: String coding problem
A numeric optimization system performs exactly k substitution operations on a number string s. In each operation, choose any digit in s that is...
Input: String
Output: Computed result
coding Medium Verified Question #11

11. Best Window For Target Count


Category: Trie-based coding problem
A log analysis tool searches for the most frequent occurrence of a specific error code within a fixed-size window of log entries. Given an integer...
Input: Array
Output: Integer
coding Medium Verified Question #12

12. Evens Before Odds


Category: Array coding problem
You are given an integer array nums. Rearrange nums so that all even numbers appear before all odd numbers. The relative order of even or odd...
Input: Array
Output: Integer
system design Hard Verified Question #13

13. Top 5 System Design Questions Jan 2026


Category: Interval-based system design problem

Top 5 Recently Asked System Design Questions - Microsoft These are the commonly asked system design questions from Microsoft interviews and some...

Input: List
Output: Computed result
coding Hard caching #1

1. [AI Enabled Coding] Azure Blob Range Cache Policy Simulator


Scenario
An Azure Blob Storage read gateway caches fetched blob ranges to reduce repeated backend reads. Build a deterministic trace simulator that gateway engineers can use to investigate expiration, cache misses, and competition between tenants on a memory-constrained worker. You may use an AI assistant while implementing the simulator, but you must explain its data structures and verify its behavior; these simplified policies are exercise requirements, not claims about Azure's production implementation.
Part 1 — Worker-wide TTL and LRU policies
  • Start with an empty cache. Each input record is a map with string keys and string values. Every record contains id, op, time, tenant, and key. A put also contains value and sizeMiB. Times are integer seconds, and sizes are positive integer MiB encoded as strings. value is an opaque payload token; its string length does not determine its declared size.

  • Cache identity is the pair (tenant, key). The worker has a 10 MiB capacity and a 5-second TTL. A successful put at time t expires at t + 5; an entry is unavailable when time >= expiresAt.

  • Before every operation, remove all expired entries. When multiple live entries expire together, report them in ascending (expiresAt, tenant, key) order; tenant and key comparisons are lexicographic.

  • A get returns HIT with the stored value or MISS. A hit makes the entry most recently used but does not extend its TTL. A miss does not change recency.

  • A put whose size exceeds 10 MiB is REJECTED by GLOBAL_ITEM_LIMIT. Rejection preserves any existing value and its recency, although expiration still happens first.

  • For any other put, remove the previous version of that identity, if present. Evict least-recently-used entries until the new entry fits, then insert it as most recently used and return STORED. Replacement itself is not an eviction. Operations execute in input order, including operations with equal timestamps.

  • Choose your own return type. The examples use a list of results, containing id and status, plus value only for a hit.


simulate_cache(records: list[dict[str, str]], policies: list[dict[str, str]] | None = None)
Omitting policies, or passing None, selects Part 1.
Example 1:
Input:
{
  "records": [
    {"id":"1","op":"put","time":"0","tenant":"A","key":"x","value":"range-x","sizeMiB":"6"},
    {"id":"2","op":"put","time":"1","tenant":"B","key":"y","value":"range-y","sizeMiB":"4"},
    {"id":"3","op":"get","time":"2","tenant":"A","key":"x"},
    {"id":"4","op":"put","time":"3","tenant":"B","key":"z","value":"range-z","sizeMiB":"4"},
    {"id":"5","op":"get","time":"5","tenant":"A","key":"x"},
    {"id":"6","op":"get","time":"6","tenant":"B","key":"z"}
  ]
}

Output:
[
  {"id":"1","status":"STORED"},
  {"id":"2","status":"STORED"},
  {"id":"3","status":"HIT","value":"range-x"},
  {"id":"4","status":"STORED"},
  {"id":"5","status":"MISS"},
  {"id":"6","status":"HIT","value":"range-z"}
]

Explanation: The first two entries consume 6 + 4 = 10 MiB. Reading A/x makes B/y least recently used. Inserting B/z would consume 14 MiB, so evicting B/y restores usage to 10 MiB. A/x expires exactly at time 5; its earlier hit did not refresh its TTL. B/z expires at time 8 and remains a hit at time 6.
Part 2 — Tenant budgets and explainable decisions
Other Azure teams need tenant-isolation policies and diagnostics explaining why cached ranges disappeared. Extend Part 1 rather than replacing it, and make the policy mechanism flexible enough to support future scoped capacity policies, such as a budget shared by a configured group of tenants. Discuss how your return type changes before implementing this extension.
  • Passing any policies list, including [], enables Part 2. Each policy is a string-valued map containing tenant and maxMiB; it overrides that tenant's default 6 MiB capacity. Tenant names are unique within this list, and capacities are positive integers. The 10 MiB worker capacity and every Part 1 TTL and recency rule still apply.

  • Validate an incoming item's size against both the worker capacity and its tenant capacity before replacing or evicting anything. Report every violated item rule, ordered GLOBAL_ITEM_LIMIT, then TENANT_ITEM_LIMIT. If any rule fails, reject the write. Expiration still happens first.

  • For an accepted write, remove its previous version, then enforce the tenant capacity by evicting that tenant's least-recently-used entries. Next enforce the worker capacity by evicting globally least-recently-used entries. Finally insert the new item. Tenant recency and global recency are updated by the same successful hits and writes.

  • Each result now also contains expired, evicted, and violations, even when those arrays are empty. An expired identity is {"tenant":"A","key":"x"}. Each eviction contains its identity and reason, either TENANT_CAPACITY or GLOBAL_CAPACITY, in actual eviction order. Do not include replacements or expirations in evicted.

  • The example return type is an envelope containing results and final usage. Usage is measured immediately after the last operation, without advancing time, and contains totalMiB and tenantMiB; omit tenants with zero usage.


Example 2:
Input:
{
  "policies": [
    {"tenant":"A","maxMiB":"6"},
    {"tenant":"B","maxMiB":"8"}
  ],
  "records": [
    {"id":"1","op":"put","time":"0","tenant":"A","key":"x","value":"ax","sizeMiB":"4"},
    {"id":"2","op":"put","time":"1","tenant":"A","key":"y","value":"ay","sizeMiB":"3"},
    {"id":"3","op":"put","time":"2","tenant":"B","key":"z","value":"bz","sizeMiB":"6"},
    {"id":"4","op":"put","time":"3","tenant":"C","key":"w","value":"cw","sizeMiB":"4"},
    {"id":"5","op":"get","time":"4","tenant":"B","key":"z"}
  ]
}

Output:
{
  "results": [
    {"id":"1","status":"STORED","expired":[],"evicted":[],"violations":[]},
    {"id":"2","status":"STORED","expired":[],"evicted":[{"tenant":"A","key":"x","reason":"TENANT_CAPACITY"}],"violations":[]},
    {"id":"3","status":"STORED","expired":[],"evicted":[],"violations":[]},
    {"id":"4","status":"STORED","expired":[],"evicted":[{"tenant":"A","key":"y","reason":"GLOBAL_CAPACITY"}],"violations":[]},
    {"id":"5","status":"HIT","value":"bz","expired":[],"evicted":[],"violations":[]}
  ],
  "usage": {"totalMiB":10,"tenantMiB":{"B":6,"C":4}}
}

Explanation: Inserting A/y would give tenant A 4 + 3 = 7 > 6 MiB, so A/x is evicted, leaving 3 MiB. Adding B/z gives 3 + 6 = 9 MiB globally and stays within B's 8 MiB cap. Adding C/w is within C's default 6 MiB cap, but global usage would be 9 + 4 = 13 > 10; evicting the globally oldest entry A/y removes 3 MiB. Final usage is 6 + 4 = 10 MiB, and no entry has expired by time 4.
Example 3:
Input:
{
  "policies": [],
  "records": [
    {"id":"1","op":"put","time":"0","tenant":"A","key":"x","value":"original","sizeMiB":"4"},
    {"id":"2","op":"put","time":"1","tenant":"B","key":"y","value":"by","sizeMiB":"6"},
    {"id":"3","op":"put","time":"2","tenant":"A","key":"x","value":"oversized","sizeMiB":"11"},
    {"id":"4","op":"get","time":"3","tenant":"A","key":"x"},
    {"id":"5","op":"put","time":"5","tenant":"A","key":"z","value":"az","sizeMiB":"6"}
  ]
}

Output:
{
  "results": [
    {"id":"1","status":"STORED","expired":[],"evicted":[],"violations":[]},
    {"id":"2","status":"STORED","expired":[],"evicted":[],"violations":[]},
    {"id":"3","status":"REJECTED","expired":[],"evicted":[],"violations":["GLOBAL_ITEM_LIMIT","TENANT_ITEM_LIMIT"]},
    {"id":"4","status":"HIT","value":"original","expired":[],"evicted":[],"violations":[]},
    {"id":"5","status":"STORED","expired":[{"tenant":"A","key":"x"}],"evicted":[{"tenant":"B","key":"y","reason":"GLOBAL_CAPACITY"}],"violations":[]}
  ],
  "usage": {"totalMiB":6,"tenantMiB":{"A":6}}
}

Explanation: Initial usage is 4 + 6 = 10 MiB. The attempted replacement has size 11, violating both 11 > 10 and 11 > 6, so the original value survives. At time 5, A/x expires despite its time-3 hit, reducing usage to 6 MiB. B/y does not expire until time 6. Adding A/z would consume 6 + 6 = 12 > 10, so B/y is globally evicted, leaving 6 MiB.
Notes:
  • There are at most 200,000 operations and 200,000 policy records. Times are nondecreasing integers from 0 through 10^12; declared sizes and policy capacities are integers from 1 through 10^9. Other fields are nonempty strings, and operation IDs are unique.

  • Inputs are well formed, the simulator is single-threaded, and all policies are fixed for one invocation. Do not scan all cached entries on every operation; use indexed recency and expiration structures.

  • Treat the stated capacities and TTL as named configuration constants so the same design scales to larger workers without changing its algorithm.
Want to practise this one?
Create a free account to open the full question and practise Microsoft questions with AI.
Sign up free
coding Medium linked list #2

2. Reverse a Linked List — Manipulating Linked List Pointers

This problem is common in manipulating linked lists, which are used in many Microsoft applications, including data structures in Azure services.
Problem statement: Given the head of a singly linked list, return the head of the list after reversing it. You need to reverse the list in-place, which means you should not use extra space for another list.
Function/class signature:
  • def reverse_linked_list(head: Optional[ListNode]) -> Optional[ListNode]:


Example 1:
  • Input: head = [1, 2, 3, 4, 5]

  • Output: [5, 4, 3, 2, 1]

  • Explanation: After reversing, the last element becomes the head.


Example 2:
  • Input: head = [1]

  • Output: [1]

  • Explanation: A single node remains unchanged when reversed.


Constraints:
  • The number of nodes in the list is in the range [0, 5000].

  • -5000 <= Node.val <= 5000.

  • The input list is guaranteed to have at least one node.


coding Medium linked list #3

3. Reverse a Linked List — Implement a function to reverse a singly linked list

Background: Reversing a linked list is a common operation in various data structures and can be essential in memory management of linked data. For Microsoft products that utilize linked lists for managing dynamic data, efficient reversing can significantly improve performance in data traversal tasks.
Problem statement: You are given a singly linked list with the head node head. Your task is to reverse the linked list and return the new head node. Ensure that the function can handle edge cases such as an empty list or a single node list.
Function/class signature:
  • def reverse_linked_list(head: Optional[Node]) -> Optional[Node]:

Example 1:
Input: head = 1 -> 2 -> 3 -> None
Output: 3 -> 2 -> 1 -> None
Explanation: The linked list is reversed from 1 -> 2 -> 3 to 3 -> 2 -> 1.
Example 2:
Input: head = None
Output: None
Explanation: The input is an empty list, so the output is also None.
Constraints:
  • The number of nodes in the list is in the range [0, 5000].

  • The values of the nodes are integers between -1000 and 1000.

  • The nodes of the linked list are unique.
coding Medium linked list #4

4. Coding — Reversing a Linked List

Background: Microsoft often works with complex data structures in its software, and understanding linked lists is crucial for optimizing performance in these systems. This exercise simulates data manipulation relevant in environments like Azure or Microsoft 365.
Problem statement: Given a singly linked list, reverse the list and return the new head of the reversed linked list. You need to ensure your solution runs in O(n) time and O(1) space complexity.
Function/class signature:
  • def reverse_linked_list(head: Optional[ListNode]) -> Optional[ListNode]:

Example 1:
Input: 1 -> 2 -> 3 -> 4 -> 5 -> None
Output: 5 -> 4 -> 3 -> 2 -> 1 -> None
Explanation: The linked list is reversed from its original order.
Example 2:
Input: 1 -> None
Output: 1 -> None
Constraints:
  • The list may be empty (head will be None).

  • The number of nodes in the list is within the range [0, 5000].
coding Medium linked list #5

5. Reversing a Linked List — in-place reversal of a linked structure

Background: Reversing a linked list is a common operation used in various algorithms and data processing tasks. Microsoft may require this for its applications dealing with data structures, especially in scenarios involving programming languages like C# where linked lists are prevalent in data representation.
Problem statement: Given a singly linked list, you need to reverse the linked list so that the head points to the last node and each node points to the previous node instead of the next node. The reversal should be done in-place without using extra space for another data structure.
Function/class signature:
  • def reverse_linked_list(head: ListNode) -> ListNode:

Example 1:
  • Input: head = [1, 2, 3, 4, 5]

  • Output: [5, 4, 3, 2, 1]

  • Explanation: The linked list gets reversed so 1 becomes 5, 2 becomes 4, and so on.

Example 2:
  • Input: head = [1]

  • Output: [1]

  • Explanation: A single element list remains unchanged.

Constraints:
  • The head of the list will have at least one node.

  • Node values can be any integer.

  • The maximum number of nodes does not exceed 10^4.
coding Medium caching #6

6. Implementing an LRU Cache — a pattern for caching responses or data

Background: Microsoft often handles large volumes of data where quick access to previously used data is critical for performance. An efficient caching mechanism like an LRU (Least Recently Used) Cache is necessary to optimize memory usage and speed up data retrieval in applications such as Azure services.
Problem statement: Design and implement an LRU Cache that supports the following operations: get(key) and put(key, value). The get method retrieves the value of the key if it exists in the cache. Otherwise, it returns -1. The put method will insert or update the value for a key. If the cache exceeds its capacity, it should invalidate the least recently used item before inserting a new item into the cache.
  • Function/class signature:

- def __init__(self, capacity: int): # Initializes the LRU cache with positive size capacity.
- def get(self, key: int) -> int: # Returns the value of the key if it exists in the cache, otherwise returns -1.
- def put(self, key: int, value: int) -> None: # Updates or inserts the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item.
Example 1:
  • Input: cache = LRUCache(2); cache.put(1, 1); cache.put(2, 2); cache.get(1)

  • Output: 1

  • Explanation: 1 was accessed and is now the most recently used.

Example 2:
  • Input: cache.put(3, 3)

  • Output: -1

  • Explanation: cache exceeds capacity. 2 is evicted.

Constraints:
  • The cache will have a capacity of at least 1 and at most 3000.

  • The keys and values will be integers ranging from 0 to 10^4.
coding Medium caching #7

7. Data Structures and Algorithms — Implement an LRU Cache

Background: Microsoft products often require efficient data retrieval and caching systems, particularly for performance optimization in applications like Azure and Windows services. Implementing an LRU cache allows for fast access to frequently used data while managing memory efficiently.
Problem statement: Design and implement a data structure that supports the following operations: get(key) and put(key, value). The get method retrieves the value of the key if it exists in the cache, otherwise returns -1. The put method updates or adds the value of the key in the cache. When the cache reaches its capacity, it should invalidate the least recently used entry before inserting a new item.
Function/class signature:
  • def __init__(self, capacity: int): # initialize LRUCache with positive size capacity

  • def get(self, key: int) -> int: # return the value of the key, or -1 if the key does not exist

  • def put(self, key: int, value: int) -> None: # update the value of the key or insert the key if it is not already present

Example 1:
Input: lru_cache = LRUCache(2)
lru_cache.put(1, 1)
lru_cache.put(2, 2)
print(lru_cache.get(1))
Output: 1
Explanation: Key 1 was found, returned 1.
Example 2:
Input: lru_cache.put(3, 3)
Output: None (cache evicts key 2)
Constraints:
  • 1 <= capacity <= 3000

  • 0 <= key <= 10^4

  • 0 <= value <= 10^8
coding Medium dynamic programming #8

8. Counting Palindromic Substrings — Count subsets of strings that are palindromes

Background: In applications like Microsoft Word or Microsoft Teams, analyzing text for formatting or categorizing can often benefit from identifying palindromic substrings to enhance features like spell-checkers or text analyzers.
Problem statement: Given a string s, you need to return the number of palindromic substrings in s. A palindrome is a string that reads the same backward as forward.
Function/class signature:
  • def count_palindromic_substrings(s: str) -> int:


Example 1: Input: "aaa", Output: 6, Explanation: Substrings are "a", "a", "a", "aa", "aa", "aaa".
Example 2: Input: "abc", Output: 3, Explanation: Substrings are "a", "b", "c".
Constraints:
  • 1 <= len(s) <= 1000

  • s consists of lowercase English letters.

coding Hard dynamic programming #9

9. [OA] Dynamic Programming — maximum subarray sum for data throughput optimization

In services like Azure Data Lake, it is important to find the maximum throughput of data streams over given segments. This requires identifying the largest sum of neighboring data packets for optimization.
Problem statement: Given an integer array nums, implement a function maxSubArray(nums: List[int]) -> int that returns the largest sum of contiguous elements in the array.
  • Method Signature: def maxSubArray(nums: List[int]) -> int: Returns the maximum sum of a contiguous subarray.


Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The contiguous subarray [4,-1,2,1] has the largest sum 6.
Example 2:
Input: nums = [1]
Output: 1
Constraints:
  • 1 <= nums.length <= 10^5

  • -10^4 <= nums[i] <= 10^4
coding Hard graph #10

10. [OA] Dijkstra's Algorithm — finding the shortest path in the Azure Network

Microsoft Azure needs to optimize routing between data centers. The goal is to find the shortest path between nodes in the network to enhance performance and reduce latency.
Problem statement: Given a directed graph represented as an adjacency list, implement a function dijkstra(graph: Dict[int, List[Tuple[int, int]]], start: int) -> Dict[int, int] that calculates the shortest path from a starting node to all other nodes.
  • Method Signature: def dijkstra(graph: Dict[int, List[Tuple[int, int]]], start: int) -> Dict[int, int]: Returns a dictionary where keys are node indices and values are the shortest distances from the start.


Example 1:
Input: graph = {0: [(1, 4), (2, 1)], 1: [(3, 1)], 2: [(1, 2), (3, 5)], 3: []}, start = 0
Output: {0: 0, 1: 3, 2: 1, 3: 4}
Explanation: The shortest path from node 0 to node 3 is through 2 and then to 1.
Example 2:
Input: graph = {0: [(1, 2)], 1: [(2, 3)], 2: [(3, 1)], 3: []}, start = 0
Output: {0: 0, 1: 2, 2: 5, 3: 6}
Constraints:
  • 1 <= len(graph) <= 10^4

  • 0 <= graph[i][j][0] < len(graph)

  • 0 < graph[i][j][1] <= 10^3
system design Hard caching #11

11. Design BlobMetadataCache — a byte-bounded LRU cache with per-entry expiration


Background
Azure Storage services repeatedly read blob metadata such as access tiers and serialized property documents. Implement an in-process cache whose keys include the blob version, whose memory budget is measured in UTF-8 payload bytes, and whose TTL prevents metadata from remaining cached indefinitely. This exercise adapts a candidate-reported Microsoft Azure Storage interview question about an LRU cache with TTL; the byte-budget rules are an extension for this exercise.
Requirements
1. Construct the cache with a nonnegative capacity_bytes. Keys are opaque, case-sensitive strings such as account/container/blob@version; values are strings. An entry costs exactly len(value.encode("utf-8")) bytes. Ignore key and bookkeeping memory when enforcing capacity.
2. Every public operation receives now_ms. Calls use globally nondecreasing timestamps. An entry written with TTL ttl_ms expires at now_ms + ttl_ms and is unavailable when now_ms >= expires_at. Logically remove all expired entries before executing each operation, including a rejected write.
3. put inserts or replaces an entry and makes it most recently used. If the new payload alone exceeds capacity, return false without changing any unexpired entry or its recency. Otherwise, remove the previous version of that key, evict least-recently-used entries until the new value fits, insert it with a fresh TTL, and return true.
4. A successful get makes the entry most recently used but does not extend its TTL. A missing or expired key returns null. Expiration events from an earlier write must never remove a later replacement of the same key.
5. invalidate removes a live entry and reports whether it existed. stats reports the number of live entries and their total payload bytes. Neither operation changes the recency of remaining entries.
6. Avoid scanning the whole cache on each operation. Use an object-oriented implementation with efficient recency tracking, lookup, and expiration processing. Calls are sequential; thread safety is not required.
Class API
  • BlobMetadataCache(capacity_bytes: int) — construct an empty cache.

  • put(key: str, value: str, ttl_ms: int, now_ms: int) -> bool — insert or replace a payload, possibly evicting LRU entries.

  • get(key: str, now_ms: int) -> str | None — return a live payload and update its recency.

  • invalidate(key: str, now_ms: int) -> bool — remove a live entry if present.

  • stats(now_ms: int) -> dict[str, int] — return exactly {"entries": count, "bytes": payload_bytes}.


Example 1:
Input sequence:
cache = BlobMetadataCache(10)
cache.put("acct/logs/a@v1", "Hot", 10, 0)
cache.put("acct/logs/b@v1", "Cool", 20, 0)
cache.get("acct/logs/a@v1", 1)
cache.put("acct/logs/c@v1", "Cool", 20, 1)
cache.get("acct/logs/b@v1", 1)
cache.stats(1)
cache.get("acct/logs/a@v1", 10)
cache.stats(10)

Output, excluding construction:
[true, true, "Hot", true, null, {"entries": 2, "bytes": 7}, null, {"entries": 1, "bytes": 4}]

Explanation: Hot costs 3 bytes and Cool costs 4. Reading a makes b least recently used. Inserting c would require 11 bytes, so b is evicted, leaving 7 bytes. At time 10, a expires exactly at its deadline; only c remains.
Example 2:
Input sequence:
cache = BlobMetadataCache(5)
cache.put("acct/docs/a@v1", "é", 3, 0)
cache.put("acct/docs/a@v1", "123456", 100, 1)
cache.get("acct/docs/a@v1", 1)
cache.put("acct/docs/b@v1", "XYZ", 10, 1)
cache.stats(1)
cache.put("acct/docs/a@v1", "Q", 20, 2)
cache.get("acct/docs/a@v1", 3)
cache.invalidate("acct/docs/b@v1", 3)
cache.stats(3)
cache.get("acct/docs/a@v1", 22)

Output, excluding construction:
[true, false, "é", true, {"entries": 2, "bytes": 5}, true, "Q", true, {"entries": 1, "bytes": 1}, null]

Explanation: é occupies 2 UTF-8 bytes. The 6-byte replacement is rejected, preserving the original value. Adding XYZ fills the 5-byte budget. Replacing é with Q reduces usage to 4 bytes and sets a new deadline of 22. The original deadline of 3 must not delete this replacement. Invalidating b leaves 1 byte, and a expires at time 22.
Constraints
  • 0 <= capacity_bytes <= 100,000,000; at most 100,000 public method calls per instance.

  • Keys are nonempty strings of at most 512 characters. Values are valid UTF-8-encodable strings with encoded lengths from 0 to 1,000,000 bytes; empty values are allowed.

  • 1 <= ttl_ms <= 10^12 and 0 <= now_ms <= 10^15. Method arguments satisfy these bounds, and timestamps never decrease.

  • Use only in-memory data structures and the standard library. No background timer, storage service, or network access is required.
system design Hard messaging #12

12. [OA] Basic Twitter Feed — design a simplified version of Twitter for Azure

Considering the real-time capabilities of Azure, create a basic Twitter API that can fetch user feeds. This design must include necessary features for users to follow others and retrieve their latest tweets in real-time.
Problem statement: Design a Twitter class that supports the following methods:
  • postTweet(userId: int, tweetId: int) -> None: Record a new tweet.

  • getNewsFeed(userId: int) -> List[int]: Retrieve the 10 most recent tweet IDs in the user's news feed.

  • follow(followerId: int, followeeId: int) -> None: Allow a follower to follow a followee.

  • unfollow(followerId: int, followeeId: int) -> None: Allow a follower to unfollow a followee.


Method Signatures:
- def postTweet(self, userId: int, tweetId: int) -> None
- def getNewsFeed(self, userId: int) -> List[int]
- def follow(self, followerId: int, followeeId: int) -> None
- def unfollow(self, followerId: int, followeeId: int) -> None
Example 1:
Input: twitter = Twitter()
twitter.postTweet(1, 5)
twitter.getNewsFeed(1)
Output: [5]
Example 2:
Input: twitter.follow(1, 2)
twitter.postTweet(2, 6)
twitter.getNewsFeed(1)
Output: [6, 5]
Constraints:
  • 0 <= userId, followerId, followeeId, tweetId <= 10^4

  • The number of tweets will not exceed 10^4. At most 3 * 10^4 follow operations will occur.
system design Hard caching #13

13. [OA] LRU Cache — implement caching layer for Azure API responses

Microsoft Azure commonly uses caching to speed up responses to repeated API requests. Implement an LRU (Least Recently Used) Cache to maintain efficient access and updates.
Problem statement: Design and implement an LRUCache class that supports get(key: int) -> int and put(key: int, value: int) -> None methods. The cache will have a limited capacity.
  • Method Signatures:

- def get(self, key: int) -> int: Returns the value of the key if present, otherwise -1.
- def put(self, key: int, value: int) -> None: Updates the value of the key or adds it if it's not already present. When the cache reaches its capacity, it invalidates 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)
Output: 1
Example 2:
Input: cache.put(2, 1)
cache.put(2, 2)
cache.get(2)
Output: 2
Constraints:
  • capacity will be between 1 and 3000.

  • key and value are integers within the range of a 32-bit signed integer.

Start practicing Microsoft questions

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

Get Started Free