Golang concise solution with explanation what to handle

  • 0

    This problem challenges us how well we can capture all corner cases, rather than algorithmic thinking.
    Anyway, it's good idea to have a function to output a missing range from given two integers. This can be commonly used for all indexes (Be careful that only lower and upper are inclusive, so we need to -1 and +1 for them, respectively) and helps to keep our brain clean:)

    So what we need to do is basically

    1. For the first element, get a missing range between `lower`.
    2. For the `i` th element, get a missing range between `i-1` th element.
    3. For the last element, get a missing range between `upper`.

    Also we need to handle cases

    1. There is no element => get missing range between lower and upper (inclusive)
    2. There is only one element => 0 th index works as both the first and last element
    func findMissingRanges(nums []int, lower int, upper int) []string {
    	nlen := len(nums)
    	var res []string
    	if nlen == 0 {
    		return []string{getMissingRange(lower-1, upper+1)}
    	} else if nlen == 1 {
    		appendIfNotEmpty(&res, getMissingRange(lower-1, nums[0]))
    		appendIfNotEmpty(&res, getMissingRange(nums[0], upper+1))
    		return res
    	for i := 0; i < nlen; i++ {
    		if i == 0 {
    			appendIfNotEmpty(&res, getMissingRange(lower-1, nums[i]))
    		appendIfNotEmpty(&res, getMissingRange(nums[i-1], nums[i]))
    		if i == nlen-1 {
    			appendIfNotEmpty(&res, getMissingRange(nums[i], upper+1))
    	return res
    func getMissingRange(a, b int) string {
    	if b-a <= 1 {
    		return ""
    	} else if b-a == 2 {
    		return strconv.Itoa(a + 1)
    	} else {
    		left, right := strconv.Itoa(a+1), strconv.Itoa(b-1)
    		return left + "->" + right
    func appendIfNotEmpty(list *[]string, s string) {
    	if s != "" {
    		*list = append(*list, s)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.