germancin
6/1/2018 - 6:07 AM

This even being a n^2 it uses a very interesting way of solving it with array and includes

This even being a n^2 it uses a very interesting way of solving it with array and includes

function removeDupes(str) {
    const uniqueChars = []

    for(let i=0; i < str.length; i++){ // O(n)
        const thisItem = str[i]
        
        // I'm checking if there is thisItem into uniqueChars
        // if so dont do anything else will add it into uniqueChars
        // the problem with this is that includes is O(n)
        // in addition the outter loop is O(n) so we get O(n^2)
        if(uniqueChars.includes(thisItem)){
            continue
        }else{
          uniqueChars.push(thisItem)
        }
    }
    return uniqueChars.join('')
}

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

)

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