T-SQL: Find First Non-Repeating Character
CREATE FUNCTION dbo.FindFirstNonRepeatingChar ( @InputString NVARCHAR(MAX) ) RETURNS NVARCHAR(1) AS BEGIN DECLARE @CharCounts TABLE ( CharValue NVARCHAR(1), Count INT ); DECLARE @i INT = 1; DECLARE @StringLength INT = LEN(@InputString); DECLARE @CurrentChar NVARCHAR(1); -- Handle...
This T-SQL function identifies the first character in a string that appears only once. It iterates through the string, counts the occurrences of each character using a temporary table, and then iterates again to find the...
The function first handles the edge case of an empty input string by returning NULL. It then iterates through the input string, using a `WHILE` loop and `SUBSTRING`, to populate a temporary table `@CharCounts` with each character and its frequency. A second `WHILE` loop iterates through the original string again. For each character, it checks its count in the `@CharCounts` table. If the count is exactly 1, that character is returned as the first non-repeating character. If the loop completes without finding such a character, it means all characters repeat, and NULL is returned. The time complexity is O(N) because we iterate through the string twice, and table lookups/updates are effectively constant time for a small alphabet. The space complexity is O(K), where K is the number of unique characters in the string, due to the temporary table.
FUNCTION FindFirstNonRepeatingChar(inputString): IF inputString is empty THEN RETURN NULL END IF CREATE a temporary table `charCounts` with columns `charValue` and `count` FOR EACH character `currentChar` in `inputString...