ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

T-SQL: Find Longest Common Prefix

T-SQL

Goal -- WPM

Ready
Exercise Algorithm Area
1CREATE FUNCTION dbo.LongestCommonPrefix (@StringArray NVARCHAR(MAX))
2RETURNS NVARCHAR(MAX)
3AS
4BEGIN
5-- Input is a comma-separated string of strings, e.g., 'flower,flow,flight'
6
7DECLARE @Strings TABLE (Value NVARCHAR(MAX), Idx INT IDENTITY(1,1));
8DECLARE @CurrentPos INT = 1;
9DECLARE @DelimiterPos INT;
10DECLARE @CurrentString NVARCHAR(MAX);
11
12-- Populate the table variable from the delimited string
13WHILE @CurrentPos <= LEN(@StringArray)
14BEGIN
15SET @DelimiterPos = CHARINDEX(',', @StringArray, @CurrentPos);
16IF @DelimiterPos = 0
17BEGIN
18SET @CurrentString = SUBSTRING(@StringArray, @CurrentPos, LEN(@StringArray));
19SET @CurrentPos = LEN(@StringArray) + 1;
20END
21ELSE
22BEGIN
23SET @CurrentString = SUBSTRING(@StringArray, @CurrentPos, @DelimiterPos - @CurrentPos);
24SET @CurrentPos = @DelimiterPos + 1;
25END
26INSERT INTO @Strings (Value) VALUES (@CurrentString);
27END
28
29DECLARE @NumStrings INT = (SELECT COUNT(*) FROM @Strings);
30
31-- Edge case: Empty input array
32IF @NumStrings = 0
33BEGIN
34RETURN '';
35END
36
37-- Edge case: Array with only one string
38IF @NumStrings = 1
39BEGIN
40RETURN (SELECT Value FROM @Strings WHERE Idx = 1);
41END
42
43DECLARE @Prefix NVARCHAR(MAX) = '';
44DECLARE @FirstString NVARCHAR(MAX) = (SELECT Value FROM @Strings WHERE Idx = 1);
45DECLARE @FirstStringLen INT = LEN(@FirstString);
46
47-- Iterate through characters of the first string
48FOR @i = 1 TO @FirstStringLen
49BEGIN
50DECLARE @CharToMatch NCHAR(1) = SUBSTRING(@FirstString, @i, 1);
51DECLARE @AllMatch BIT = 1;
52
53-- Check this character against all other strings
54DECLARE @CurrentStringIdx INT = 2;
55WHILE @CurrentStringIdx <= @NumStrings
56BEGIN
57DECLARE @OtherString NVARCHAR(MAX) = (SELECT Value FROM @Strings WHERE Idx = @CurrentStringIdx);
58DECLARE @OtherStringLen INT = LEN(@OtherString);
59
60-- If current character index is out of bounds for the other string, or characters don't match
61IF @i > @OtherStringLen OR SUBSTRING(@OtherString, @i, 1) <> @CharToMatch
62BEGIN
63SET @AllMatch = 0;
64BREAK; -- Exit inner loop
65END
66SET @CurrentStringIdx = @CurrentStringIdx + 1;
67END
68
69IF @AllMatch = 1
70BEGIN
71SET @Prefix = @Prefix + @CharToMatch;
72END
73ELSE
74BEGIN
75BREAK; -- Exit outer loop, prefix found
76END
77END
78
79RETURN @Prefix;
80END
Algorithm description viewbox

T-SQL: Find Longest Common Prefix

Algorithm description:

This T-SQL function determines the longest common prefix among a list of strings. The list is provided as a comma-separated string, which is parsed into a table. The function then iterates character by character through the first string in the list, comparing each character with the corresponding character in all other strings. If a mismatch is found or a string ends prematurely, the process stops, and the common prefix found so far is returned. This is useful for tasks like file path manipulation or searching through indexed data.

Algorithm explanation:

The function first parses the input comma-separated string into a table variable. It handles edge cases for zero or one string in the input. It then iterates through the characters of the first string. For each character, it checks if it matches the character at the same position in all other strings. If a mismatch occurs or a string is shorter than the current character index, the loop breaks, and the prefix accumulated up to that point is returned. If all characters of the first string match across all other strings, the entire first string is the common prefix. The time complexity is O(S * M), where S is the number of strings and M is the length of the shortest string (or the length of the common prefix). The space complexity is O(S * L_avg), where L_avg is the average length of strings, for storing them in the table variable. The invariant is that `@Prefix` always holds the common prefix found among strings processed so far for the current character index.

Pseudocode:

FUNCTION LongestCommonPrefix(stringArray):
  IF stringArray is empty THEN RETURN ""
  IF stringArray has only one string THEN RETURN that string

  prefix = ""
  firstString = stringArray[0]

  FOR i from 0 to length(firstString) - 1:
    currentChar = firstString[i]
    FOR j from 1 to length(stringArray) - 1:
      otherString = stringArray[j]
      IF i >= length(otherString) OR otherString[i] != currentChar THEN
        RETURN prefix
    prefix = prefix + currentChar

  RETURN prefix