Longest Common Prefix Leetcode Solution 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 "".

Leetcode Solution (Python)

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        prefix = ''
        # Length of smallest string
        minlen = len(strs[0])
        for string in strs:
            if len(string)<minlen:
                minlen = len(string)
        
        for i in range(0,minlen):
            curr_char = strs[0][i]
            for string in strs:
                if string[i]!=curr_char:
                    return prefix
            prefix += curr_char
        
        return prefix

Elements of Programming Interviews in Python: The Insiders’ Guide

How to speed up R code in RStudio

I just found out by trial and error that the suppressing of print statements in RStudio greatly speeds up the R code.

In my case, code that was originally estimated to take around 40 hours to run,  just ran in under an hour after I suppressed all the print statements in the for loops.

This is supported by evidence in other forums, for example in StackOverflow: R: Does the use of the print function inside a for loop slow down R?

Basically, if your code prints too much output to the console, it will slow down RStudio and your R code as well. It may be due to all the output clogging up the memory in RStudio. R is known to be “single thread” so it can only use 1 CPU at a time, even if your computer has multiple cores.

Hence, the tips are to:

  • Reduce the number of print statements in the code manually.
  • Set quiet=TRUE in all scan statements. Basically, the default behavior is that scan() will print a line, saying how many items have been read.

This is especially true with for loops, since the amount of printed output can easily number to the millions, and overwhelm RStudio.