Skip to content
RED SAGSkills

Join Two Record Lists

Implement an in-memory SQL-style join of left and right on the field key, where mode is "inner" or "left".

Let the right fields be every field name, other than key, that appears in at least one right record, in order of first appearance. Every output row starts as a copy of the left record and then gets one entry per right field: if the left record already has a field with that name, the entry is stored as "right_" + name instead. The value comes from the matched right record, or is null if that right record (or the missing match) does not have the field.

For each left record in order, output one row per matching right record (right[key] === left[key]), in right-list order. In "left" mode a left record with no match still produces one row with all right fields null; in "inner" mode it produces nothing.

Example 1

Input: left = [{"id":1,"name":"Asha"},{"id":2,"name":"Ben"}], right = [{"id":1,"orderId":"o1"},{"id":1,"orderId":"o2"}], key = "id", mode = "inner"
Output: [{"id":1,"name":"Asha","orderId":"o1"},{"id":1,"name":"Asha","orderId":"o2"}]
Explanation: Customer 2 has no orders, so the inner join drops it.

Example 2

Input: left = [{"id":1,"name":"Asha"},{"id":2,"name":"Ben"}], right = [{"id":1,"orderId":"o1"}], key = "id", mode = "left"
Output: [{"id":1,"name":"Asha","orderId":"o1"},{"id":2,"name":"Ben","orderId":null}]
Explanation: In left mode customer 2 is kept with null order fields.

Constraints

  • 0 <= left.length, right.length <= 10^4
  • Key values are strings or numbers
  • Left records never contain a field that starts with right_
Hint 1

Group the right records by key in a Map first so each lookup is O(1).

Hint 2

Work out the list of right fields once, up front.

Good practice for: Backend Developer, Full Stack Developer, Data Engineer, Database Administrator, Data Scientist

Run checks your code on 3 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.