LeetCode: Summary Ranges Solution

Straight forward checking

Approach

On each iteration, init start and end to be equal to the iterated element

Keep assigning end while next element is greater than the current by one unit

If start !== end then it's a sub range

Implementation

1var summaryRanges = function (nums) {
2 let start, end
3 let res = []
4
5 for (let i = 0; i < nums.length; i++) {
6 start = end = nums[i]
7
8 for (; nums[i + 1] === nums[i] + 1; i++) {
9 end = nums[i + 1]
10 }
11
12 res.push(start === end ? "" + start : start + "->" + end)
13 }
14
15 return res
16}

Comments

Loading comments...

Tags

leetcode

array

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Contains Duplicate II

Tricky

Previous Post

LeetCode: Majority Element

Boyer-Moore Voting Algorithm

HoningJS

Search Posts