Notice
Recent Posts
Recent Comments
Link
«   2026/04   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
Archives
Today
Total
관리 메뉴

제니 블로그

Solving Leetcode : Longest common prefix 본문

Building Blocks

Solving Leetcode : Longest common prefix

jennystar 2023. 3. 15. 16:47

This is leetcode problem number 14, difficulty of "Easy".

Problem being :

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return ""

The leetcode provides us with the starting :

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:

the longestCommonPrefix function will need list as an argument.

The way I thought of first, is using enumerate to loop through all the letters in the list.

prefix = strs[0]
for count, value in enumerate(strs[1:], 1):
    while value.find(prefix) != 0:
        prefix = prefix[:-1]
        if not prefix:
            return ""
return prefix

if not strs:
    return ""
  1. Function initializes the prefix variable to the first string in the list, thus it being set to strs[0].
  2. Iterates over the remaining strings in strs using enumerate with a starting index of 1 --> count takes on values 1, 2, 3, etc...
  3. Enter a while loop that checks whether the prefix is a valid prefix of s
  4. Use a .find() method of string, returning the index of the first occurence of the substring prefix in s.
  5. If there is no prefix, return nothing.

The runtime ended up with 37ms, beating 56.29% of the other solutions summited, and 13.9 MB of memory taken, beating 79.57%. 

'Building Blocks' 카테고리의 다른 글

Using Ansible  (0) 2025.05.12
Installing Ansible  (0) 2025.05.12
Using .gitignore  (0) 2023.03.09
Linux - Simple Commands and Navigation Part 1  (0) 2023.02.17
Basics of Github - Concepts  (0) 2023.02.16