Problem Description: Write function summaryRanges(nums) that given a sorted array of numbers, returns the summary of its ranges.
For example:
summaryRanges([1,2,3,4]) === ['1->4']
summaryRanges([0, 1, 2, 5, 6, 9]) === ["0->2", "5->6", "9"]
summaryRanges([0, 1, 2, 3, 3, 3, 4, 5, 6, 7]) === ["0->7"]
summaryRanges([0, 1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 7, 9, 9, 10]) === ["0->7","9->10"]
summaryRanges([-2,0, 1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 7, 9, 9, 10, 12]) ===["-2", "0->7", "9->10", "12"]
summaryRanges([1,1,1,1,1]) === ['1']
Level: 6kyu
Link to Kata: Summarize Ranges
This was a very interesting Kata. We are given with a sorted array of numbers and we ave to find the range of numbers which are present in the array. We initialize an "ans" array and start going through every element of the array using a while loop. If the difference of element on the index is 1 or 0 we push the element to another "inst" array which we initialized in the starting of the loop. If we do not find such an element then we push the "inst" array to "ans" array and re-initialize the "inst" array to an empty array.
After we are done with the above step we start to go through every sub-array of the answer array and check if all the elements of sub-array are equal or not using a function. If it is then we put the single element in the "answer" which we initialized in the starting. If its not equal then we push a string which contains first element of sub-array followed by a "->" and then the last element of sub-array so as to define the range of that sub-array.
Finally we output the "answer" in order to output the required ranges.
This was a fairly complex Kata so go through the code and explanation simultaneously and please mention if you can come up with a better approach.
Here is a link to the code: Kata Day 17
Please mention your suggestions or your doubts in the comment below.
Happy coding. :)
No comments:
Post a Comment