Type Coercion Comparator

Difficulty: Medium · Topics: Edge Cases, Comparison, Type System

Difficulty: Medium  |  Tags: Edge Cases, Comparison, Type System

Description

Implement a comparator that can meaningfully compare values of different types. This is useful when comparing JSON values where numbers might come as strings, booleans as "true"/"false" strings, etc.

Implement:

flexibleEquals(value1, value2) → boolean
flexibleCompare(value1, value2) → int  // -1, 0, 1

Coercion rules (in priority order):

  • If same type → compare directly.
  • If one is String, other is Number → try parsing string as number.
  • If one is String, other is Boolean → "true"/"false" comparison (case-insensitive).
  • If both are numeric types (int, long, float, double) → compare as double.
  • null equals null, but null ≠ anything else.
  • Examples

    Example 1:

    Input:  flexibleEquals(42, "42")
    Output: true
    

    Example 2:

    Input:  flexibleEquals(true, "TRUE")
    Output: true
    

    Example 3:

    Input:  flexibleEquals(1.0, 1)
    Output: true
    

    Example 4:

    Input:  flexibleEquals(null, "null")
    Output: false
    Explanation: null only equals null, not the string "null".
    

    Example 5:

    Input:  flexibleCompare("10", 9)
    Output: 1  (10 > 9)
    

    Example 6:

    Input:  flexibleEquals("abc", 123)
    Output: false
    Explanation: String "abc" can't be parsed as number → not equal.
    

    Constraints

    ---

    ## Concurrency

    Practice this problem

    Related problems