š Scenario: You work in a word game company. You need to check if two words are anagrams. Anagrams are words made by rearranging the letters of another word, like "listen" and "silent".
šÆ Goal: Build a simple Go program that checks if two given words are anagrams using a letter counting technique.
š What You'll Learn
Create two string variables with exact words
Create a map to count letters
Write a loop to count letters in the first word
Write a loop to decrease counts using the second word
Check if all counts are zero to confirm anagram
Print true if anagrams, else false
š” Why This Matters
š Real World
Checking anagrams is useful in word games, puzzles, and text analysis tools.
š¼ Career
Understanding maps and loops is essential for many programming jobs, especially in data processing and algorithm design.
Progress0 / 4 steps
1
Create two string variables for the words
Create two string variables called word1 and word2 with values "listen" and "silent" respectively.
DSA Go
Hint
Use := to create and assign string variables.
2
Create a map to count letters in the first word
Create a variable called letterCount as a map from rune to int. Initialize it with make(map[rune]int).
DSA Go
Hint
Use make(map[rune]int) to create an empty map for counting letters.
3
Count letters in word1 and adjust counts with word2
Use a for loop with variable ch to iterate over word1 and increase letterCount[ch] by 1. Then use another for loop with variable ch to iterate over word2 and decrease letterCount[ch] by 1.
DSA Go
Hint
Use for _, ch := range word to loop over each letter.
4
Check if all counts are zero and print result
Use a for loop with variables _, count to iterate over letterCount. If any count is not zero, print false and return. After the loop, print true.
DSA Go
Hint
If any letter count is not zero, the words are not anagrams.
Practice
(1/5)
1. What is the main idea behind checking if two strings are anagrams?
easy
A. Both strings have the same characters with the same frequency
B. Both strings have the same length only
C. Both strings start with the same character
D. Both strings contain vowels only
Solution
Step 1: Understand anagram definition
Anagrams are words or phrases made by rearranging letters of another, so they must have the same characters with the same counts.
Step 2: Compare character frequency
Checking if two strings have the same frequency of each character confirms if they are anagrams.
Final Answer:
Both strings have the same characters with the same frequency -> Option A
Quick Check:
Character frequency equality = Anagram check [OK]
Hint: Check if sorted strings are equal [OK]
Common Mistakes:
Only comparing string lengths
Ignoring character counts
Checking first characters only
2. Which Go code snippet correctly checks if two strings are anagrams by sorting?
easy
A. sort.Strings([]string{s1, s2}); return s1 == s2