Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Check if two given strings are anagrams

Posted on January 26, 2022January 26, 2022 by admin

Overview

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the word anagram itself can be rearranged into nagaram, also the word binary into brainy, and the word adobe into the abode.

For example

Input: abc, bac
Ouput: true

Input: abc, cb
Ouput: false

Here is the idea of how to do it. Create a map of string to int. Now

  • Traverse the first string and increase the count of each character in the map
  • Traverse the second string and decrease the count of each character in the map
  • Traverse the first string again and if for any character the count is non-zero in the map then return false.
  • In the end return true

Program

Here is the program for the same.

package main

import "fmt"

func isAnagram(s string, t string) bool {

	lenS := len(s)
	lenT := len(t)

	if lenS != lenT {
		return false
	}

	anagramMap := make(map[string]int)

	for i := 0; i < lenS; i++ {
		anagramMap[string(s[i])]++
	}

	for i := 0; i < lenT; i++ {
		anagramMap[string(t[i])]--
	}

	for i := 0; i < lenS; i++ {
		if anagramMap[string(s[i])] != 0 {
			return false
		}
	}

	return true
}

func main() {
	output := isAnagram("abc", "bac")
	fmt.Println(output)

	output = isAnagram("abc", "bc")
	fmt.Println(output)
}

Output

true
false
©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme