Class President (Hash)

Problem

A, B, C, D, and E candidates registered as candidates to select the class president.
The ballot is written with the symbol (alphabetically) of the candidate chosen by the students in the class, and the teacher announces the symbol.
After the teacher’s presentation, write a program that prints out which preference candidate became the class president. It is assumed that the result of the vote is to ensure that one class president is elected.

input

  • The first line gives the number of students in the class N (5<=N<=50)
  • In the second line, each candidate’s symbol written on the N ballots is entered as a string in the order announced by the teacher
15

BACBACCACCBDEDE

output

Prints the selected symbol as the class president.

C

Solution

O(2n): Using for loop and sort

function solution(s) {
	let answer, temp;
	let i = 0,
		count = 0,
		save = 0;

	const sorted = s.split('').sort().join('');

	for (i; i < s.length; i++) {
		if (temp !== sorted[i]) {
			temp = sorted[i];
			save = count;
			count = 1;
		} else {
			count++;

			if (count > save) {
				answer = temp;
			}
		}
	}

	return answer;
}

Use Map().set() & Map().get()

function solution(s) {
	let answer;
	let sH = new Map();

	for (let x of s) {
		if (sH.has(x)) {
			sH.set(x, sH.get(x) + 1);
		} else {
			sH.set(x, 1);
		}
	}

	let max = Number.MIN_SAFE_INTEGER;
	for (let [key, val] of sH) {
		if (val > max) {
			max = val;
			answer = key;
		}
	}

	return answer;
}