JSFiddle - React, Tailwind, and code Playground

by kkdaily

HTML

<h3>
(CTCI 1.1) Implement an algorithm to determine if a string has all unique characters. what if you cannot use additional data structures?
</h3>

<div id="message"></div>

CSS

#message {
  padding: 10px;
}

.success {
  background-color: lightgreen;
}

.failure {
  background-color: pink;
}

JavaScript

// ex: 'cat'
// 1. split str into seperate chars str.split = ['c', 'a', 't']
// 2. create a hash table to store seen chars (var seenChars = {})
// 3. loop through chars array
// 4. check if current char already exists in hash table (seenChars[currentChar])
// 5. 	if it already exists, exit loop and return false for the function
// 6. 	else, add the char as a new key in the hash table (seenChars[currentChar] = 1)
// 7. after the end of the loop return true
hasUniqueChars = (str) => {
	if (!str.length) {
  	return new Error('string must contain at least 1 character')
  }
	const chars = str.split('')
  const seenChars = {}
  let hasUniqueChars = true
  for (let i = 0; i < chars.length; i++) {
  	if (seenChars[chars[i]]) {
    	hasUniqueChars = false
    	break
    } else {
    	seenChars[chars[i]] = 1
    }
  }
  return hasUniqueChars
}

// TEST CASES
runTests = (algo) => {
	tests = {
    'cat': true,
    'catto': false,
    'a': true,
    'ooo': false
  }
  
  const failedTests = []
  Object.keys(tests).forEach((key) => {
    if (algo(key) !== tests[key]) {
      failedTests.push(key)
    }
  })
  const messageEl = document.getElementById('message')
  if (!failedTests.length) {
    messageEl.innerText = 'all tests passed!'
    messageEl.classList.add('success')
  } else {
    const failedTestNames = failedTests.join(', ')
    messageEl.innerText = `the following test cases failed: ${failedTestNames}`
    messageEl.classList.add('failure')
  }
}

runTests(hasUniqueChars)