In this tutorial, we will solve the leetcode problem longest common prefix in python.
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Input: strs = ["flower","flow","flight"]
Output: "fl"
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
new_str = ""
if len(strs) == 0:
return ""
elif len(strs) == 1:
return strs[0]
strs.sort()
last = min(len(strs[0]), len(strs[-1]))
j = 0
while j < last and (strs[0][j] == strs[len(strs)-1][j]):
new_str += strs[0][j]
j += 1
return new_str
setp1: first we make an empty string, and added two base cases.
step2: Now, we sort the string and set the variable last to the minimum of string at index 0 and last index.
step3: Now, we run a while loop till last and check the string characters, and adding it the new string while updating the index variable j.
step4: After the loop we return the new string as our required solution.
Trainings :
Data Science Training in Indore | Python Training in Indore | Data Analytics Training in Indore | Blockchain Training in Indore | React JS Training in Indore | Web Development Training in Indore | Full Stack Development Training in Indore |Free Courses and Resource :
Dart | OpenCV Tutorials | Projects | Interview Questions | Python Data Structures and Algorithms | Aptitude Tests | Verbal Aptitude | Matplotlib Tutorials | Examples | Interview Questions | HackerRank Python | Pandas Tutorials | Projects | Interview Questions | Rust Tutorials | Projects | Interview Questions | ExpressJS Tutorials | Projects | Interview Questions | Django | MongoDB Tutorials | Examples | Interview Questions | HackerRank C Program Solutions | Python Tutorials by CodersDaily | React.js Tutorials | Golang Tutorials | Projects | Interview Questions | MS Sql Server Tutorials | Examples | Interview Questions | Verbal Ability Tutorial | Numpy Tutorials | Projects | Interview Questions | Power BI Tutorials | Projects | Interview Questions | Example Dashboards | Tensor Flow | HackerRank C++ Solutions | Django REST Framework Tutorial | CodeChef Python Solutions | Leetcode Python Solutions | Reasoning Ability Tutorial | Quantitative Ability Tutorial | C++ Tutorials | HackerRank Java Solutions | TCS NQT Mock Test Series | Verbal Aptitude 2 | HackerRank DSA Solutions | HackerRank SQL Solutions | Javascript | Node.js Tutorials |Interview Questions :
Pandas Tutorials | Projects | Interview Questions | ExpressJS Tutorials | Projects | Interview Questions | Django | Python Tutorials by CodersDaily | Golang Tutorials | Projects | Interview Questions | Numpy Tutorials | Projects | Interview Questions | Django REST Framework Tutorial |Top Colleges in India :
Indian Institute of Technology Bombay | Jaypee University of Engineering and Technology - Guna |