Problem · Array

K Most Recent Unique Request IDs

Learn this problem
EasyMicrosoft logoMicrosoftINTERNOA
See Microsoft hiring insights

Problem statement

You are given an array of request IDs, requests, and an integer k. The end of requests represents the most recent request.

A request ID may appear more than once. Scan requests from right to left and collect each distinct request ID the first time you encounter it. Stop after collecting k distinct IDs.

Return the collected request IDs in order from most recent to least recent.

Function

getMostRecentUniqueRequests(requests: String[], k: int) → String[]

Examples

Example 1

requests = ["item1","item2","item3","item1","item3"]k = 3return = ["item3","item1","item2"]

Scanning from right to left first collects "item3" and then "item1". The next "item3" is skipped because it has already been collected. Collecting "item2" produces the required three distinct IDs.

Constraints

  • 1 <= k <= requests.length <= 10^5
  • requests contains at least k distinct request IDs.
  • Every requests[i] consists only of lowercase English letters and digits.

More Microsoft problems

drafts saved locally
public String[] getMostRecentUniqueRequests(String[] requests, int k) {
  // Write your code here.
}
requests["item1","item2","item3","item1","item3"]
k3
expected["item3", "item1", "item2"]
checking account