### Understanding fixed length of arrays in Rust with anagram function

2 months ago | 📖 3 min read

## What are we trying to do?

We are going to learn about a simple use case of Rust arrays by using them to find anagrams. This short example aims to show difference between `Vec` ,`HashMap` and array in Rust programming language.

## What is an anagram?

Two words are said to be anagrams if all letters of one wore are the letter for other word as well. Example `food` and `fodo` are anagrams. Since it is a letter-counting problem our obvious thought would be to use data structure like `Hashmap` but we are going to approach things differently. Now let's look at Rust code for detecting if words are anagrams.

``````pub fn is_anagram(s: String, t: String) -> bool {
if s.len() != t.len() {
return false;
}
let mut s_vec: [usize; 27] = [0; 27];
for ch in s.chars() {
let index = ch as u32 - 'a' as u32;
let uindex = index as usize;
s_vec[uindex] = s_vec[uindex] + 1;
}
let mut t_vec: [usize; 27] = [0; 27];
for ch in t.chars() {
let index = ch as u32 - 'a' as u32;
let uindex = index as usize;
t_vec[uindex] = t_vec[uindex] + 1;
}
t_vec == s_vec
}``````

Let's break down the code.

``````if s.len() != t.len() {
return false;
}``````

We return false because two words cannot be composed of same letters if they are not even of same length. Next, we define two arrays of length 27 that store `usize` and are initialized to 0. Next,for both words we iterate through characters and update value by one if they appear.So, a increases value at index 0 by one b increases on index and so on.

``````  let mut s_vec: [usize; 27] = [0; 27];
for ch in s.chars() {
let index = ch as u32 - 'a' as u32;
let uindex = index as usize;
s_vec[uindex] = s_vec[uindex] + 1;
}
let mut t_vec: [usize; 27] = [0; 27];
for ch in t.chars() {
let index = ch as u32 - 'a' as u32;
let uindex = index as usize;
t_vec[uindex] = t_vec[uindex] + 1;
}``````

And finally, we just compare two arrays. If the count of each letter in both words is equal then it will return true (i.e. words are anagrams) else false.

Note that here we are dealing with only lowercase alphabets

## Why this approach?

• This approach is more efficient compared to `Vec` or `Hashmap`
• We are able to directly compare two arrays at the end
• The solution is easy to understand

## Conclusion

In scenarios where we need to store data whose length is already known or even for dynamic data we need the final result in things such as number of counts this approach. Hence, always look for approach that use builtin simple data types before moving to complex solutions like `Vec` or `Hashmap`.