[Question]: Given an integer array of size n
, find all elements that appear more than ⌊ n/3 ⌋
times.
Example: Input = [11, 33, 33, 11, 33, 11]; Output:–// [11,33]
Approach: By using dictionary
- Create an empty dictionary and assign the numbers count
- Create another loop and filter elements which are greater than the n/3
// TC: O(2N)
// SC: O(2N)
func majorityElementNBy3(_ nums: [Int]) -> [Int] {
if nums.isEmpty { return [] }
var frequencyDictionary: Dictionary<Int,Int> = [:], result: [Int] = []
for num in nums {
frequencyDictionary[num, default: 0] += 1
}
for (key,val) in frequencyDictionary where val > (nums.count/3) {
result.append(key)
}
return result
}
let majority3Input = [11, 33, 33, 11, 33, 11];
let majority3Output = majorityElementNBy3(majority3Input);
// print("The majority elements are: ", majority3Output); // 11, 33