CSInterviewing
Problems
Register
Login
Problems
Register
Login
menu
First Duplicate Character
string
hashtable
# First Duplicate Character ## Difficulty Easy ## Tags `string`, `hash table` ## Problem Statement Given a string, find the first character that appears more than once. "First" is defined by the position of the **second occurrence** - return the character whose second occurrence appears earliest. If no character is duplicated, return an empty string or null. ## Constraints - String consists of lowercase English letters (a-z). - 0 ≤ s.length ≤ 10⁵ - Time complexity: O(N) - Space complexity: O(1) (alphabet size is fixed at 26) ## Signatures ### Python ```python def first_duplicate_char(s: str) -> Optional[str]: pass ``` ### Java ```java public class Solution { public Object first_duplicate_char(String s) { return null; } } ``` ### Csharp ```csharp public class Solution { public Object first_duplicate_char(string s) { throw new NotImplementedException(); } } ``` ### Cpp ```cpp class Solution { public: Object first_duplicate_char(string s) { } }; ``` ### C ```c Object first_duplicate_char(char* s) { } ``` ### Ruby ```ruby def first_duplicate_char(s) end ``` ### Perl ```perl sub first_duplicate_char { my ($self, @args) = @_; } ``` ### Scala ```scala object Solution { def first_duplicate_char(s: String): Object = { } } ``` ### Haskell ```haskell first_duplicate_char :: ... -> ... first_duplicate_char args = undefined ``` ### Clojure ```clojure (defn first_duplicate_char [s] ) ``` ### Scheme ```scheme (define (first_duplicate_char s) ) ``` ## Examples ### Example 1 **Input:** ``` s = "abca" ``` **Output:** ``` "a" ``` **Explanation:** 'a' at index 3 is the first repeated character (first second occurrence). ### Example 2 **Input:** ``` s = "abcba" ``` **Output:** ``` "b" ``` **Explanation:** 'b' repeats at index 3, 'a' repeats at index 4. Since 3 < 4, 'b' is the answer. ### Example 3 **Input:** ``` s = "abcdef" ``` **Output:** ``` None # or "" ``` **Explanation:** No duplicates. ### Example 4 **Input:** ``` s = "aa" ``` **Output:** ``` "a" ``` ## Hints 1. Use a HashSet to track characters seen so far. 2. Iterate through the string from left to right. 3. If the current character is already in the set, return it immediately. 4. Otherwise, add it to the set.
Login required
Please log in to view the solution editor and submit code.
Login
Register