diff --git a/problems/compare-strings-by-frequency-of-the-smallest-character/compare_strings_by_frequency_of_the_smallest_character.go b/problems/compare-strings-by-frequency-of-the-smallest-character/compare_strings_by_frequency_of_the_smallest_character.go new file mode 100644 index 000000000..5434d51ab --- /dev/null +++ b/problems/compare-strings-by-frequency-of-the-smallest-character/compare_strings_by_frequency_of_the_smallest_character.go @@ -0,0 +1,33 @@ +package problem1170 + +import "sort" + +func numSmallerByFrequency(queries []string, words []string) []int { + ans, m := make([]int, len(queries)), make([]int, len(words)) + for i, w := range words { + m[i] = f(w) + } + sort.Ints(m) + for i, q := range queries { + t := f(q) + for j := len(m) - 1; j >= 0; j-- { + if t >= m[j] { + break + } + ans[i]++ + } + } + return ans +} + +func f(s string) int { + m, p := [26]int{}, byte(25) + for i := 0; i < len(s); i++ { + k := s[i] - 'a' + m[k]++ + if p > k { + p = k + } + } + return m[p] +} diff --git a/problems/compare-strings-by-frequency-of-the-smallest-character/compare_strings_by_frequency_of_the_smallest_character_test.go b/problems/compare-strings-by-frequency-of-the-smallest-character/compare_strings_by_frequency_of_the_smallest_character_test.go new file mode 100644 index 000000000..6aa450488 --- /dev/null +++ b/problems/compare-strings-by-frequency-of-the-smallest-character/compare_strings_by_frequency_of_the_smallest_character_test.go @@ -0,0 +1,33 @@ +package problem1170 + +import ( + "reflect" + "testing" +) + +type testType struct { + in []string + w []string + want []int +} + +func TestNumSmallerByFrequency(t *testing.T) { + tests := [...]testType{ + { + in: []string{"cbd"}, + w: []string{"zaaaz"}, + want: []int{1}, + }, + { + in: []string{"bbb", "cc"}, + w: []string{"a", "aa", "aaa", "aaaa"}, + want: []int{1, 2}, + }, + } + for _, tt := range tests { + got := numSmallerByFrequency(tt.in, tt.w) + if !reflect.DeepEqual(got, tt.want) { + t.Fatalf("in: %v, got: %v, want: %v", tt.in, got, tt.want) + } + } +}