0
0
DSA Pythonprogramming~10 mins

Longest Common Prefix in DSA Python - Interactive Practice

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

Complete the code to return an empty string if the input list is empty.

DSA Python
def longest_common_prefix(strs):
    if not strs:
        return [1]
Drag options to blanks, or click blank then click option'
A''
BNone
C0
Dstrs
Attempts:
3 left
💡 Hint
Common Mistakes
Returning None instead of an empty string.
Returning 0 or the list itself.
2fill in blank
medium

Complete the code to initialize the prefix as the first string in the list.

DSA Python
def longest_common_prefix(strs):
    if not strs:
        return ''
    prefix = [1]
Drag options to blanks, or click blank then click option'
A''
Bstrs[1]
Cstrs[0]
Dstrs[-1]
Attempts:
3 left
💡 Hint
Common Mistakes
Using strs[1] which may not exist or is not the first string.
Starting with an empty string which won't help find the prefix.
3fill in blank
hard

Fix the error in the loop that compares prefix with each string.

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
Drag options to blanks, or click blank then click option'
A0
B1
C-1
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Starting loop from 0 causes redundant comparison.
Using negative or out-of-range indices.
4fill in blank
hard

Fill both blanks to correctly reduce the prefix until it matches the start of the string.

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]1
            if not prefix:
                return [2]
    return prefix
Drag options to blanks, or click blank then click option'
A[:-
B''
C[-
D[::
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect slicing syntax like prefix[+1].
Returning None instead of empty string.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps each word to its length if length is greater than 3.

DSA Python
words = ['apple', 'bat', 'car', 'door']
lengths = { [1] : [2] for [3] in words if len([3]) > 3 }
Drag options to blanks, or click blank then click option'
Aword
Blen(word)
Ditem
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Using len(word) as key instead of value.