Smeliott
Smeliott

Reputation: 47

Trouble understanding .indexOf in this code problem

I recently completed this Leetcode assessment for an open-book interview. Luckily I was able to Google for help, and passed the assessment. I'm having trouble understanding what exactly is happening on the line declared below. I'd love it if one of your smartypants could help me understand it better!

Thank you!

The problem:

Have the function NonrepeatingCharacter(str) take the str parameter being passed, which will contain only alphabetic characters and spaces, and return the first non-repeating character. For example: if str is "agettkgaeee" then your program should return k. The string will always contain at least one character and there will always be at least one non-repeating character.

Once your function is working, take the final output string and combine it with your ChallengeToken, both in reverse order and separated by a colon.

Your ChallengeToken: iuhocl0dab7

function SearchingChallenge(str) { 
 
  // global token variable
  let token = "iuhocl0dab7"

  // turn str into array with .split()
  let arrayToken = token.split('')

  // reverse token
  let reverseArrayToken = arrayToken.reverse();
 
  // loop over str 
  for (var i = 0; i < str.length; i++) {

    // c returns each letter of the string we pass through
    let c = str.charAt(i);

    ***--------------WHAT IS THIS LINE DOING?-------------***
    if (str.indexOf(c) == i && str.indexOf(c, i + 1) == -1) {

      // create variable, setting it to array with first repeating character in it
      let arrayChar = c.split()

      // push colon to array
      arrayChar.push(':')

      // push reversed token to array
      arrayChar.push(reverseArrayToken)

      // flatten array with .flat() as the nested array is only one level deep
      let flattenedArray = arrayChar.flat()

      // turns elements of array back to string
      let joinedArray = flattenedArray.join('')

      return joinedArray;
    }
  }
 
};

Upvotes: 0

Views: 303

Answers (1)

Pointy
Pointy

Reputation: 413682

What I'd do is:

  1. Reduce the string to an object, where the keys are the letters and the values are objects containing counts of occurrences and initial index in the string
  2. Sort the .values() of that object in order of minimum count and minimum index
  3. Use the first entry in the result of the sort to return the character

So something like

function firstUnique(str) {
  const counts = Array.from(str).reduce((acc, c, i) => {
    (acc[c] || (acc[c] = { c, count: 0, index: i })).count++;
    return acc;
  }, {});
  return Object.values(counts).sort((c1, c2) =>
    c1.count - c2.count || c1.index - c2.index
  )[0].c;
}

Upvotes: 1

Related Questions