First Repeating Character
Java coding interview problem for Character Problems: First Repeating Character.
Finding the First Repeating Character is one of the most common Java String interview questions asked in coding interviews.
Although it looks simple, this problem tests several important programming concepts including:
- String Traversal
- HashSet
- HashMap
- Frequency Counting
- Arrays
- Time Complexity
- Space Complexity
Interviewers often ask follow-up questions such as:
- Can you solve it in one pass?
- Can you solve it without HashSet?
- Which solution is the fastest?
- How would you handle Unicode characters?
- What if the input is extremely large?
Understanding multiple approaches prepares you for all these interview variations.
Problem Statement
Given a string, return the first character that repeats while traversing from left to right.
If no repeating character exists, return
'\0'
or
-1
depending on the problem statement.
Example 1
Input
abccba
Output
c
Explanation
a
↓
Seen once
b
↓
Seen once
c
↓
Seen once
c
↓
Repeats first
Example 2
Input
abcdaf
Output
a
Example 3
Input
abcdef
Output
No Repeating Character
Example 4
Input
programming
Output
r
Traversal
p
↓
First time
r
↓
First time
o
↓
First time
g
↓
First time
r
↓
Repeated
What is a Repeating Character?
A repeating character is a character that appears more than once.
Example
banana
Character Frequency
b → 1
a → 3
n → 2
Repeating characters
a
n
The first repeating character during traversal
is
a
because its second occurrence appears before
n
Another Example
programming
Traversal
p
↓
Unique
r
↓
Unique
o
↓
Unique
g
↓
Unique
r
↓
First Repeat
Answer
r
Why is this Question Asked in Interviews?
This problem evaluates whether candidates understand:
- HashSet
- HashMap
- Character Frequency
- Arrays
- String Traversal
- Collection Framework
It also introduces concepts used in:
- Data Processing
- Log Analysis
- Streaming Systems
- Text Analytics
Real-World Applications
Finding duplicate values has many practical applications.
Duplicate User Detection
Detect repeated usernames.
Fraud Detection
Identify repeated transaction IDs.
Log Analysis
Detect repeated log messages.
Data Cleaning
Find duplicate records.
Text Processing
Detect repeated symbols or characters.
First Repeating vs First Non-Repeating Character
These two interview questions are commonly confused.
First Repeating
Example
abccba
Traversal
a
↓
Seen
b
↓
Seen
c
↓
Seen
c
↓
Repeated
Answer
c
First Non-Repeating
Example
swiss
Frequency
s → 3
w → 1
i → 1
Answer
w
Comparison
| Feature | First Repeating | First Non-Repeating |
|---|---|---|
| Appears More Than Once | ✅ Yes | ❌ No |
| Appears Exactly Once | ❌ No | ✅ Yes |
| Uses HashSet | ✅ Often | ❌ Usually No |
| Uses Frequency Count | Sometimes | Very Common |
Mathematical Concept
Input
abccba
Traverse
a
↓
Store
b
↓
Store
c
↓
Store
c
↓
Already Exists
↓
Return
The first character already present in the set is the answer.
Visual Representation
Input
banana
Visited Set
{}
↓
{b}
↓
{b,a}
↓
{b,a,n}
↓
a already exists
↓
Answer
Dry Run
Input
programming
Visited
{}
Read
p
Visited
{p}
Read
r
Visited
{p,r}
Read
o
Visited
{p,r,o}
Read
g
Visited
{p,r,o,g}
Read
r
Already exists.
Answer
r
Approach 1 — Using HashSet (Recommended)
This is the simplest and most common interview solution.
The idea is straightforward.
- Traverse the string.
- Store every new character inside a HashSet.
- If the character already exists, return it immediately.
Since HashSet provides nearly constant-time lookup, this solution is highly efficient.
Why HashSet?
HashSet stores only unique values.
Example
banana
Initially
{}
After reading
b
{b}
After reading
a
{b,a}
When
a
appears again,
HashSet already contains it.
Therefore,
a
is the first repeating character.
Algorithm
- Create a HashSet.
- Traverse every character.
- If character exists in HashSet, return it.
- Otherwise add it to HashSet.
- Continue until the end.
Java Program
import java.util.HashSet;
import java.util.Set;
public class FirstRepeatingCharacter {
public static char firstRepeating(String text) {
Set<Character> visited =
new HashSet<>();
for (char ch : text.toCharArray()) {
if (visited.contains(ch)) {
return ch;
}
visited.add(ch);
}
return '\0';
}
public static void main(String[] args) {
System.out.println(
firstRepeating("programming"));
System.out.println(
firstRepeating("abccba"));
System.out.println(
firstRepeating("abcdef"));
}
}
Output
r
c
No Repeating Character
Step-by-Step Code Explanation
Create the HashSet.
Set<Character> visited =
new HashSet<>();
The set stores all characters seen so far.
Traverse the string.
for(char ch : text.toCharArray())
Process one character at a time.
Check whether the character already exists.
visited.contains(ch)
If true,
return the character immediately.
Otherwise
visited.add(ch);
Store it for future comparisons.
If traversal finishes
return '\0';
No repeating character exists.
Dry Run of HashSet Approach
Input
abccba
| Character | HashSet | Result |
|---|---|---|
| a | {a} | Continue |
| b | {a,b} | Continue |
| c | {a,b,c} | Continue |
| c | Already Exists | Return c |
Answer
c
Advantages
- Very easy to implement.
- Excellent interview solution.
- Stops immediately after finding the answer.
- Linear time complexity.
- Uses only one traversal.
Drawbacks
- Uses additional memory.
- Depends on Java Collections Framework.
Approach 2 — Using Frequency Array
If the input contains only ASCII characters,
an array provides an even faster implementation.
Instead of using a HashSet,
we maintain a frequency array while traversing the string.
As soon as a character frequency becomes
2
it is the first repeating character.
Algorithm
- Create an integer array.
- Traverse the string.
- Increment frequency.
- If frequency becomes two, return the character.
Java Program
public class FirstRepeatingArray {
public static char firstRepeating(String text) {
int[] frequency = new int[256];
for (char ch : text.toCharArray()) {
frequency[ch]++;
if (frequency[ch] == 2) {
return ch;
}
}
return '\0';
}
public static void main(String[] args) {
System.out.println(
firstRepeating("programming"));
System.out.println(
firstRepeating("abccba"));
}
}
Output
r
c
Step-by-Step Code Explanation
Create the array.
int[] frequency = new int[256];
Each index represents one ASCII character.
Increment frequency.
frequency[ch]++;
Check whether it became
2
if(frequency[ch] == 2)
Return immediately.
Time & Space Complexity
| Approach | Time | Extra Space |
|---|---|---|
| HashSet | O(n) | O(k) |
| Frequency Array | O(n) | O(1)* |
Where
- n = Length of the string
- k = Number of distinct characters
*For a fixed ASCII character set, the array size is constant (256), so the extra space is considered O(1).
Comparison of Approaches
| Feature | HashSet | Frequency Array |
|---|---|---|
| Interview Friendly | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Easy to Understand | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| Performance | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Supports Unicode | ⭐⭐⭐⭐⭐ | Limited (ASCII example) |
Advantages
- Both solutions run in O(n) time.
- HashSet provides a clean and intuitive implementation.
- Frequency Array is extremely fast for ASCII input.
- Both return the answer immediately upon finding the first repeated character.
Drawbacks
- HashSet requires additional memory.
- Frequency Array is limited to fixed-size character sets unless adapted.
- Neither approach directly addresses streaming input scenarios.
In Part 2, we'll cover:
- Approach 3 – Using HashMap
- Approach 4 – Using Java Streams
- Approach 5 – Using BitSet / Boolean Array (ASCII Optimization)
- Unicode Considerations
- Comparison of All Approaches
- Common Interview Mistakes
- Edge Cases
- Interview Follow-up Questions
- Related Problems
- Key Takeaways
- Frequently Asked Interview Questions
- Interview Tips
Approach 3 — Using HashMap
A HashMap can also be used to solve this problem.
Instead of storing only visited characters, we store the frequency of every character.
During traversal,
as soon as a character frequency becomes
2
it is the first repeating character.
Why HashMap?
Unlike a HashSet,
a HashMap stores both
- Character
- Frequency
Example
banana
Frequency Updates
b → 1
a → 1
n → 1
a → 2
Return a
Algorithm
- Create a HashMap.
- Traverse the string.
- Increment frequency.
- If frequency becomes two, return the character.
- Otherwise continue.
Java Program
import java.util.HashMap;
import java.util.Map;
public class FirstRepeatingHashMap {
public static char firstRepeating(String text) {
Map<Character, Integer> map =
new HashMap<>();
for (char ch : text.toCharArray()) {
map.put(ch,
map.getOrDefault(ch, 0) + 1);
if (map.get(ch) == 2) {
return ch;
}
}
return '\0';
}
public static void main(String[] args) {
System.out.println(
firstRepeating("programming"));
System.out.println(
firstRepeating("banana"));
}
}
Output
r
a
Advantages
- Easy implementation.
- Stores character frequencies.
- Useful when frequencies are required later.
Drawbacks
- Uses more memory than HashSet.
- Slightly more operations due to frequency updates.
Approach 4 — Using Java Streams
Java Streams provide a functional approach.
Although this solution is elegant,
traditional loops are generally preferred in coding interviews due to simplicity and lower overhead.
Algorithm
- Traverse the string.
- Maintain a HashSet.
- Filter repeated characters.
- Return the first repeated one.
Java Program
import java.util.HashSet;
import java.util.Set;
public class FirstRepeatingStreams {
public static Character firstRepeating(String text) {
Set<Character> visited =
new HashSet<>();
return text.chars()
.mapToObj(ch -> (char) ch)
.filter(ch -> !visited.add(ch))
.findFirst()
.orElse(null);
}
public static void main(String[] args) {
System.out.println(
firstRepeating("programming"));
}
}
Output
r
Advantages
- Modern Java style.
- Concise implementation.
- Demonstrates Java 8 Streams.
Drawbacks
- Harder for beginners.
- Additional Stream overhead.
- Rarely preferred during whiteboard interviews.
Approach 5 — Using Boolean Array (ASCII Optimization)
If the input contains only ASCII characters,
a boolean array is extremely efficient.
Instead of HashSet,
we directly use character values as array indexes.
Visualization
Input
abccba
Visited Array
a → true
b → true
c → true
c
↓
Already true
↓
Return c
Algorithm
- Create a boolean array.
- Traverse characters.
- If already visited, return.
- Otherwise mark visited.
Java Program
public class FirstRepeatingBooleanArray {
public static char firstRepeating(String text) {
boolean[] visited =
new boolean[256];
for (char ch : text.toCharArray()) {
if (visited[ch]) {
return ch;
}
visited[ch] = true;
}
return '\0';
}
public static void main(String[] args) {
System.out.println(
firstRepeating("banana"));
System.out.println(
firstRepeating("programming"));
}
}
Output
a
r
Advantages
- Extremely fast.
- Constant-time lookup.
- Very low overhead.
Drawbacks
- Works only for fixed-size character sets (ASCII example).
- Not suitable for arbitrary Unicode without modifications.
Unicode Considerations
Java uses UTF-16 for String.
Examples
こんにちは
नमस्ते
😊😊😂
For general Java strings,
the HashSet and HashMap approaches work well.
For supplementary Unicode characters (such as many emoji), iterate over Unicode code points instead of individual char values.
Edge Cases
| Input | Expected Output |
|---|---|
"" |
No Repeating Character |
"a" |
No Repeating Character |
"aa" |
a |
"abcdef" |
No Repeating Character |
"aabbcc" |
a |
null |
Handle appropriately based on application requirements |
Time & Space Complexity
| Approach | Time | Extra Space |
|---|---|---|
| HashSet | O(n) | O(k) |
| Frequency Array | O(n) | O(1)* |
| HashMap | O(n) | O(k) |
| Java Streams | O(n) | O(k) |
| Boolean Array | O(n) | O(1)* |
Where
- n = Length of the string
- k = Number of distinct characters
*For a fixed ASCII character set, the array size is constant.
Comparison of All Approaches
| Approach | Interview Friendly | Performance | Best Use Case |
|---|---|---|---|
| HashSet | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | Most interview questions |
| Frequency Array | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ASCII-only strings |
| HashMap | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | Need character frequencies |
| Java Streams | ⭐⭐⭐⭐ | ⭐⭐⭐ | Modern Java applications |
| Boolean Array | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | Maximum performance for ASCII |
Common Interview Mistakes
Mistake 1
Confusing first repeating with most frequent.
Example
banana
First repeating
a
Most frequent
a
These are not always the same.
Example
programming
First repeating
r
Most frequent
g
Mistake 2
Returning the first duplicate after counting frequencies.
The interview asks for the first character that repeats during traversal, not the first character with frequency greater than one after processing the entire string.
Mistake 3
Using nested loops.
for(...)
for(...)
This results in
O(n²)
A HashSet provides an
O(n)
solution.
Mistake 4
Ignoring empty strings.
Always handle
""
and
null
appropriately.
Mistake 5
Using an ASCII array for Unicode input.
Prefer HashSet or HashMap when the input is not limited to ASCII.
Interview Follow-up Questions
Q1. Why is HashSet preferred for this problem?
Q2. Can this be solved without using collections?
Q3. What is the fastest solution for ASCII characters?
Q4. How would you support Unicode?
Q5. Can you solve this using Java Streams?
Q6. What is the time complexity?
Q7. What if the input is a stream of characters?
Q8. Which approach uses the least memory?
Q9. Can multiple repeating characters exist?
Q10. How would you process a file larger than memory?
Related Problems
- First Non-Repeating Character
- Count Character Frequency
- Remove Duplicate Characters
- Longest Substring Without Repeating Characters
- Valid Anagram
- Group Anagrams
- String Compression
- Find Duplicate Characters
Key Takeaways
- The First Repeating Character is the first character whose second occurrence is encountered during left-to-right traversal.
- HashSet is the preferred interview solution because it is simple, efficient, and runs in O(n) time.
- Frequency Array and Boolean Array provide the fastest implementations for fixed-size character sets like ASCII.
- HashMap is useful when character frequencies are also needed.
- Java Streams offer a concise functional approach but are less common in coding interviews.
Frequently Asked Interview Questions
Q1. Which solution is best for interviews?
The HashSet approach is the best choice because it is easy to explain, requires only one traversal, and has O(n) time complexity.
Q2. Why use HashSet instead of HashMap?
A HashSet is sufficient when you only need to know whether a character has already been seen.
Use a HashMap when frequency counts are required.
Q3. Which approach is the fastest?
For ASCII input,
the Boolean Array or Frequency Array approach is typically the fastest because array indexing is constant time.
Q4. Can this problem be solved in one pass?
Yes.
The HashSet, HashMap, Boolean Array, and Frequency Array approaches all solve the problem in a single traversal.
Q5. Does this work for Unicode?
Yes.
The HashSet and HashMap approaches work well for Java strings.
For supplementary Unicode characters (such as many emoji), iterate using Unicode code points instead of individual char values.
Interview Tip
If an interviewer asks:
"Find the first repeating character in a string."
Start with the HashSet approach because it is the most intuitive and interview-friendly solution.
Then discuss additional approaches:
- HashSet (recommended)
- Frequency Array (ASCII optimization)
- HashMap (frequency counting)
- Java Streams (functional programming)
- Boolean Array (highest performance for ASCII)
Before coding, clarify requirements such as:
- Should uppercase and lowercase letters be treated as different characters?
- Can the input contain Unicode characters?
- What should be returned if no repeating character exists?
- Is the input limited to ASCII?
Explaining these trade-offs demonstrates strong Java fundamentals, problem-solving ability, and interview readiness.