Bird
0
0
DSA Cprogramming~10 mins

Longest Common Prefix in DSA C - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to return the first string as the initial prefix.

DSA C
char* longestCommonPrefix(char** strs, int strsSize) {
    if (strsSize == 0) return "";
    char* prefix = [1];
    return prefix;
}
Drag options to blanks, or click blank then click option'
ANULL
Bstrs[0]
C""
Dstrs[1]
Attempts:
3 left
💡 Hint
Common Mistakes
Using strs[1] instead of strs[0]
Returning NULL instead of a string
Returning an empty string "" immediately
2fill in blank
medium

Complete the code to loop through each string in the array.

DSA C
for (int i = [1]; i < strsSize; i++) {
    // compare prefix with strs[i]
}
Drag options to blanks, or click blank then click option'
A1
B0
CstrsSize
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Starting loop at 0 causing redundant comparison
Starting loop at strsSize causing no iteration
Starting loop at -1 causing invalid index
3fill in blank
hard

Fix the error in the while loop condition to compare characters correctly.

DSA C
while (prefix[j] && strs[i][j] && prefix[j] == [1]) {
    j++;
}
Drag options to blanks, or click blank then click option'
Astrs[i][j]
B'\0'
Cstrs[0][j]
Dprefix[j]
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing prefix[j] with itself
Comparing with strs[0][j] which is prefix itself
Comparing with '\0' which is end of string
4fill in blank
hard

Fill both blanks to update prefix length and terminate it correctly.

DSA C
prefix[[1]] = '\0';
int j = [2];
Drag options to blanks, or click blank then click option'
Aj
B0
C1
DstrsSize
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 instead of j to terminate prefix
Not resetting j to 0 causing wrong indexing
Using strsSize as index causing out of bounds
5fill in blank
hard

Fill all three blanks to complete the longestCommonPrefix function.

DSA C
char* longestCommonPrefix(char** strs, int strsSize) {
    if (strsSize == 0) return "";
    char* prefix = [1];
    int i = [2];
    int j = 0;
    while (i < strsSize) {
        while (prefix[j] && strs[i][j] && prefix[j] == strs[i][j]) {
            j++;
        }
        prefix[[3]] = '\0';
        i++;
        j = 0;
    }
    return prefix;
}
Drag options to blanks, or click blank then click option'
Astrs[0]
B1
Cj
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Starting i at 0 causing redundant comparison
Terminating prefix at 0 or wrong index
Not initializing prefix correctly