W
W
WarriorKodeK2018-02-17 15:01:03
JavaScript
WarriorKodeK, 2018-02-17 15:01:03

How to return the last element?

Hello. I'm solving algorithmic problems and I have a question.
Task:
Given a string, and it is necessary to find the most repeated character in it.
That is: "abcccss" => "c";
My implementation:

const maxChar = str => {
  const charObj = {};
  let max = 0;
  let maxChar = '';

  for (let char of str) {
    if (charObj[char]) {
      charObj[char]++;
    } else {
      charObj[char] = 1;
    }
  }

  for (let char in charObj) {
    if (charObj[char] > max) {
      max = charObj[char];
      maxChar = char;
    }
  }
  console.log(charObj);
  return maxChar;
};

maxChar('abccccsddasdadwqwf') => "c" // а должно "d"

But if the word has >2 repetitions. characters, then you need to return the last one, but for me it returns the first one. How to implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bogdan, 2018-02-17
@WarriorKodeK

Algorithmically, it is possible to calculate it in one pass of the loop

const maxChar = str => {
  const charObj = {};
  let max = {char:'', count:''};
  let maxChar = '';

  for (let char of str) {

    if (charObj[char]) {
      charObj[char]++;
    } else {
      charObj[char] = 1;
    }

    if ( charObj[char] >= max.count ) {
      max.char = char
      max.count = charObj[char]
    }

  }

  return max.char;
};

console.log( maxChar('abccccsddasdadwqwf'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question