Member-only story

πŸ§‘β€πŸ’» LeetCode 2351 β€” Finding the First Letter to Appear Twice πŸ”₯

Leo N
4 min readNov 12, 2024

--

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)…

--

--

Leo N
Leo N

Written by Leo N

πŸ‡»πŸ‡³ πŸ‡ΈπŸ‡¬ πŸ‡²πŸ‡Ύ πŸ‡¦πŸ‡Ί πŸ‡ΉπŸ‡­ Engineer @ GXS Bank, Singapore | MSc πŸŽ“ | Technical Writer . https://github.com/nphausg

No responses yet