Skip to the code
cf.
+50 XP

#712 Fewest Moves for a Keyed List

hard

A list of rows is rendered with a unique key per row. After an update, the framework must remove rows whose keys are gone, insert rows with new keys, and move some of the kept rows so the order matches. Moving DOM nodes is slow, so it moves as few as possible: the kept rows that are already in the right relative order stay put.

Write keyedListOps(oldKeys, newKeys) that returns [removed, inserted, moved]: how many old keys are not in newKeys, how many new keys were not in oldKeys, and the smallest number of kept rows that must move so the kept rows appear in newKeys order.

Example 1

Input: oldKeys = ["a","b","c","d"], newKeys = ["d","a","b","c"]
Output: [0,0,1]

Only d has to move to the front; a, b, c keep their relative order.

Example 2

Input: oldKeys = ["a","b","c"], newKeys = ["c","x","b","a"]
Output: [0,1,2]

x is inserted. Of c, b, a, only one can stay; the other two move.

Constraints

  • 0 <= oldKeys.length, newKeys.length <= 10^5
  • Keys are strings, unique within each list.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).