Skip to content

S2Q1 · Words with Consecutive Identical Letters

⚡ Quick Reference

Function: words_with_consecutive_letters(words: list) -> list

Core idea: for each word, check if any two adjacent characters are the same (case-insensitive).

def words_with_consecutive_letters(words):
    def has_consecutive(word):
        w = word.lower()
        return any(w[i] == w[i+1] for i in range(len(w) - 1))
    return [w for w in words if has_consecutive(w)]

Key rules: - Case-insensitive → lowercase before comparing - Check adjacent pairs: word[i] == word[i+1] - Preserve original order - any() short-circuits on the first matching pair


Problem Statement

Problem

Write a function words_with_consecutive_letters(words) that returns all words containing at least one pair of consecutive identical letters, in their original order.

Examples:

Input
["hello", "apple", "ball", "test", "cat"]
Output
["hello", "apple", "ball"]
Input
["sky", "fly", "run", "jump"]
Output
[]

Tracing example 1

Word Pairs checked Consecutive pair? Include?
"hello" he, el, ll✅, lo ll
"apple" ap, pp✅, pl, le pp
"ball" ba, al, ll✅ ll
"test" te, es, st none
"cat" ca, at none

Result: ["hello", "apple", "ball"]


Solution approaches

def words_with_consecutive_letters(words):
    def has_consecutive(word):
        w = word.lower()
        return any(a == b for a, b in zip(w, w[1:]))
    return [w for w in words if has_consecutive(w)]

zip(w, w[1:]) creates adjacent pairs without index arithmetic. any() short-circuits on the first match.

def words_with_consecutive_letters(words):
    result = []
    for word in words:
        w = word.lower()
        found = False
        for i in range(len(w) - 1):
            if w[i] == w[i + 1]:
                found = True
                break
        if found:
            result.append(word)
    return result
def words_with_consecutive_letters(words):
    has_consec = lambda w: any(
        w[i] == w[i+1] for i in range(len(w) - 1)
    )
    return [w for w in words if has_consec(w.lower())]
def words_with_consecutive_letters(words):
    has_consec = lambda w: any(a == b for a, b in zip(w, w[1:]))
    return list(filter(lambda w: has_consec(w.lower()), words))

Key takeaways

01

zip(w, w[1:]) - elegant adjacent pair iteration

zip(w, w[1:]) pairs each character with the next one without index arithmetic. It naturally stops one pair before the end - no off-by-one risk.

02

any() short-circuits - stops at first match

any(a==b for a,b in zip(w, w[1:])) stops checking as soon as the first consecutive pair is found. No need to scan the whole word once a match is confirmed.

03

Lowercase for comparison, return original case

Apply .lower() only for the comparison - keep the original word in the result list. has_consec(w.lower()) checks the lowercased version while the list comprehension appends the original w.