Bird
Raised Fist0
DSA Cprogramming~20 mins

Substring Search Patterns in DSA C - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Substring Search Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Naive Substring Search
What is the output of the following code that searches for the pattern "ana" in the text "banana" using a naive substring search?
DSA C
const char* text = "banana";
const char* pattern = "ana";

for (int i = 0; text[i] != '\0'; i++) {
    int j = 0;
    while (pattern[j] != '\0' && text[i + j] == pattern[j]) {
        j++;
    }
    if (pattern[j] == '\0') {
        printf("%d ", i);
    }
}
printf("\n");
A0 2
B1 2 3
C2 4
D1 3
Attempts:
2 left
💡 Hint
Check each position in the text where the pattern matches fully.
❓ Predict Output
intermediate
2:00remaining
Output of KMP Prefix Table Construction
What is the output array (prefix table) constructed by the KMP algorithm for the pattern "ABABAC"?
DSA C
int prefix[] = {0, 0, 0, 0, 0, 0};
char pattern[] = "ABABAC";
int len = 0;
for (int i = 1; pattern[i] != '\0'; i++) {
    while (len > 0 && pattern[i] != pattern[len]) {
        len = prefix[len - 1];
    }
    if (pattern[i] == pattern[len]) {
        len++;
        prefix[i] = len;
    }
}
for (int i = 0; i < 6; i++) {
    printf("%d ", prefix[i]);
}
printf("\n");
A0 0 1 2 3 1
B0 1 0 1 2 0
C0 0 1 2 3 0
D0 0 1 2 0 1
Attempts:
2 left
💡 Hint
The prefix table stores the length of the longest proper prefix which is also suffix for each prefix of the pattern.
🔧 Debug
advanced
2:00remaining
Identify the error in Rabin-Karp hash update
What error will occur when running this Rabin-Karp rolling hash update code snippet for substring search?
DSA C
int base = 256;
int prime = 101;
int h = 1;
int pattern_len = 3;
for (int i = 0; i < pattern_len - 1; i++) {
    h = (h * base) % prime;
}
int text_hash = 0;
int pattern_hash = 0;
char text[] = "abcd";
char pattern[] = "bcd";
for (int i = 0; i < pattern_len; i++) {
    pattern_hash = (base * pattern_hash + pattern[i]) % prime;
    text_hash = (base * text_hash + text[i]) % prime;
}
// Update hash for next window
text_hash = (base * (text_hash - text[0] * h) + text[pattern_len]) % prime;
if (text_hash < 0) text_hash += prime;
printf("%d\n", text_hash);
ARuntime error: array index out of bounds
BNo error, prints 31
CWrong hash value due to missing parentheses
DNegative hash value without correction
Attempts:
2 left
💡 Hint
Check the calculation of the rolling hash and the array indices used.
❓ Predict Output
advanced
2:00remaining
Output of Boyer-Moore Bad Character Table
What is the value of bad character table entry for character 'c' in the pattern "abcabc" using Boyer-Moore preprocessing?
DSA C
int badChar[256];
char pattern[] = "abcabc";
int m = 6;
for (int i = 0; i < 256; i++) {
    badChar[i] = -1;
}
for (int i = 0; i < m; i++) {
    badChar[(unsigned char)pattern[i]] = i;
}
printf("%d\n", badChar['c']);
A5
B2
C-1
D3
Attempts:
2 left
💡 Hint
The bad character table stores the last occurrence index of each character in the pattern.
🧠 Conceptual
expert
2:00remaining
Minimum number of comparisons in substring search
Which substring search algorithm guarantees the minimum worst-case number of character comparisons for searching a pattern of length m in a text of length n?
AKnuth-Morris-Pratt (KMP) algorithm
BNaive substring search algorithm
CRabin-Karp algorithm
DBoyer-Moore algorithm
Attempts:
2 left
💡 Hint
Consider worst-case linear time complexity and character comparisons.

Practice

(1/5)
1. What is the main goal of substring search algorithms in strings?
easy
A. To find if a smaller string exists inside a larger string
B. To sort the characters of a string alphabetically
C. To reverse the entire string
D. To count the total number of characters in a string

Solution

  1. Step 1: Understand substring search purpose

    Substring search algorithms check if a smaller string (pattern) appears inside a bigger string (text).
  2. Step 2: Compare options with definition

    Only To find if a smaller string exists inside a larger string describes finding a smaller string inside a larger one, which matches substring search.
  3. Final Answer:

    To find if a smaller string exists inside a larger string -> Option A
  4. Quick Check:

    Substring search = find smaller string inside larger [OK]
Hint: Substring search means finding a smaller string inside a bigger one [OK]
Common Mistakes:
  • Confusing substring search with sorting or reversing strings
  • Thinking substring search counts characters
  • Mixing substring search with string length calculation
2. Which of the following is the correct syntax to check if string pattern is a substring of string text in C?
easy
A. if (text.find(pattern)) { /* found */ }
B. if (text.contains(pattern)) { /* found */ }
C. if (pattern in text) { /* found */ }
D. if (strstr(text, pattern) != NULL) { /* found */ }

Solution

  1. Step 1: Recall C substring search function

    In C, strstr() returns a pointer to the first occurrence of pattern in text, or NULL if not found.
  2. Step 2: Check each option's syntax

    if (strstr(text, pattern) != NULL) { /* found */ } uses strstr correctly with NULL check. Options A, B, C use syntax from other languages or invalid in C.
  3. Final Answer:

    if (strstr(text, pattern) != NULL) { /* found */ } -> Option D
  4. Quick Check:

    C substring search uses strstr() [OK]
Hint: Use strstr() in C to find substring, check for NULL [OK]
Common Mistakes:
  • Using methods from other languages like contains() or find()
  • Not checking if strstr() returns NULL
  • Confusing order of arguments in strstr()
3. What will be the output of the following C code snippet?
char text[] = "hello world";
char *pos = strstr(text, "wor");
if (pos != NULL) {
    printf("%ld", pos - text);
} else {
    printf("-1");
}
medium
A. 6
B. 0
C. -1
D. 3

Solution

  1. Step 1: Understand strstr() return value

    strstr(text, "wor") returns pointer to first occurrence of "wor" in "hello world", which starts at index 6.
  2. Step 2: Calculate pointer difference

    Subtracting text pointer from pos gives index 6, which is printed.
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    Substring "wor" starts at index 6 [OK]
Hint: Pointer difference in strstr() gives substring start index [OK]
Common Mistakes:
  • Printing pointer value instead of index difference
  • Assuming substring starts at 0 or 3 incorrectly
  • Not checking if strstr() returns NULL before subtracting
4. Identify the error in the following C code for substring search:
char *find_substring(char *text, char *pattern) {
    for (int i = 0; i <= strlen(text); i++) {
        if (strncmp(&text[i], pattern, strlen(pattern)) == 0) {
            return &text[i];
        }
    }
    return NULL;
}
medium
A. Function should return int index, not pointer
B. strncmp() is used incorrectly; should use strcmp() instead
C. The loop condition should be 'i < strlen(text) - strlen(pattern) + 1' to avoid overflow
D. No error; code works correctly

Solution

  1. Step 1: Analyze loop boundary

    The loop runs from 0 to strlen(text), but comparing substrings beyond text length minus pattern length causes overflow.
  2. Step 2: Correct loop condition

    Loop should run until i <= strlen(text) - strlen(pattern) to safely compare substrings of pattern length.
  3. Final Answer:

    The loop condition should be 'i < strlen(text) - strlen(pattern) + 1' to avoid overflow -> Option C
  4. Quick Check:

    Loop boundary must prevent substring overflow [OK]
Hint: Loop till text length minus pattern length to avoid overflow [OK]
Common Mistakes:
  • Looping beyond valid substring start positions
  • Using strcmp instead of strncmp for partial comparison
  • Ignoring return type correctness
5. You want to find all occurrences of substring pat in string txt using C. Which approach correctly finds all start indices of pat in txt?
hard
A. Use strstr() once and return the first found position only
B. Use a loop with strstr() starting from last found position + 1 until strstr() returns NULL
C. Use strcmp() on entire text and pattern directly
D. Use strlen() to compare lengths and decide if substring exists

Solution

  1. Step 1: Understand strstr() usage for multiple occurrences

    strstr() returns pointer to first occurrence. To find all, repeatedly call strstr() starting after last found position.
  2. Step 2: Evaluate options

    Use a loop with strstr() starting from last found position + 1 until strstr() returns NULL correctly describes looping with strstr() advancing pointer. Use strstr() once and return the first found position only finds only first occurrence. Options C and D do not find all occurrences.
  3. Final Answer:

    Use a loop with strstr() starting from last found position + 1 until strstr() returns NULL -> Option B
  4. Quick Check:

    Loop with strstr() to find all occurrences [OK]
Hint: Loop with strstr() advancing pointer to find all matches [OK]
Common Mistakes:
  • Using strstr() only once for all matches
  • Using strcmp() which compares whole strings only
  • Relying on length checks without searching
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard