Erlang: Efficiently Find First Non-Repeating Character
-module(string_utils). -export([find_first_non_repeating_char/1]). %% @doc Finds the first character in a string that does not repeat. %% Returns the character if found, otherwise returns null. find_first_non_repeating_char(String) when is_list(String) -> % Handle empty string ed...
This Erlang module provides a function to find the first non-repeating character in a given string. It's useful in text processing tasks where identifying unique elements is crucial, such as in data validation or simple...
The `find_first_non_repeating_char` function first handles the edge case of an empty input string, returning `null`. It then calls `build_frequency_map` to create a map where keys are characters and values are their counts within the string. This map is built using `lists:foldl`, efficiently updating counts for each character. The `build_frequency_map` function ensures that even if a character appears multiple times, its count is correctly incremented. After constructing the frequency map, `find_first_unique` is called. This helper function iterates through the original string, checking the frequency of each character in the map. The first character encountered with a frequency of exactly 1 is returned. If the loop completes without finding such a character (meaning all characters repeat or the string was empty), `null` is returned. The time complexity is O(N) because the string is traversed twice, and map operations (insertion/lookup) are O(1) on average. The space complexity is O(K), where K is the number of unique characters in the string, to store the frequency map. This approach guarantees correctness by ensuring every character's frequency is accounted for before determining uniqueness.
function find_first_non_repeating_char(string): if string is empty: return null frequency_map = create an empty map for each character in string: increment count for character in frequency_map, default to 0 if not presen...