| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.WordSubsets; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class WordSubsetsFrequencyFiltering : IWordSubsets |
| | 16 | | { |
| | 17 | | private const int LettersCount = 'z' - 'a' + 1; |
| | 18 | |
|
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(words1.Length + words2.Length) |
| | 21 | | /// Space complexity - O(words1.Length) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="words1"></param> |
| | 24 | | /// <param name="words2"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public IList<string> WordSubsets(string[] words1, string[] words2) |
| 2 | 27 | | { |
| 2 | 28 | | var maxCharFrequencies = new int[LettersCount]; |
| | 29 | |
|
| 14 | 30 | | foreach (var word in words2) |
| 4 | 31 | | { |
| 4 | 32 | | var tempFrequency = new int[maxCharFrequencies.Length]; |
| | 33 | |
|
| 20 | 34 | | foreach (var c in word) |
| 4 | 35 | | { |
| 4 | 36 | | tempFrequency[c - 'a']++; |
| | 37 | |
|
| 4 | 38 | | maxCharFrequencies[c - 'a'] = Math.Max(maxCharFrequencies[c - 'a'], tempFrequency[c - 'a']); |
| 4 | 39 | | } |
| 4 | 40 | | } |
| | 41 | |
|
| 2 | 42 | | var result = new List<string>(); |
| | 43 | |
|
| 26 | 44 | | foreach (var word in words1) |
| 10 | 45 | | { |
| 10 | 46 | | var wordFrequency = new int[maxCharFrequencies.Length]; |
| | 47 | |
|
| 162 | 48 | | foreach (var c in word) |
| 66 | 49 | | { |
| 66 | 50 | | wordFrequency[c - 'a']++; |
| 66 | 51 | | } |
| | 52 | |
|
| 203 | 53 | | if (wordFrequency.Where((t, i) => t < maxCharFrequencies[i]).Any()) |
| 4 | 54 | | { |
| 4 | 55 | | continue; |
| | 56 | | } |
| | 57 | |
|
| 6 | 58 | | result.Add(word); |
| 6 | 59 | | } |
| | 60 | |
|
| 2 | 61 | | return result; |
| 2 | 62 | | } |
| | 63 | | } |