Problem Description
Given a value that can be a string, number, array, object, boolean, or null, return its valid JSON string representation. The output must not include any extra spaces, and for objects, the key order should follow the order returned by Object.keys(). You are not allowed to use the built-in JSON.stringify method.
Key Insights
- The solution must support all JSON primitives: strings, numbers, booleans, and null.
- Composite types such as arrays and objects require recursive traversal for proper serializing.
- For strings, wrap them in double quotes.
- For arrays, recursively process every element and join them with commas between square brackets.
- For objects, iterate keys in insertion order and combine key-value pairs (key must be a string in double quotes) with commas between curly braces.
- Use recursion carefully to handle nested structures without adding unnecessary spaces.
Space and Time Complexity
Time Complexity: O(n), where n is the total number of elements/characters in the JSON structure. Space Complexity: O(n) due to the recursion stack and the constructed output string.
Solution
We use a recursive approach that inspects the type of the value and processes it accordingly:
- If the value is null, output "null".
- If the value is a boolean or number, convert it directly to its string representation.
- For a string, ensure it is enclosed in double quotes.
- For an array, iterate over each element, serialize each recursively, join them with commas, and enclose in square brackets.
- For an object, iterate over its keys in insertion order (or using Object.keys in JS / LinkedHashMap in Java), serialize both key (wrapped in double quotes) and its corresponding value, join with commas, and enclose in curly braces. This approach leverages recursion to handle arbitrarily nested objects and arrays while ensuring there are no extra spaces in the final string.