Skip to content

Instantly share code, notes, and snippets.

@hzhu
Last active February 26, 2017 07:46
Show Gist options
  • Select an option

  • Save hzhu/4087a121d39b8b3ed76548671c7016f2 to your computer and use it in GitHub Desktop.

Select an option

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 using a loop to find duplicate touching characters. When we find a set of duplicate touching characters, we can concat all the characters before the dups, and all the characters after the dups, creating a new string. Then we reset our variables to run a new loop, on our newly created string, repeating the steps above.

Solution Code

function reduce_dups(str) {
  let prev = str[0]

  for (let i = 1; i < str.length; i++) {
    if (str[i] === prev) {
      let before_dups = str.slice(0, i - 1)
      let after_dups = str.slice(i + 1, str.length)

      str = before_dups + after_dups
      i = -1
      prev = undefined
    } else {
      prev = str[i]
    }
  }

  return str
}

reduce_dups('abba') // ''
reduce_dups('aab') // 'b'
reduce_dups('aba') // 'aba'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment