Published on

Digit anagrams

Authors

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 and a[4] = 53 (i = 1 and j = 4),
  • a[2] = 872 and a[5] = 278 (i = 2 and j = 5),
  • a[2] = 872 and a[6] = 872 (i = 2 and j = 6),
  • a[5] = 278 and a[6] = 872 (i = 5 and j = 6).

Solution

Just read through comment in the code to help you understand


_32
import (
_32
    "strings"
_32
    "sort"
_32
)
_32
_32
func 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
}