FastPrepValidate a Nested Object Against a Schema
Problem · String

Validate a Nested Object Against a Schema

Learn this problem
HardConfluent logoConfluentFULLTIMEONSITE INTERVIEW

Problem statement

You are given two strings, schema and document, containing valid JSON objects from the restricted grammar below. Return true exactly when the complete document matches the schema.

  • Each schema leaf is the descriptor "string" or "number".
  • Each non-leaf schema value is another schema object.
  • Each document leaf is a JSON string or integer, and each non-leaf value is another object.

An object matches only when it has exactly the declared fields: every schema field is present, no undeclared document field is present, and each value recursively matches its descriptor or nested schema. Field order does not matter.

The JSON-string interface is only a language-neutral execution adapter for the nested object structures used in the interview. Inputs may contain JSON whitespace. Keys and string values use letters, digits, spaces, underscores, and hyphens, so escaped characters do not occur. Both inputs are syntactically valid and every object has unique keys. In this exercise, the source's number descriptor means a signed integer.

Function

validateNestedObjectSchema(schema: String, document: String) → boolean

Examples

Example 1

schema = "{\"name\":\"string\",\"location\":{\"x\":\"number\",\"y\":\"number\"}}"document = "{\"name\":\"bob\",\"location\":{\"x\":5,\"y\":6}}"return = true

Both root fields are present, and every nested value has the declared type.

Example 2

schema = "{\"name\":\"string\",\"location\":{\"x\":\"number\"}}"document = "{\"name\":\"bob\",\"location\":{\"x\":\"5\"}}"return = false

location.x is a string, but its schema descriptor is number.

Example 3

schema = "{\"user\":{\"id\":\"number\"}}"document = "{\"user\":{\"id\":7,\"name\":\"Lin\"}}"return = false

The nested name field is undeclared, and matching requires the exact recursive shape.

Constraints

  • 2 <= schema.length, document.length <= 20000.
  • The nesting depth of either object is at most 100.
  • Each object contains at most 10000 total fields.
  • Every document integer is between -10^9 and 10^9, inclusive.
  • Schema leaves are exactly "string" or "number"; document leaves are strings or integers.

More Confluent problems

drafts saved locally
public boolean validateNestedObjectSchema(String schema, String document) {
    // Write your code here.
}
schema"{\"name\":\"string\",\"location\":{\"x\":\"number\",\"y\":\"number\"}}"
document"{\"name\":\"bob\",\"location\":{\"x\":5,\"y\":6}}"
expectedtrue
checking account