Longest Common Prefix

Problem Statement

Given two strings, you have to find the longest common prefix of the two strings.

For example, if apple and application are the two strings, then appl is the longest common prefix for the two strings.

Input

The first line of input is the first string: string1.

The second line of input is the second string: string2.

Output

Print the longest common prefix of the two strings: string1 and string2.

As is

The boilerplate code is already there to read the input from user, in the main() function, and to print the value returned by the longestCommonPrefix() function. Do not edit this code.

To do ✍

largestCommonPrefix() has two parameters: string1 and string2. Complete the function that finds the longest common prefix of the two strings, and returns the same.

Example 1

Test input

apple
application

Test output

appl

Explanation

For the two strings appl is the common, and also the longest common prefix. a, ap, and app are also common prefixes, but are not the longest.

Example 2

Test input

bank
banana

Test output

ban

Useful References

Python Program

# Complete the following function
def longestCommonPrefix(string1, string2):





# Boilerplate code - Do not edit the following
def main():
    string1 = input()
    string2 = input()
    print(longestCommonPrefix(string1, string2))

if __name__ == "__main__":
    main()

Input and Outputs 1

apple
application
appl

Input and Outputs 2

apple
banana

Input and Outputs 3

banana
banking
ban

Input and Outputs 4

manali
manas
mana
# Complete the following function
def longestCommonPrefix(string1, string2):
    length = min(len(string1), len(string2))
    for i in range(length):
        if string1[i] != string2[i]:
            return string1[0:i]

# Boilerplate code - Do not edit the following
def main():
    string1 = input()
    string2 = input()
    print(longestCommonPrefix(string1, string2))

if __name__ == "__main__":
    main()
show answer
main.py
⏵︎ Run Tests
Reset
Download
×
Code copied to clipboard successfully 👍