JavaScriptMediumCollections20 min

Count records by a property

Count objects by their string-valued property named key. Return [value,count] pairs ordered by the first occurrence of each value; treat property names literally, including __proto__. All input is valid JSON satisfying the constraints; do not mutate the meaning of values through type coercion. Interviewers use this problem to assess use a Map to avoid object prototype collisions and preserve insertion order.

Input

A JSON object {"items": [objects], "key": string}.

Output

Print one compact JSON value: an array of [string, integer] pairs.

Constraints

0 <= items length <= 10000; every item owns key with a string value of length <= 100; key length <= 100.

Example

Input

{"items":[{"team":"qa"},{"team":"dev"},{"team":"qa"}],"key":"team"}

Output

[["qa",2],["dev",1]]

Example 2 input

{"items":[{"x":""},{"x":""}],"key":"x"}

Output

[["",2]]

Boundary case: Do not use a plain object as an unguarded frequency table

Public test cases (2)

  • Input

    {"items":[{"team":"qa"},{"team":"dev"},{"team":"qa"}],"key":"team"}

    Expected output

    [["qa",2],["dev",1]]
  • Input

    {"items":[{"x":"10"},{"x":"2"},{"x":"10"}],"key":"x"}

    Expected output

    [["10",2],["2",1]]
Hints (2)
  1. Read the dynamic property with bracket notation
  2. Do not use a plain object as an unguarded frequency table

Target complexity: time O(n) · space O(g), with g distinct values

Your solution

Checking runner availability…

Reference solution

Sign in for solution
All JavaScript programs