- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a list of lowercase alphabet strings called words. We have to find the length of the longest contiguous sublist where the first letter of each words have the same first letter.

So, if the input is like words = ["she", "sells", "seashells", "on", "the", "sea", "shore"], then the output will be 3, the longest contiguous sublist is ["she", "sells", "seashells"]. The first letter for each words is 's'.

To solve this, we will follow these steps −

cnt := 1

maxcnt := 0

prev_char := blank string

for each word in words, do

if prev_char is empty, then

prev_char := first letter of word

otherwise when prev_char is same as first letter of word, then

cnt := cnt + 1

otherwise,

prev_char := first letter of word

cnt := 1

maxcnt := maximum of maxcnt and cnt

return maxcnt

Let us see the following implementation to get better understanding

def solve(words): cnt = 1 maxcnt = 0 prev_char = "" for word in words: if prev_char == "": prev_char = word[0] elif prev_char == word[0]: cnt += 1 else: prev_char = word[0] cnt = 1 maxcnt = max(maxcnt, cnt) return maxcnt words = ["she", "sells", "seashells", "on", "the", "sea", "shore"] print(solve(words))

["she", "sells", "seashells", "on", "the", "sea", "shore"]

3

- Related Questions & Answers
- Program to find length of contiguous strictly increasing sublist in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest sublist with given condition in Python
- Program to find length of longest consecutive sublist with unique elements in Python
- Program to find length of longest sublist with value range condition in Python
- Program to find length of longest alternating inequality elements sublist in Python
- Program to find sum of contiguous sublist with maximum sum in Python
- Program to find length of longest strictly increasing then decreasing sublist in Python
- Program to find length of longest sublist whose sum is 0 in Python
- Program to find length of shortest sublist with maximum frequent element with same frequency in Python
- Program to find length of longest contiguously strictly increasing sublist after removal in Python
- Program to find length of longest sublist containing repeated numbers by k operations in Python
- Program to find length of longest matrix path length in Python
- Program to find all words which share same first letters in Python
- Program to find a sublist where first and last values are same in Python

Advertisements