Member-only story
π§βπ» LeetCode 2351 β Finding the First Letter to Appear Twice π₯
In coding, handling strings efficiently is crucial, especially when working with algorithms to identify patterns. Today, weβll explore LeetCode Problem 2351, βFirst Letter to Appear Twice.β This blog post dives into several approaches to solve this problem efficiently in Java, with detailed explanations for each solution.
π€ Problem Statement
Level π₯ Easy
Given a string s
containing only lowercase letters, find the first character that appears at least twice. You are guaranteed that thereβs at least one such character in s
.
Example:
- Input:
"abccbaacz"
- Output:
'c'
- Input:
"abcdd"
- Output:
'd'
π‘ Solution
β Approach 1: Using a HashSet to Track Seen Characters
The initial solution uses a HashSet
to store each character as we encounter it. The goal is to check if a character has already been seen. If yes, thatβs our answer since itβs the first one appearing twice. If not, we add it to our HashSet
.
import java.util.HashSet;
public class Solution {
public char repeatedCharacter(String s)β¦