PL/SQL: Find First Non-Repeating Character in String
CREATE OR REPLACE FUNCTION find_first_non_repeating_idx ( p_input_string IN VARCHAR2 ) RETURN NUMBER IS v_char_counts DBMS_UTILITY.uncl_array; v_string_length NUMBER; v_char VARCHAR2(1); v_idx NUMBER; BEGIN -- Handle edge case: empty or null input string IF p_input_string IS NULL...
This PL/SQL function identifies the index of the first character in a string that appears only once. It's useful in text processing tasks, such as data validation or finding unique identifiers within log entries. For exa...
The function first handles edge cases by returning -1 for null or empty input strings. It then uses a helper function, `initialize_char_counts`, to create a frequency map (simulated using `DBMS_UTILITY.uncl_array`) of all characters in the input string. This map stores each unique character as a key and its occurrence count as the value. The main function then iterates through the input string again, character by character. For each character, it checks its count in the frequency map. If a character's count is exactly 1, its current index (1-based) is immediately returned, as this signifies the first non-repeating character. If the loop completes without finding such a character, it means all characters repeat, and -1 is returned. The time complexity is O(N) because we iterate through the string twice, and the space complexity is O(K), where K is the number of unique characters in the string (at most 256 for ASCII, or more for Unicode, but bounded).
FUNCTION find_first_non_repeating_idx(input_string): IF input_string is NULL or empty THEN RETURN -1 END IF char_counts = initialize_char_counts(input_string) FOR each character at index i in input_string: IF char_counts...