Codiwan.com

The blog for Design Patterns, Linux, HA and Myself!

Remove Duplicates from Sorted Array ii Solution - Leetcode

Understand Remove Duplicates from sorted array ii (80 Leetcode) with Solution

This document presents the solution to the problem 80. Remove Duplicates from Sorted Array II - Leetcode.

Known Information

Requirements

Solution

  1. current - current element in the loop
  2. currentCount - the number of times the current element is found consecutively
  3. duplicateStartIndex & duplicateEndIndex - continuous range inside the array that holds the duplicate element

The solution involes:

Initial State

1st Iteration:

2nd Iteration:

3rd Iteration:

4th Iteration:

5th Iteration:

6th Iteration:

7th Iteration:

8th Iteration:

11th Iteration

Exit Conditions

Please do provide some comments if you find the explanation a bit lacking.

func removeDuplicates(nums []int) int {
	current := -1
	currentCount := 0
	duplicateStartIndex := -1
	duplicateEndIndex := -1

	for idx, num := range nums {
		if num != current {
			current = num
			currentCount = 1
		} else if num == current {
			currentCount++
		}

		if currentCount > 2 {
			if duplicateStartIndex == -1 {
				duplicateStartIndex = idx
				duplicateEndIndex = idx
			} else {
				duplicateEndIndex = idx
			}
		} else if currentCount <= 2 && duplicateStartIndex != -1 {
			swap(nums, idx, duplicateStartIndex)
			duplicateStartIndex++
			duplicateEndIndex++
		}

		if idx == len(nums)-1 {
			if duplicateStartIndex != -1 {
				return len(nums) - (duplicateEndIndex - duplicateStartIndex + 1)
			}
			return len(nums)
		}
	}

	return 0
}

func swap(nums []int, i, j int) {
	temp := nums[i]
	nums[i] = nums[j]
	nums[j] = temp
}
Loading Comments... Disqus Loader
comments powered by Disqus