package shared // DuplicatePositions identifies a retained representative and later duplicates // by their positions in the caller's input sequence. type DuplicatePositions struct { Representative int Removed []int } // GroupDuplicates retains the first eligible record per key; ineligible records // remain independent. Duplicate groups follow representative encounter order. func GroupDuplicates[K comparable](count int, keyFor func(int) (K, bool)) ([]int, []DuplicatePositions) { retained := make([]int, 0, count) groups := make([]DuplicatePositions, 0) byKey := make(map[K]int) for index := 0; index < count; index++ { key, eligible := keyFor(index) if !eligible { retained = append(retained, index) continue } if group, exists := byKey[key]; exists { groups[group].Removed = append(groups[group].Removed, index) continue } byKey[key] = len(groups) groups = append(groups, DuplicatePositions{Representative: index}) retained = append(retained, index) } var duplicates []DuplicatePositions for _, group := range groups { if len(group.Removed) > 0 { duplicates = append(duplicates, group) } } return retained, duplicates }