How to find the first repeated character in a string with JavaScript

3 Answers

0 votes
/**
 * Finds the first repeated character in a string.
 *
 * Examples:
 *   "abca"         -> "a"
 *   "abcbd"        -> "b"
 *   "abcde"        -> null
 *   "abcdxypcbop"  -> "c"
 *
 * Time Complexity: O(n)
 * Space Complexity: O(n)
 *
 * @param {string} str - The input string.
 * @returns {string|null} The first repeated character, or null if none exists.
 */
function findFirstRepeatedCharacter(str) {
    if (!str) {
        return null;
    }

    const seen = new Set();

    for (const ch of str) {
        // If the character is already in the set,
        // we've found the first repeated character.
        if (seen.has(ch)) {
            return ch;
        }

        seen.add(ch);
    }

    // No repeated character found.
    return null;
}

// Test cases
console.log(findFirstRepeatedCharacter("abca"));         
console.log(findFirstRepeatedCharacter("abcbd"));        
console.log(findFirstRepeatedCharacter("abcde"));        
console.log(findFirstRepeatedCharacter("abcdxypcbop"));  
  
    
    
/*
run:
    
a
b
null
c
   
*/

 



answered Sep 5, 2022 by avibootz
edited 6 days ago by avibootz
0 votes
function get_first_repeated_character(s) {
    const len = s.length;
 
    for (let i = 0; i < len; i++) {
         for (let j = 0; j < i; j++) {
            if (s[i] === s[j]) {
                return s[i];
            }
        }
    }
 
    return "-1";
}
 
const s = "abcdxypcbop"; 
 
console.log(get_first_repeated_character(s));
 
 
    
/*
run:
    
c
    
*/

 



answered 6 days ago by avibootz
0 votes
function findFirstRepeatedCharacter(input) {
    const seen = new Map();

    for (const ch of input) {
        if (seen.has(ch)) {
            return ch;
        }

        seen.set(ch, true);
    }

    return null;
}

// Test cases
console.log(findFirstRepeatedCharacter("abca"));         
console.log(findFirstRepeatedCharacter("abcbd"));        
console.log(findFirstRepeatedCharacter("abcde"));        
console.log(findFirstRepeatedCharacter("abcdxypcbop"));  
  
    
    
/*
run:
    
a
b
null
c
   
*/

 



answered 6 days ago by avibootz
...