String Manipulation
Repeated Characters
Programming
Algorithms
Data Processing

Testing for repeated characters in a string

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Testing for repeated characters in a string can mean two slightly different things: checking whether any character appears more than once anywhere in the string, or checking whether the same character appears consecutively. The correct implementation depends on which definition you actually need.

Detect Any Repeated Character

If the question is simply whether any character occurs more than once, a set is the most direct solution.

python
1def has_repeated_character(text):
2    seen = set()
3    for ch in text:
4        if ch in seen:
5            return True
6        seen.add(ch)
7    return False
8
9
10print(has_repeated_character("abcd"))
11print(has_repeated_character("abca"))
text
False
True

This exits early as soon as a repeat is found, which is efficient and easy to read.

A Shorter Version with Length Comparison

For a compact solution, compare the string length with the length of the set of its characters.

python
1def has_repeated_character(text):
2    return len(text) != len(set(text))
3
4
5print(has_repeated_character("abcd"))
6print(has_repeated_character("abca"))

This is concise, but it does not short-circuit. It still builds the full set even if a repeat appears early.

Detect Consecutive Repeats Instead

Sometimes the actual requirement is to detect repeated adjacent characters such as the double l in hello. That is a different test.

python
1def has_consecutive_repeat(text):
2    for i in range(1, len(text)):
3        if text[i] == text[i - 1]:
4            return True
5    return False
6
7
8print(has_consecutive_repeat("hello"))
9print(has_consecutive_repeat("world"))
text
True
False

This distinction matters because abca has repeated characters, but no consecutive repeat.

Counting Repeats

If you need more than a boolean answer, use collections.Counter.

python
1from collections import Counter
2
3text = "mississippi"
4counts = Counter(text)
5repeated = {ch: count for ch, count in counts.items() if count > 1}
6print(repeated)
text
{'i': 4, 's': 4, 'p': 2}

That is useful for validation, reporting, or analytics where you care which characters repeat and how often.

Case and Whitespace Rules

Before implementing the check, decide whether A and a should count as the same character and whether spaces or punctuation matter.

python
def has_repeat_case_insensitive(text):
    normalized = text.lower()
    return len(normalized) != len(set(normalized))

Without an explicit normalization rule, two developers can write different "correct" solutions to the same requirement.

Complexity

The set-based solution runs in linear time relative to the string length. That is the right default for normal inputs. A nested-loop approach would be much slower and is rarely justified unless the character set is extremely constrained and you are solving a specialized problem.

Character Set Assumptions Matter

For most application code, iterating over Python strings is enough. But if the requirement is tied to user-visible text rather than code points, Unicode normalization may matter. Two visually identical strings can behave differently if one uses combined characters and the other uses precomposed ones.

Decide Whether Space Counts

In usernames, passwords, or identifiers, spaces often count as ordinary characters. In free-form text cleaning, they may be ignored deliberately. That one rule changes the result, so a good implementation should either document the policy clearly or normalize the string before checking repeats.

Common Pitfalls

  • Not clarifying whether "repeated" means anywhere in the string or only consecutively.
  • Forgetting to define case sensitivity and punctuation rules.
  • Using a nested-loop comparison when a set-based linear solution is simpler.
  • Choosing the length-comparison shortcut when early exit would be better for long strings.
  • Returning only a boolean when the real requirement is to identify which characters repeated.

Summary

  • Use a set to detect whether any character repeats anywhere in a string.
  • Use neighbor comparison when the requirement is repeated adjacent characters.
  • Use Counter when you need counts instead of a yes-or-no answer.
  • Define normalization rules such as case sensitivity before coding the check.
  • The best implementation depends on the exact meaning of "repeated" in the requirement.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.