How to find the minimum distance between two numbers in a slice with Go

1 Answer

0 votes
package main

import (
	"errors"
	"fmt"
	"math"
)

/*
FindMinimumDistance returns the minimum distance between two target values.

Returns:
  - The minimum distance between target1 and target2.
  - -1 if no valid pair exists.

Time Complexity: O(n)
Space Complexity: O(1)
*/
func FindMinimumDistance(numbers []int, target1, target2 int) (int, error) {
	if numbers == nil {
		return -1, errors.New("numbers cannot be nil")
	}

	// Handle the special case where both targets are the same.
	if target1 == target2 {
		return findMinimumDistanceForDuplicates(numbers, target1), nil
	}

	lastSeenIndex := -1
	minDistance := math.MaxInt

	for currentIndex, currentValue := range numbers {

		// Ignore values that are not one of the targets.
		if currentValue != target1 && currentValue != target2 {
			continue
		}

		/*
		   If we've previously seen one target and the current
		   value is the other target, update the minimum distance.
		*/
		if lastSeenIndex >= 0 && currentValue != numbers[lastSeenIndex] {
			distance := currentIndex - lastSeenIndex

			if distance < minDistance {
				minDistance = distance
			}
		}

		// Remember the most recent occurrence.
		lastSeenIndex = currentIndex
	}

	if minDistance == math.MaxInt {
		return -1, nil
	}

	return minDistance, nil
}

/*
findMinimumDistanceForDuplicates finds the minimum distance
between consecutive occurrences of the same value.
*/
func findMinimumDistanceForDuplicates(
	numbers []int,
	target int,
) int {
	previousIndex := -1
	minDistance := math.MaxInt

	for currentIndex, currentValue := range numbers {

		if currentValue != target {
			continue
		}

		if previousIndex >= 0 {
			distance := currentIndex - previousIndex

			if distance < minDistance {
				minDistance = distance
			}
		}

		previousIndex = currentIndex
	}

	if minDistance == math.MaxInt {
		return -1
	}

	return minDistance
}

func main() {
	numbers := []int{2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3,
	}

	distance, err := FindMinimumDistance(numbers, 3, 8)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	if distance >= 0 {
		fmt.Printf(
			"Minimum distance between 3 and 8: %d\n",
			distance,
		)
	} else {
		fmt.Println("No valid pair found.")
	}
}


/*
run:

Minimum distance between 3 and 8: 2

*/

 



answered Oct 21 by avibootz
...