Most Common Elements in an Array using Swift - iOS Coding Challenge

Complexity : O(n)

Let's Code :

//: Playground - noun: a place where people can play

import Foundation
import UIKit

var elementArray : [String] = ["one","two","three","four","five","two","five","two","one","two","five","three","three","four","one","four","three","five"]

func getMostCommonElementFromArray(array:[String]) -> [String] {
    var mostOccuredElements : [String] = []
    var elementDict : [String:Int] = [:]
    for item in array {
        if let count = elementDict[item] {
            elementDict[item] = count + 1
        }else{
            elementDict[item] = 1
        }
    }
    let highestVal = elementDict.values.max()
    for (element,_) in elementDict {
        if elementDict[element] == highestVal {
            mostOccuredElements.append(element)
        }
    }
    return mostOccuredElements
}

getMostCommonElementFromArray(array: elementArray)

Result 

Comments

Popular posts from this blog

Best coding practice and structure for redux saga with react hooks | Separate watcher and worker saga | React clean code

How to use redux with React Hooks - Creating TodoList

Setting up Redux Devtools for React applications