Bird
Raised Fist0
DSA Pythonprogramming~20 mins

Longest Common Prefix in DSA Python - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Longest Common Prefix Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Longest Common Prefix Function
What is the output of the following code that finds the longest common prefix among a list of strings?
DSA Python
def longest_common_prefix(strs):
    if not strs:
        return ""
    prefix = strs[0]
    for s in strs[1:]:
        while not s.startswith(prefix):
            prefix = prefix[:-1]
            if not prefix:
                return ""
    return prefix

print(longest_common_prefix(["flower", "flow", "flight"]))
A"flow"
B"f"
C"fl"
D""
Attempts:
2 left
💡 Hint
Check the common starting letters of all strings.
❓ Predict Output
intermediate
2:00remaining
Longest Common Prefix with Empty String Present
What will be the output of this code when one string is empty?
DSA Python
def longest_common_prefix(strs):
    if not strs:
        return ""
    prefix = strs[0]
    for s in strs[1:]:
        while not s.startswith(prefix):
            prefix = prefix[:-1]
            if not prefix:
                return ""
    return prefix

print(longest_common_prefix(["", "b", "c"]))
A"b"
B""
C"c"
DNone
Attempts:
2 left
💡 Hint
If any string is empty, what can the prefix be?
🔧 Debug
advanced
2:00remaining
Identify the Error in Longest Common Prefix Code
What error will this code produce when run?
DSA Python
def longest_common_prefix(strs):
    prefix = strs[0]
    for s in strs[1:]:
        while not s.startswith(prefix):
            prefix = prefix[:-1]
    return prefix

print(longest_common_prefix([]))
AIndexError
BReturns empty string ""
CTypeError
DInfinite loop
Attempts:
2 left
💡 Hint
What happens if strs is an empty list?
🧠 Conceptual
advanced
2:00remaining
Longest Common Prefix Algorithm Complexity
What is the time complexity of the standard longest common prefix algorithm that compares characters one by one among n strings of average length m?
AO(n * m)
BO(n + m)
CO(m^2)
DO(n^2)
Attempts:
2 left
💡 Hint
Consider how many characters are compared in total.
🚀 Application
expert
3:00remaining
Longest Common Prefix in Trie Data Structure
Given a trie built from the strings ["interview", "interrupt", "integrate", "integral"], what is the longest common prefix represented by the trie?
A"integr"
B"int"
C"inter"
D"inte"
Attempts:
2 left
💡 Hint
Find the deepest node in the trie where all strings share the same path.

Practice

(1/5)
1. What does the Longest Common Prefix (LCP) problem ask you to find given a list of strings?
easy
A. The total number of strings in the list
B. The longest starting substring common to all strings
C. The longest substring common to any two strings
D. The longest ending substring common to all strings

Solution

  1. Step 1: Understand the problem definition

    The Longest Common Prefix means the longest substring at the start of all strings that is the same.
  2. Step 2: Compare options with the definition

    Only The longest starting substring common to all strings matches this definition exactly.
  3. Final Answer:

    The longest starting substring common to all strings -> Option B
  4. Quick Check:

    Longest Common Prefix = longest starting substring [OK]
Hint: Focus on the start of strings, not anywhere else [OK]
Common Mistakes:
  • Confusing prefix with suffix
  • Thinking about any substring instead of prefix
  • Counting total strings instead of prefix length
2. Which of the following Python code snippets correctly initializes a variable to store the longest common prefix as an empty string?
easy
A. lcp = None
B. lcp = []
C. lcp = ''
D. lcp = 0

Solution

  1. Step 1: Identify the correct data type for prefix storage

    The longest common prefix is a string, so it should be initialized as an empty string.
  2. Step 2: Match initialization with data type

    lcp = '' initializes lcp as an empty string, which is correct.
  3. Final Answer:

    lcp = '' -> Option C
  4. Quick Check:

    Prefix is a string, so empty string initialization [OK]
Hint: Use empty string '' to start prefix, not list or number [OK]
Common Mistakes:
  • Using list [] instead of string
  • Using None which is not a string
  • Using 0 which is a number, not string
3. What will be the output of the following Python code?
def longest_common_prefix(strs):
    if not strs:
        return ''
    prefix = strs[0]
    for s in strs[1:]:
        while not s.startswith(prefix):
            prefix = prefix[:-1]
            if not prefix:
                return ''
    return prefix

print(longest_common_prefix(['flower', 'flow', 'flight']))
medium
A. fl
B. flow
C. f
D. flower

Solution

  1. Step 1: Initialize prefix and iterate over strings

    Prefix starts as 'flower'. Check 'flow': 'flow' does not start with 'flower', so remove last char to 'flowe', then 'flow', which matches.
  2. Step 2: Check next string 'flight'

    'flight' does not start with 'flow', remove last char to 'flo', no match; then 'fl', which matches.
  3. Final Answer:

    fl -> Option A
  4. Quick Check:

    Common start of all strings = 'fl' [OK]
Hint: Shrink prefix until all strings start with it [OK]
Common Mistakes:
  • Returning first string without checking others
  • Not shrinking prefix correctly
  • Confusing substring anywhere with prefix
4. The following code is intended to find the longest common prefix but has a bug. What is the bug?
def longest_common_prefix(strs):
    prefix = strs[0]
    for s in strs:
        while not s.startswith(prefix):
            prefix = prefix[:-1]
    return prefix

print(longest_common_prefix(['dog', 'racecar', 'car']))
medium
A. No return statement inside the loop
B. Loop starts from first string causing incorrect prefix update
C. Using s.startswith(prefix) instead of prefix.startswith(s)
D. Missing check for empty prefix causing infinite loop

Solution

  1. Step 1: Analyze loop and prefix shrinking

    The code shrinks prefix until s starts with prefix, but does not check if prefix becomes empty.
  2. Step 2: Identify infinite loop risk

    If no common prefix exists, prefix will shrink to empty string, then prefix[:-1] stays empty, causing infinite loop.
  3. Final Answer:

    Missing check for empty prefix causing infinite loop -> Option D
  4. Quick Check:

    Empty prefix check needed to stop loop [OK]
Hint: Always check if prefix is empty to avoid infinite loops [OK]
Common Mistakes:
  • Not checking prefix empty condition
  • Looping over all strings including first
  • Confusing startswith arguments
5. Given a list of strings, how would you efficiently find the longest common prefix using a vertical scanning approach? Which of the following best describes the method?
hard
A. Compare characters column by column across all strings until a mismatch is found
B. Sort the strings and compare only the first and last strings completely
C. Use a hash map to count character frequencies at each position
D. Concatenate all strings and find the longest substring

Solution

  1. Step 1: Understand vertical scanning

    Vertical scanning means checking each character position across all strings one by one.
  2. Step 2: Identify stopping condition

    Stop when a mismatch or end of any string is found at that position.
  3. Final Answer:

    Compare characters column by column across all strings until a mismatch is found -> Option A
  4. Quick Check:

    Vertical scanning = column-wise character comparison [OK]
Hint: Check characters by columns, stop at first mismatch [OK]
Common Mistakes:
  • Confusing vertical scanning with sorting
  • Using hash maps unnecessarily
  • Concatenating strings instead of comparing
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