You are given a string 'STR' representing JSON object. Return an array of strings denoting JSON objects with proper indentation.
Rules for proper indentation:1. Every inner brace should increase one indentation to the following lines.
2. Every close brace should decrease one indentation to the same line and the following lines.
3. Every ‘,’ will mean a separate line.
4. The indents can be increased with an additional 4 spaces or ‘/t’.
Example:
Let the input be: "{A:"B",C:{D:"E",F:{G:"H",I:"J"}}}"
Then we return the following array of strings:
{
A:"B",
C:
{
D:"E",
F:
{
G:"H",
I:"J"
}
}
}
Note that for every new brace we are putting an additional 4 spaces or \t.
Note:
1. [] and {} are only acceptable braces in this case.
The first line of input contains an integer ‘T’ denoting the number of test cases to run. Then the test cases follow.
The first line of each test case contains the string ‘STR’.
Output Format:
For each test case, return an array of strings containing the indented JSON file.
Output for each test case will be printed in a new line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= N <= 2*10^3
Where 'N' denotes the length of the string.
Time limit: 1 sec
2
["foo", {"bar":["baz",null,1.0,2]}]
[{"EmployeeID":1,"Name":"Abhishek","Designation":"SoftwareEngineer"}]
[
"foo",
{
"bar":
[
"baz",
null,
1.0,
2
]
}
]
[
{
"Employee ID":1,
"Name":"Abhishek",
"Designation":"SoftwareEngineer"
}
]
Test Case 1:
In the first test case,
We can see that we have 3 braces so we print when we encounter ‘[‘ we indent by leaving 4 spaces and then put “foo” in the string.
Then we indent 4 more spaces and put “bar”.
Finally, we indent 4 more spaces for the last opening brace and then print baz.
Since we have ‘,’ after ‘bazz’ we make a new line for null and the numbers.
Finally, we close the brackets taking care of the proper indentation.
In the second test case,
We have 2 braces only. After the first ‘[‘ we leave 4 spaces and put ‘{‘ in the string.
Then we put the string data taking care to change the line after every ‘,’ and de-indent for every closing brace.
1
{"EmployeeID":2,"Name":"Garima","Designation":"EmailMarketing Specialist"}
{
"Employee ID":2,
"Name":"Garima",
"Designation":"EmailMarketing Specialist"
}
Just find the braces and put appropriate spaces.
The key idea in solving this problem is to simply iterate through the given string and construct our array of strings. We need to take care of the following points:
Below is the detailed algorithm:
Do check your code for the following corner cases:
O(N ^ 2), where ‘N’ is the length of the string.
The time required for the construction of the array of strings will be in order of N ^ 2. Hence, the overall time complexity is O(N ^ 2).
O(N ^ 2), where ‘N’ is the length of the string.
In the worst case, we can have all braces, and that makes the space complexity will be O(N ^ 2).