DEV Community

Cover image for Unlocking Uniqueness: Mastering the Unique Character Algorithm in Go
Ruben Alvarado
Ruben Alvarado

Posted on

Unlocking Uniqueness: Mastering the Unique Character Algorithm in Go

Hello, Go enthusiast! Today we're covering a new algorithm in Go.

This is a commonly asked question for entry-level positions as it covers Go basics like maps, runes, and string manipulation. We'll explore how to determine if all characters in a string are unique.

Problem Statement

As we have been doing, let's start by understanding the problem statement.

Implement an algorithm to determine if a string contains only unique characters.

Breaking down the problem statement, we have a string as input, we need to process each character in the string to determine if any are repeated, and finally return a boolean as output.

Now that we've established our input, process, and output, let's define our algorithm to solve it.

Algorithm to Solve it

The first step is to initialize a data structure to contain each character and track its occurrences. In Go, we have maps for this purpose. Using the make built-in function, let's declare our set of characters.

When used for maps, this function expects just one argument: the type for the map. Here, we're declaring a map of runes with bool values to keep track of each character's occurrence.

charMap := make(map[rune]bool)
Enter fullscreen mode Exit fullscreen mode

Next, utilizing Go's elegant for-range loop syntax, we iterate through each character in the string.

for _, c := range s {} //s is the input string
Enter fullscreen mode Exit fullscreen mode

Here's where the magic happens: if c is already in charMap, we return false because this character has appeared previously in the string.

if charMap[c] {
    return false
}
Enter fullscreen mode Exit fullscreen mode

If the character isn't in the charMap yet, we add it to track it for future iterations.

charMap[c] = true
Enter fullscreen mode Exit fullscreen mode

Finally, if the loop completes without finding any repetition, it means every character is unique, so we return true.

return true
Enter fullscreen mode Exit fullscreen mode

And voilà! We've solved the unique character algorithm. Here are some test cases you can use to verify the solution:

  • abcdef → returns true because it contains no repeated characters.
  • hello → returns false because it contains a repeated letter l

Final Thoughts

We are gradually increasing the difficulty of algorithms in this series. As I've been emphasizing throughout, you must strengthen your fundamentals before tackling more complex challenges. There's a saying: "Learn to walk before you run."

So, keep practicing and remember me when you land that desired job. As usual, you can find this and other algorithms in Go and TypeScript in my algorithms GitHub repo: https://github.com/RubenOAlvarado/algorithms
Until the next one!

Photo by Igor Omilaev in Unsplash

Top comments (0)