Elixir: Find First Non-Repeating Character
defmodule StringAlgorithms do @moduledoc """ Provides algorithms for string manipulation. """ @doc """ Finds the first non-repeating character in a given string. It iterates through the string, counting character frequencies using a map. Then, it iterates again to find the first...
This Elixir function finds the first character in a string that does not repeat. It first constructs a map to store the frequency of each character. Then, it iterates through the string again, returning the first charact...
The `first_non_repeating_char` function first handles the edge case of an empty string by returning `nil`. For non-empty strings, it calls `build_frequency_map` to create a map where keys are characters and values are their counts. This map is built by iterating through the string once using `Enum.reduce`. The `build_frequency_map` helper uses `Map.update` to efficiently increment counts. Subsequently, `find_first_unique` iterates through the original string again. For each character, it checks its count in the `frequency_map`. If the count is 1, that character is returned immediately. If no such character is found after checking the entire string, `Enum.find_value` implicitly returns `nil`. The time complexity is O(N) because we iterate through the string twice, and map operations 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.
FUNCTION first_non_repeating_char(string): IF string is empty THEN RETURN null END IF CREATE an empty map called frequency_map FOR EACH character in string: INCREMENT count for character in frequency_map END FOR FOR EACH...