Invert Maps And Report Key Collisions

Invert a map into a reverse lookup and surface duplicate values as collisions, iterating keys in sorted order so the surviving key is deterministic.

GoData Integrity

Code

gosnippet
52 lines
package main

import (
	"fmt"
	"sort"
)

// invert flips a service->port map into port->service.
// map range order is random, so the keys are sorted before iterating:
// that makes the winner among duplicate values deterministic; the rest land in collisions and get reported at the end
func invert(m map[string]int) (map[int]string, map[int][]string) {
	keys := make([]string, 0, len(m))
	for key := range m {
		keys = append(keys, key)
	}
	sort.Strings(keys)

	lookup := make(map[int]string, len(m))
	collisions := make(map[int][]string)
	for _, key := range keys {
		port := m[key]
		if _, seen := lookup[port]; seen {
			collisions[port] = append(collisions[port], key)
			continue
		}
		lookup[port] = key
	}
	return lookup, collisions
}

func main() {
	byName := map[string]int{
		"postgres": 5432,
		"pg-dev":   5432,
		"redis":    6379,
		"web":      8080,
	}

	byPort, collisions := invert(byName)
	for _, port := range []int{5432, 6379, 8080} {
		fmt.Printf("%d -> %s\n", port, byPort[port])
	}

	ports := make([]int, 0, len(collisions))
	for port := range collisions {
		ports = append(ports, port)
	}
	sort.Ints(ports)
	for _, port := range ports {
		fmt.Printf("collision report on %d: %v\n", port, collisions[port])
	}
}

Inverting and tracking collisions

Invert Maps And Report Key Collisions comes down to the functions invert and main.

The one repetition in this snippet is the loop for key := range m.

Applying it

Entry signature: func invert(m map[string]int) (map[int]string, map[int][]string)

Running the file prints labeled results such as collision report on — each operation’s effect is visible in the output.

Treat main as the orchestrator calling invert in a fixed order.

Statements that matter

for _, port := range []int{5432, 6379, 8080} {
fmt.Printf("%d -> %s\n", port, byPort[port])
}
for port := range collisions {
ports = append(ports, port)
}
for _, port := range ports {
fmt.Printf("collision report on %d: %v\n", port, collisions[port])
}

Interactive Tools for This Topic

FAQ

What does Invert Maps And Report Key Collisions print when run?
No setup needed: run the file and look for labeled lines like `collision report on` in the output.