Advanced Map Operations in Go

Advanced Map Operations in Go

Hello, Go enthusiasts! Congratulations on reaching this advanced lesson on Go's map data structure. You've come a long way in this course, and your dedication is truly commendable. Whether you are organizing data like a contact list, counting word occurrences, or managing inventory, maps in Go provide a powerful solution for handling key-value pairs. Let’s explore how maps can simplify complex tasks through practical examples and further reinforce the skills you've honed so far.

Problem 1: Word Counter

Imagine you have a large piece of text, perhaps a short story or a report, and you want to count how often each word appears. This isn't just a fun computation — it can be a critical tool for writers seeking to diversify their vocabulary.

Picture yourself coding a feature for a text editor that offers feedback on word usage. This allows a writer to refine their work by ensuring they use varied vocabulary effectively.

Naive Approach

Consider iterating over the text word by word, keeping track of each instance using slices. This may work for a short excerpt, but as the text grows, it becomes inefficient. Each word requires a scan through the slice to update counts, resulting in a time complexity of O(n)O(n) per word operation. For the complete text, this exponential growth leads to inefficient O(n2)O(n^2) complexity.

Go
package main

import (
    "fmt"
    "strings"
)

func main() {
    text := "Go Go Go"
    wordsList := []string{}  // Slice to store unique words
    countList := []int{}     // Corresponding slice to store word counts
    words := strings.Split(text, " ")  // Split the text into words using space as delimiter

    for _, word := range words {
        index := indexOf(wordsList, word)
        if index != -1 {
            countList[index]++  // If word exists, increment its count
        } else {
            wordsList = append(wordsList, word)  // Add new word to list
            countList = append(countList, 1)     // Initialize its count to 1
        }
    }

    // Print each word and its count
    for i, word := range wordsList {
        fmt.Printf("%s: %d\n", word, countList[i])
    }
}

// Helper function to find index of a word in the slice
func indexOf(slice []string, target string) int {
    for i, v := range slice {
        if v == target {
            return i  // Return index if word is found
        }
    }
    return -1  // Return -1 if word is not found
}

Go's strings.Split function splits a string into substrings based on specified delimiters and returns a slice of these substrings. This method is analogous to slicing fruits; with "apple,banana,cherry" split by ',', you get ["apple", "banana", "cherry"].

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal