- Published on
Digit anagrams
- Authors
- Name
- Moch Lutfi
- @kaptenupi
Problem
Given an array of integers a
, your task is to count the number of pairs i
and j
(where 0 ≤ i < j < a.length
), such that a[i]
and a[j]
are digit anagrams.
Two integers are considered to be digit anagrams if they contain the same digits. In other words, one can be obtained from the other by rearranging the digits (or trivially, if the numbers are equal). For example, 12345
and 54231
are digit anagrams, but 321
and 782
are not (since they don't contain the same digits). 220
and 22
are also not considered as digit anagrams, since they don't even have the same number of digits.
Example
For a = [25, 35, 872, 228, 53, 278, 872]
, the output should be solution(a) = 4
.
There are 4
pairs of digit anagrams:
a[1] = 35
anda[4] = 53
(i = 1
andj = 4
),a[2] = 872
anda[5] = 278
(i = 2
andj = 5
),a[2] = 872
anda[6] = 872
(i = 2
andj = 6
),a[5] = 278
anda[6] = 872
(i = 5
andj = 6
).
Solution
Just read through comment in the code to help you understand
_32import (_32 "strings"_32 "sort"_32)_32_32func solution(a []int) int {_32_32 anagramCount := 0_32_32 // Create a map to store the frequency of digits in each number_32 freqMap := make(map[string]int)_32_32 for i := 0; i < len(a); i++ {_32_32 // Convert the integer to a string and sort the digits_32 numStr := strconv.Itoa(a[i])_32 numArr := strings.Split(numStr, "")_32 sort.Strings(numArr)_32 sortedNumStr := strings.Join(numArr, "")_32_32 // Check if we've seen this sorted string before_32 if val, ok := freqMap[sortedNumStr]; ok {_32 // If we have, increment the count and update the map_32 anagramCount += val_32 freqMap[sortedNumStr] = val + 1_32 } else {_32 // If we haven't seen this sorted string before, add it to the map with a count of 1_32 freqMap[sortedNumStr] = 1_32 }_32 }_32 return anagramCount_32}