• + 0 comments

    I'm trying to solve this in Go and all of my attempts are timing out on test cases 1 - 3, despite working on the sample input 0. I think it's the loop reading/handling the query names, but I don't know why. Some examples:

    // Using a Scanner to handle queries
    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
    	name := scanner.Text()
    	if phone, ok := addressBook[name]; !ok {
    		fmt.Println("Not found")
    	} else {
    		fmt.Printf("%s=%s\n", name, phone)
    	}
    }
    if err := scanner.Err(); err != nil {
    	log.Fatal(err)
    }
    
    // Using fmt.Scan to handle queries
    var query string
    for {
    	_, err := fmt.Scan(&query)
    	if err != nil {
    		if err == io.EOF {
    			break
    		}
    		log.Fatal(err)
    	}
    	if phone, ok := addressBook[query]; !ok {
    		fmt.Println("Not found")
    	} else {
    		fmt.Printf("%s=%s\n", query, phone)
    	}
    }
    
    // Reading all of STDIN then iterating over it
    stdin, err := io.ReadAll(os.Stdin)
    if err != nil {
    	log.Fatal(err)
    }
    
    queries := strings.Split(string(stdin), "\n")
    for _, name := range queries {
    	if phone, ok := addressBook[name]; !ok {
    		fmt.Println("Not found")
    	} else {
    		fmt.Printf("%s=%s\n", name, phone)
    	}
    }