Skip to content

Instantly share code, notes, and snippets.

@treyhunner
Created February 20, 2013 22:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treyhunner/5000243 to your computer and use it in GitHub Desktop.
Save treyhunner/5000243 to your computer and use it in GitHub Desktop.
Programming interview practice of the week (Feb. 20, 2013)
"""
Programming interview practice of the week (2013-02-20)
Problem of the week - Singletons considered okay
1. Write a simple singleton class in your favorite programming language with an example usage.
2. Solve the Sorted array binary search problem:
Given a sorted array of integers array and an integer key, return the index of the first instance of key in the array. If key is not present in array, you should return -1.
For example, given the array [-10, -2, 1, 5, 5, 8, 20] and key 5, you should return the index 3.
Your solution should be a binary search, that is, it should run in O(log n) time.
"""
# Problem 1
class Singleton(object):
__instance = None
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls.__instance
s = Singleton()
t = Singleton()
assert s is t
# Problem 2
def find(array, key, min_index=0, max_index=None):
if max_index is None:
max_index = len(array)
length = max_index - min_index
mid = length / 2 + min_index
if length == 0:
return -1
elif length == 1:
return mid if array[mid] == key else -1
elif array[mid] < key:
return find(array, key, mid, max_index)
else:
lower = find(array, key, min_index, mid)
return lower if lower != -1 or array[mid] != key else mid
assert find([-10, -2, 1, 5, 5, 8, 20], 5) == 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment