215 views
// Implement autocomplete for movies: // by entering the first 3+ letters, output the top-3 matches alphabetically. // ["macarthur", "interstellar", "intrusion", "macao", "into the abyss", "internship"] // me -> [] // mac -> ["macao", "macarthur", "machinist"] // int -> ["internship", "interstellar", "into the abyss"] // interstellar -> ["interstellar"] // intr -> ["intrusion"] // intrusion -> ["intrusion"] // into -> ["into the abyss"] // stellaris -> [] package main func main() {}
Asked at
AI answer
go package main
import ( "fmt" "sort" "strings" )
func autocomplete(movies []string, input string) []string { if len(input) < 3 { return []string{} }
input = strings.ToLower(input)
matches := []string{}
for _, movie := range movies {
if strings.HasPrefix(strings.ToLower(movie), input) {
matches = append(matches, movie)
}
}
sort.Strings(matches)
if len(matches) > 3 {
matches = matches[:3]
}
return matches
}
func main() { movies := []string{"macarthur", "interstellar", "intrusion", "macao", "into the abyss", "internship"}
tests := []string{"me", "mac", "int", "interstellar", "intr", "intrusion", "into", "stellaris"}
for _, test := range tests {
fmt.Printf("%s -> %v\n", test, autocomplete(movies, test))
}
}
This code implements autocomplete based on the first 3 or more letters, returning up to three matches in alphabetical order.
Also asked at Okko
- Did you write tests? Which ones?
- [name] asked: Tell me about your current workplace — what kind of company is it, what product are you working on?
- Does the order in which fields are included in a composite index matter?
- Tell how you optimized queries — you mentioned reducing from 10–12 minutes to 5–7 minutes. What kind of report takes so long? How did you optimize?
- Tracing has already been done — what exactly did you do?
Similar questions
- Implement a top-5 service retrieval in O(N) using an auxiliary structure.
- Implement a generic Filter function that takes a slice and a predicate function and returns a filtered slice.
- package main import "fmt" func execute(template string, args ...interface{}) string { return template } func main() { res := execute("mailbox/:mailbox/folder/:folder_id", "inbox", 123) // Output: mailbox/inbox/folder/123 fmt.Println(res) }
- """ Seats in a cinema are arranged in a single row. A newly arrived viewer chooses a seat to sit as far as possible from others. That is, the distance from the seat they choose to the nearest viewer should be maximized. It is guaranteed that there are always free seats and at least one viewer is already seated. Write a function that, given a row of seats (an array of zeros and ones), returns the distance (number of gaps between chairs) from the chosen seat to the nearest viewer. [1, 0, 0, 0, 1] -> 2 [1, 0, 1, 0, 0, 1, 0, 0, 0, 1] -> 2 [1, 0, 1, 0] -> 1 """ func maxPlaces(arr []int) int { }
- Implement a function that takes several sorted slices of integers and merges them into one sorted slice.