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

2 Answers

0 votes
function get_last_character_repeated(s) { 
    var len = s.length;
    var ch_idx = -1;
            
    for (var i = 0; i < len; i++) { 
       for (var j = i + 1; j < len; j++) { 
            if (s[i] === s[j]) { 
                ch_idx = i;
                break;
            } 
        } 
    } 

    return ch_idx; 
}  
 
s = "abcdxypcbadom"; 
         
i = get_last_character_repeated(s); 
        
if (i === -1) {
    document.write("Not found"); 
}
else {
     document.write(s[i]);
}


     
/*
run:
 
d
          
*/
  

 



answered Jan 26, 2020 by avibootz
edited 5 days ago by avibootz
0 votes
/**
 * Finds the last repeated character in a string.
 *
 * Examples:
 *   "abca"          -> "a"
 *   "abcbd"         -> "b"
 *   "abcde"         -> null
 *   "abcdxypcbop"   -> "p"
 *   "abcdxypcbadom" -> "d"
 *
 * Time Complexity: O(n)
 * Space Complexity: O(k)
 *
 * @param {string} str - The input string.
 * @returns {string|null} The last repeated character,
 *                        or null if none exists.
 */
function findLastRepeatedCharacter(str) {
    if (!str) {
        return null;
    }

    // Count occurrences of each character.
    const frequency = new Map();

    for (const ch of str) {
        frequency.set(ch, (frequency.get(ch) || 0) + 1);
    }

    // Traverse from right to left.
    for (let i = str.length - 1; i >= 0; i--) {
        const ch = str[i];

        if (frequency.get(ch) > 1) {
            return ch;
        }
    }

    // No repeated character found.
    return null;
}

// Test cases
console.log(findLastRepeatedCharacter("abca"));          
console.log(findLastRepeatedCharacter("abcbd"));         

const result = findLastRepeatedCharacter("abcde");
console.log(result ?? " ");                              

console.log(findLastRepeatedCharacter("abcdxypcbop"));   
console.log(findLastRepeatedCharacter("abcdxypcbadom"));


/*
run:

a
b
 
p
d

*/

 



answered 5 days ago by avibootz
...