germancin
6/1/2018 - 6:40 AM

Remove duplicates using object better than array.

Remove duplicates using object better than array.

function removeDupes(str) {
    const uniqueChars = []
    const chars = {}

    for(let i=0; i < str.length; i++){ // O(n)
        const thisItem = str[i]
        
        // I'm checking if inside of the object Chars there is 
        // the letter with a true value which means that it found 
        // that element into the object so does not fo anything
        // else it add it to the uniqueChars array and also
        // add it into the object to search for it int the loop
        // And I do that because searching trough an object is instantaneous O(1)
        // rather than use includes which lopps trough the whole array

        if(chars[thisItem] === true){ // O(1)
            continue
        }else{
            uniqueChars.push(thisItem)
            chars[thisItem] = true
        }
    }
    return uniqueChars.join('')
}

console.log(
  //removeDupes('abcd'),          // abcd
  removeDupes('aabbccdd'),      // abcd
  //removeDupes('abababcdcdcd'), // abcd

)

// Time:  O(n)
// Space: O(n)