Skip to main content
Bumped by Community user
Bumped by Community user
edited tags; edited title
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

Optimizing Form a simple solutionstring consisting of the common letters that appear in two input strings

Source Link
SakoBu
  • 157
  • 2

Optimizing a simple solution

The idea is to write a function that takes two strings and returns a new string that repeats in the previous two: examples:

'ABBA' & 'AOHB' => 'AB'
'cohs' & 'ohba' => 'oh'

A brute force solution would be nested for loops like so:

const x = 'ABCD'
const y = 'AHOB'

function subStr(str1, str2) {
  let final = ''

  for (let i = 0; i < str1.length; i++) {
    for (let j = 0; j < str2.length; j++) {
      if (str1[i] === str2[j]) {
        final += str1[i]
      }
    }
  }

  return final
}



console.log(subStr(x, y)) // => AB