FastPrepNested Set Structural Equivalence
Problems/Nested Set Structural Equivalence

Nested Set Structural Equivalence

Pinterest logoPinterest● MediumFULLTIMEPHONE SCREENONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The source specifies recursive, order-insensitive equality for serialized nested sets. It omits the serialization grammar, atomic value type, duplicate behavior, empty-set behavior, and a portable function interface. The judged core task matches the visible report at about 90%.

You are given two valid strings, left and right, that encode nested mathematical sets. An encoded set follows this grammar:

set     := "{" [element ("," element)*] "}"
element := integer | set

An integer is a signed decimal integer. The encoding contains no whitespace. The empty set {} is valid.

Two encoded sets are equal when they contain the same distinct elements. The order of elements does not matter at any nesting level, and repeated equal elements at the same level collapse according to mathematical set semantics. Integer atoms compare by value, while nested sets compare recursively. An integer and a set are always different, so 1 is not equal to {1}.

Return true if left and right encode equal nested sets; otherwise, return false.

Function

nestedSetsEqual(left: String, right: String) → boolean

Examples

Example 1

left = "{1,{2,3},4}"right = "{{3,2},4,1}"return = true

Both top-level sets contain the integers 1 and 4 plus a nested set containing 2 and 3. Permuting either level does not change the set.

Example 2

left = "{1,{2,3}}"right = "{{1,2},3}"return = false

The nesting hierarchy differs. In left, 1 is a top-level atom and 3 is nested; in right, those roles are reversed.

Example 3

left = "{1,1,{},{{2},2}}"right = "{{},1,{2,{2}}}"return = true

The repeated top-level 1 collapses. Both sides then contain 1, the empty set, and a nested set whose elements are the atom 2 and the set {2}.

Constraints

  • 2 <= left.length, right.length <= 20000
  • Each input is a valid encoding generated by the stated grammar and contains no whitespace.
  • Every integer is in [-10^9, 10^9] and uses ordinary decimal notation.
  • The maximum nesting depth is at most 300.
  • Repeated recursively equal elements at one set level represent one mathematical set element.

More Pinterest problems

  • Gaussian Naive Bayes Classifier (Machine Learning OA)OA · Seen Nov 2026
  • Top K Pins with Insert and QueryPHONE SCREEN · Seen Nov 2026
  • Pins Violation Log QueriesPHONE SCREEN · Seen Nov 2026
All Pinterest interview questionsSee Pinterest hiring insights
Saved
class Solution {
    public boolean nestedSetsEqual(String left, String right) {
        // Write your code here.
    }
}
Checking account…