Program to find all words which share same first letters in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of words in lowercase letters, we have to find the length of the longest contiguous sublist where all words have the same first letter.

So, if the input is like ["she", "sells", "seashells", "on", "the", "seashore"], then the output will be 3 as three contiguous words are "she", "sells", "seashells", all have same first letter 's'.

To solve this, we will follow these steps −

  • maxlength := 0
  • curr_letter := Null, curr_length := 0
  • for each word in words, do
    • if curr_letter is null or curr_letter is not same as word[0], then
      • maxlength := maximum of maxlength, curr_length
      • curr_letter := word[0], curr_length := 1
    • otherwise,
      • curr_length := curr_length + 1
  • return maximum of maxlength and curr_length

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, words):
      maxlength = 0
      curr_letter, curr_length = None, 0
      for word in words:
         if not curr_letter or curr_letter != word[0]:
            maxlength = max(maxlength, curr_length)
            curr_letter, curr_length = word[0], 1
            curr_length += 1
      return max(maxlength, curr_length)
ob = Solution()
words = ["she", "sells", "seashells", "on", "the", "seashore"]


["she", "sells", "seashells", "on", "the", "seashore"]


Published on 06-Oct-2020 07:28:53