Skip to content

Instantly share code, notes, and snippets.

@hzhu
Last active February 26, 2017 07:46
Show Gist options
  • Save hzhu/4087a121d39b8b3ed76548671c7016f2 to your computer and use it in GitHub Desktop.
Save hzhu/4087a121d39b8b3ed76548671c7016f2 to your computer and use it in GitHub Desktop.
Remove Neighboring Duplicates

Problem

Write a function that accepts a string argument and removes duplicate characters that are neighbors. If the new string also has duplicate neighbors, those should be removed also.

reduce_dups('abb') => "a"
reduce_dups('abba') => ""
reduce_dups('aba') => "aba"

Analysis of Problem

We can solve this problem by for looping through the string starting at index 1. Then compare the current character str[i], to the previous character prev.

When we find a set of duplicate touching characters (str[i] === prev), we can concat all the characters before the dups, and all the characters after the dups, creating a new string.

Finally, we reset our variables: str, i, prev. This allows our program to run a new loop, on our newly created string, repeating the steps above.

Solution Code

function remove_dups(str) {
  let prev = str[0];
  for (let i = 1; i < str.length; i++) {
    if (str[i] === prev) {
      str = str.slice(0, i - 1) + str.slice(i + 1, str.length);
      prev = str[0];
      i = 0;
    } else {
      prev = str[i];
    }
  }
  return str;
}

remove_dups('abba') // ''
remove_dups('aab') // 'b'
remove_dups('aba') // 'aba'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment