Skip to content

Instantly share code, notes, and snippets.

@sefields
Created November 14, 2017 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sefields/6c10518c7c6c885471596093f3882464 to your computer and use it in GitHub Desktop.
Save sefields/6c10518c7c6c885471596093f3882464 to your computer and use it in GitHub Desktop.
Reddit DailyProgrammer Solution 2017-11-13
// Prompt: https://www.reddit.com/r/dailyprogrammer/comments/7cnqtw/20171113_challenge_340_easy_first_recurring/
// Solution 1:
// This solution is 0-indexed.
// In the worst case scenario, this creates and checks a number
// of substrings equal to the length of inputStr. Not very efficient.
function firstRecurring(inputStr) {
var charArr = inputStr.split('');
for (var i = 0; i < charArr.length; i++) {
var mySubStr = inputStr.slice(i + 1, inputStr.length);
if (mySubStr.includes(charArr[i])) {
console.log("Duplicate char '" + charArr[i] + "' found at index " + (mySubStr.indexOf(charArr[i]) + i + 1));
return;
}
}
console.log("No duplicate characters found.");
}
// Solution 2: Inspired by pkoepke's solution.
// This solution is 0-indexed.
// O(n) time, where n is the length of inputStr.
function newFirstRecurring(inputStr) {
var charArr = inputStr.split('');
var isCharPresent = {}; // empty object
for (var i = 0; i < charArr.length; i++) {
if (isCharPresent[charArr[i]] === undefined) {
isCharPresent[charArr[i]] = true;
}
else {
var mySubStr = inputStr.slice(i + 1, inputStr.length); // Slicing off the first occurrence of the char...
console.log("Duplicate char '" + charArr[i] + "' found at index " + (mySubStr.indexOf(charArr[i]) + i + 1)); //...So that we can call indexOf
return;
}
}
console.log("No duplicate characters found.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment