Given an array array, find the majority element that appears more than half times in the array. If no majority exists, return -1.
Create an empty list or dictionary to keep track of how many times each item appears in the original list. Go through each item in the original list:
Go through the count list, if the count of any item is greater than half the size of the original list, that item is the majority element.
ls = [2, 2, 2, 4, 5, 2, 7, 2, 9] output = {} for item in ls: if item in output: output[item] = output[item] + 1 else: output[item] = 1 half = len(ls) // 2 result = -1 for item in output: if output[item] >= half: result = item break print(result)
const list = [2, 2, 2, 4, 5, 2, 7, 2, 9]; const counts = {}; for (let item of list) { if (!counts[item]) { counts[item] = 1; } else { counts[item] = counts[item] + 1; } } const half = Math.floor(list.length / 2); let output = -1; for (let i in counts) { if (counts[i] > half) { output = i; break; } } console.log(output);