Skip to content

Instantly share code, notes, and snippets.

@taravancil
Last active October 4, 2016 23:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taravancil/a29d3788c9b53cae3863c8f0f56d3384 to your computer and use it in GitHub Desktop.
Save taravancil/a29d3788c9b53cae3863c8f0f56d3384 to your computer and use it in GitHub Desktop.
Approaches for finding the most common integer in an array.
# Constraints: an array of size n of integers in the range 0 to k-1, where k is a positive integer and k <= n
test = [0, 1, 1, 1, 3, 17, 5, 3, 2, 1, 9] # k = 10, n = 11
get_common(test, 10)
def get_common(A, k):
"""Return the most popular integer in an array. O(n) time, O(k) space."""
# Create a lookup array with length k to track the occurrence of each possible member.
# O(k) space
lookup = [0] * k
# For each element in A, increment the count in the lookup array at position `el`
# O(n)
for el in A:
lookup[el] += 1
# Iterate through the lookup array to find the max count
max_count = 0 # O(1) space
result = 0
# O(k)
for i range(0, k):
if lookup[i] > max_count:
max_count = lookup[i]
result = i
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment