Your question is Optimize Time and Space. Take a moment with it on the right.
Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).
IMDB-style services aggregate millions of user ratings into per-title averages for display and ranking. The Go code below produces correct numbers but does not scale to a large catalog of titles and ratings.
package main
import "fmt"
import "strconv"
type Movie struct {
ID string
Title string
}
type Rating struct {
MovieID string
Score float64
}
func buildReport(movies []Movie, ratings []Rating) string {
report := ""
for _, m := range movies {
var total float64
var count int
for _, r := range ratings {
if r.MovieID == m.ID {
total += r.Score
count++
}
}
var avg float64
if count > 0 {
avg = total / float64(count)
}
report = report + m.Title + ": " + strconv.FormatFloat(avg, 'f', 2, 64) + "
"
}
return report
}
func topRated(movies []Movie, ratings []Rating, minCount int) []string {
var result []string
for _, m := range movies {
count := 0
for _, r := range ratings {
if r.MovieID == m.ID {
count++
}
}
if count >= minCount {
result = append(result, m.Title)
}
}
return result
}
func main() {
movies := []Movie{{"tt001", "Arrival Point"}, {"tt002", "Silent Harbor"}}
ratings := []Rating{{"tt001", 8.0}, {"tt001", 9.0}, {"tt002", 7.0}}
fmt.Println(buildReport(movies, ratings))
fmt.Println(topRated(movies, ratings, 2))
}
Explain the time and space complexity of buildReport and topRated as written, and how you would bring them down for a catalog with millions of titles and ratings.