Problem · Parsing

Merge JSON Array Fields

Learn this problem
MediumTesla logoTeslaFULLTIMEPHONE SCREEN

Problem statement

You are given two compact JSON objects, baseJson and incomingJson. Each object maps a unique lowercase key to an array of integers. Inputs contain no whitespace. Merge every incoming field into the base object using behavior:

  • "OVERWRITE": an incoming key replaces the complete existing array.
  • "APPEND": if the key exists, append the incoming array elements in order; otherwise insert the incoming array.

Fields that occur only in the base object remain unchanged. Return compact JSON with keys in lexicographic order and no whitespace. Preserve array element order and duplicates. The inputs are not modified.

Function

mergeJson(baseJson: String, incomingJson: String, behavior: String) → String

Examples

Example 1

baseJson = "{\"a\":[1,2],\"b\":[3]}"incomingJson = "{\"a\":[4],\"c\":[5]}"behavior = "APPEND"return = "{\"a\":[1,2,4],\"b\":[3],\"c\":[5]}"

The incoming value for a is appended, b is preserved, and c is inserted.

Example 2

baseJson = "{\"b\":[3],\"a\":[1,2]}"incomingJson = "{\"a\":[],\"d\":[7]}"behavior = "OVERWRITE"return = "{\"a\":[],\"b\":[3],\"d\":[7]}"

The empty incoming array replaces a, and output keys are sorted regardless of input order.

Constraints

  • Each object contains at most 10000 unique lowercase keys of length 1 to 30.
  • Each array contains at most 10000 integers in [-10^9, 10^9].
  • The total number of keys and array elements across both objects is at most 100000.
  • behavior is "OVERWRITE" or "APPEND".
  • Both input strings are valid compact JSON in the specified subset.

More Tesla problems

drafts saved locally
public String mergeJson(String baseJson, String incomingJson, String behavior) {
    // Write your code here.
}
baseJson"{\"a\":[1,2],\"b\":[3]}"
incomingJson"{\"a\":[4],\"c\":[5]}"
behavior"APPEND"
expected"{\"a\":[1,2,4],\"b\":[3],\"c\":[5]}"
checking account