hackerrank/miscellaneous/friend_circle_queries/main_trial_03.gox
package main
func MaxCircle(queries [][]int32) (result []int32) {
var friendshipID int32
size := make(map[int32]int32) // map[friendshipID]size
friendship := make(map[int32]int32) // map[personID]friendshipID
var biggestSize int32
for _, q := range queries {
// Check whether these 2 friendship are already friends
// If yes, then do nothing
// fmt.Println("\nq:", q)
person1 := q[0]
person2 := q[1]
if friendship[person1] != 0 && friendship[person1] == friendship[person2] {
result = append(result, result[len(result)-1])
continue
}
// If a person is new, assign them to a new friendship of her/himself
if friendship[person1] == 0 {
friendshipID++
friendship[person1] = friendshipID
size[friendshipID] = 1
// fmt.Println("NEW: person1:", person1)
// fmt.Println("NEW: friendshipID:", friendshipID)
// fmt.Println("NEW: size[friendshipID]:", size[friendshipID])
}
if friendship[person2] == 0 {
friendshipID++
friendship[person2] = friendshipID
size[friendshipID] = 1
// fmt.Println("NEW: person2:", person2)
// fmt.Println("NEW: friendshipID:", friendshipID)
// fmt.Println("NEW: size[friendshipID]:", size[friendshipID])
}
// Create new friendship for them
friendshipID++
// fmt.Println("friendshipID:", friendshipID)
// fmt.Println("size[friendship[person1]]:", size[friendship[person1]])
// fmt.Println("size[friendship[person2]]:", size[friendship[person2]])
size[friendshipID] = size[friendship[person1]] +
size[friendship[person2]]
delete(size, friendship[person1])
delete(size, friendship[person2])
// fmt.Println("size[friendshipID]:", size[friendshipID])
// Merge all their friends into the same friendshipID
oldFriendship1 := friendship[person1]
oldFriendship2 := friendship[person2]
// Assign all persons in oldFriendship1 and 2 to new friendship
for p, f := range friendship {
if f == oldFriendship1 || f == oldFriendship2 {
friendship[p] = friendshipID
}
}
if size[friendshipID] > biggestSize {
biggestSize = size[friendshipID]
}
// fmt.Println("friendship:", friendship)
// fmt.Println("size:", size)
result = append(result, biggestSize)
}
return result
}