
Sponsored
Sponsored
This approach utilizes arrays to count the frequency of each letter from 'a' to 'z' for both strings. By iterating through the characters of each word, we can populate two frequency arrays. Then, by comparing the absolute differences between corresponding elements of these arrays, we can determine if the words are almost equivalent.
Time Complexity: O(n + 26), which simplifies to O(n) where n is the length of the words.
Space Complexity: O(1) since the frequency arrays have a constant size of 26.
1using System;
2
3public class Solution {
4 public bool AreAlmostEquivalent(string word1, string word2) {
5 int[] freq1 = new int[26];
6 int[] freq2 = new int[26];
7
8 for (int i = 0; i < word1.Length; i++) {
9 freq1[word1[i] - 'a']++;
10 freq2[word2[i] - 'a']++;
11 }
12
13 for (int i = 0; i < 26; i++) {
14 if (Math.Abs(freq1[i] - freq2[i]) > 3) {
15 return false;
16 }
17 }
18 return true;
19 }
20
21 public static void Main() {
22 Solution sol = new Solution();
23 Console.WriteLine(sol.AreAlmostEquivalent("abcdeef", "abaaacc"));
24 }
25}The C# solution employs a similar mechanism as other solutions, using arrays to track character occurrences. The final check ensures no frequency difference exceeds 3.
This alternate approach uses the hashmap or hash table data structure to record character frequencies for both strings. Hash maps are dynamic, allowing insertion without specifying a fixed field size. The hash maps' keys are characters, and their values are frequencies. The function calculates differences between frequency keys of two maps.
Time Complexity: O(n), limited by character frequency computation.
Space Complexity: O(1), determined by number of distinct characters, since max 26 distinct alphabets.
1function areAlmostEquivalent
JavaScript uses a Map object to store each word's character frequencies. In verifying deviations, both maps initialize with zero where characters don't exist. The integrity of almost equivalent criteria is confirmed by verifying the deviation of each character between 0 and 3.