Find the maximum frequency of an element in a given Array

Problem outline

This is the solution I have come up with but I’m unsure whether this is the best possible solution as far as Big (O) notation is concerned…

def solution(A):
    B = [0, 0, 0, 0, 0]
    for i in range (len(A)):
        if A[i] == "Cardiology":
            B[0] += 1
        elif A[i] == "Neurology":
            B[1] += 1
        elif A[i] == "Orthopaedics":
            B[2] += 1
        elif A[i] == "Gynaecology":
            B[3] += 1
        elif A[i] == "Oncology":
            B[4] += 1
    max_patients = max(B)
    return max_patients

>Solution :

You can solve this very easily with collections.Counter. You don’t want or need dictionaries, side lists or anything else extra. Everything you add is another thing to break. Keep it as simple as possible.

from collections import Counter

def solution(A):
    return max(Counter(A).values())

I only stuck this in a function to give you context. There’s no reason for this to be a function. Wrapping this in a function is basically just giving the operation an alias. Unfortunately, your alias doesn’t give any indication of what you aliased. It’s better to just put the one line in place.

Leave a Reply