Академический Документы
Профессиональный Документы
Культура Документы
www.firecode.io
Count the Leaves!
Trees Queues
Write a function to find the total number of leaf nodes in a binary tree. A node is described as a leaf node if it
doesn't have any children. If there are no leaf nodes, return 0 .
Example:
1
/\
2 3
/\/\
4 56 7
/\
8 9
==> no. of leaves = 5
Your solution
class BinaryTree:
def __init__(self, root_node = None):
self.root = root_node
def number_of_leaves(self,root):
if root == None:
return 0
if root.left_child == None and root.right_child == None:
return 1
def number_of_leaves(self,root):
if root is None:
return 0
elif root.left_child is None and root.right_child is None:
return 1
else:
return self.number_of_leaves(root.left_child) + self.number_of_leaves(root.righ
t_child)
Comments
Dylan Richardson - 07 Nov, 2016
ooh yours was a tad cleaner, stinky little man.
1
1
2
Reverse a Singly Linked List
Linked Lists
Example:
1->2->3 ==> 3->2->1
Your solution
class SinglyLinkedList:
#constructor
def __init__(self):
self.head = None
def reverse(self):
current = self.head
prev_node = None
def reverse(self):
p = self.head
self.head = None
while p is not None:
temp = p.getNext()
p.setNext(self.head)
self.head = p
p = temp
Comments
Daniel - 07 Aug, 2017
cool
0
Numbers and Ranges ...
Arrays Sorting Algorithms Search Algorithms
Given a sorted list and an input number as inputs, write a function to return a Range object, consisting of
the indices of the first and last occurrences of the input number in the list. Check out the Use Me section to
examine the structure of the Range class.
Note: The List can have duplicate numbers. The indices within the Range object should be zero based.
Examples:
Your solution
def find_range(input_list,input_number):
for i in range(len(input_list)):
if input_list[i] == input_number:
first = i
last = i
while input_list[last+1] == input_number:
last+=1
break
return Range(first,last)
return left
Comments
Madhu - 21 Jan, 2018
Great Man, what a logic and crisp code.
0
1
0
Inserting a Node at the End of
a Singly Linked List
Linked Lists
Examples:
LinkedList: 1->2 , Head = 1
Your solution
class SinglyLinkedList:
#constructor
def __init__(self):
self.head = None
if self.head is None:
self.setHead(new_node)
else:
last_node = self.head
while last_node.getNext() != None:
last_node = last_node.getNext()
last_node.setNext(new_node)
new_node.setData(data)
Top voted solution
class SinglyLinkedList:
#constructor
def __init__(self):
self.head = None
if self.head is None:
self.head = newNode
else:
curr = self.head
while curr.getNext():
curr = curr.getNext()
curr.setNext(newNode)
Better Fibonacci
Numbers
The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found
by adding up the two numbers before it.
Your goal is to write an optimal method - better_fibonacci that returns the nth Fibonacci number in the
sequence. n is 0 indexed, which means that in the sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... , n == 0 should
return 0 and n == 3 should return 2. Your method should exhibit a runtime complexity of O(n) and use
constant O(1) space. With this implementation, your method should be able to compute larger sequences
where n > 40.
Examples:
better_fibonacci(0) ==> 0
better_fibonacci(1) ==> 1
better_fibonacci(3) ==> 2
Your solution
def better_fibonacci(n):
if n in [0,1]:
return n
n1 = 0
n2 = 1
fib = 0
for i in range(n-1):
fib = n1 + n2
n1 = n2
n2 = fib
return fib
Comments
Kevin - 19 Dec, 2016
Wow, really elegant!
0
0
2
0
Kendy - 13 Nov, 2017
Nice!
0
0
0
0
Insert Stars
Strings Recursion
Example:
insert_star_between_pairs("cac") ==> "cac"
Your solution
def insert_star_between_pairs(a_string):
if a_string == None or a_string == "" or len(a_string) == 1:
return a_string
if a_string[0] == a_string[1]:
return a_string[0] + '*' + insert_star_between_pairs(a_string[1:])
else:
return a_string[0] + insert_star_between_pairs(a_string[1:])
def insert_star_between_pairs(a_string):
# Add your code below this line. Do not modify any other code
if a_string is None or len(a_string) == 1:
return a_string
else:
if a_string[0] == a_string[1]:
return a_string[0] + '*' + insert_star_between_pairs(a_string[1:])
else:
return a_string[0] + insert_star_between_pairs(a_string[1:])
# Add your code above this line. Do not modify any other code
Comments
Cornelius - 03 May, 2016
This would fail if you pass in an empty string, I think. Check for "len(a_string) in line 3 instead.
7
2
6
1
S - 03 Jul, 2017
as others mentioned, string concat is costly and iteration is preferable to recursion in general.
1
Andrew P. - 19 Aug, 2017
I think the question is more of a brain buster, I did not expect to have to do recursion here because
it doesn't make sense to do it. An interviewer might ask you to do a problem you think doesn't make
sense, but they want you to do it a specific way.
0
3
0
Bubble Sort
Arrays Numbers Sorting Algorithms
Examples:
bubble_sort([5, 4, 3]) -> [3, 4, 5]
bubble_sort([]) -> []
Your solution
def bubble_sort(a_list):
for i in range(len(a_list)-1):
for j in range(len(a_list)-1-i):
if a_list[j] > a_list[j+1]:
a_list[j], a_list[j+1] = a_list[j+1], a_list[j]
return a_list
Comments
Kendy - 13 Nov, 2017
That's a cool optimization.
0
Reverse a String
Strings
Write a function that takes in a string and returns the reversed version of the string .
Examples:
Your solution
def reverse_string(a_string):
return a_string[::-1]
def reverse_string(a_string):
return a_string[::-1]
Comments
Scott Lorimor - 26 Sep, 2017
...sigh. this is it.
1
Horizontal Flip
Multi Dimensional Arrays
You are given an m x n 2D image matrix ( List of Lists ) where each integer represents a pixel. Flip it in-place
along its horizontal axis.
Example:
Input image :
11
00
Modified to :
00
11
Your solution
def flip_horizontal_axis(matrix):
matrix.reverse()
def flip_horizontal_axis(matrix):
size = len(matrix)
for i in range(size // 2):
matrix[i], matrix[size - 1 - i] = matrix[size - 1 - i], matrix[i]
Comments
Awokeknowing - 30 Jun, 2016
this haz python zen!
3
Revanth Sakthi - 22 Mar, 2017
clever!
2
0
0
0
0
Mohammad Al-Abbasi - 06 Mar, 2018
Can you explain what happens with two variables on each side of the equals operator?
0
Palindrome Tester
Strings Arrays
A palindrome is a string or sequence of characters that reads the same backward and forward. For example,
"madam" is a palindrome.
Write a function that takes in a string and returns a Boolean -> True if the input string is a palindrome and
False
if it is not. An empty string is considered a palindrome. You also need to account for the space character. For
example, "race car" should return False as read backward it is "rac ecar".
Examples:
is_palindrome("madam") -> True
Your solution
def is_palindrome(input_string):
if input_string == "":
return True
l = len(input_string)
for i in range(l//2):
if input_string[i] != input_string[-(i+1)]:
return False
return True
def is_palindrome(input_string):
return input_string == input_string[::-1]
Comments
John McCreight - 24 Jun, 2017
I like it, very short 'n clean. I'd hope for comments if seeing this in use, but I dig it.
0
0
1
2
Repeated Elements in Array
Arrays
Write a function - duplicate_items to find the redundant or repeated items in a list and return them in sorted
order.
This method should return a list of redundant integers in ascending sorted order (as illustrated below).
Examples:
duplicate_items([1, 3, 4, 2, 1]) => [1]
Your solution
def duplicate_items(list_numbers):
list_numbers.sort()
l = []
for i in range(len(list_numbers)-1):
if list_numbers[i] == list_numbers[i+1]:
l.append(list_numbers[i])
return l
def duplicate_items(list_numbers):
set_list = set(list_numbers)
return [i for i in set_list if list_numbers.count(i)>1]
Comments
Anonymous - 30 Apr, 2017
Easy and efficient ha :D
0
3
1
2
0
George Chinedu Nwankwo - 07 Feb, 2018
I agree that this is an O(n^2) solution
0
0
0
Binary Representation
Recursion
Write a function to compute the binary representation of a positive decimal integer. The method should return
a string .
Example:
dec_to_bin(6) ==> "110"
Your solution
def dec_to_bin(number):
if number < 2:
return str(number)
else:
return dec_to_bin(number/2) + dec_to_bin(number%2)
def dec_to_bin(n):
if n<2: return str(n)
else:
return dec_to_bin(n/2) + dec_to_bin(n%2)
Comments
2
Ackshaey Singh - 15 Sep, 2016
Thanks!
0
0
0
0
8
Jason - 28 Sep, 2017
This is a very nice solution. Would using a while loop be preferred for a larger value for n due to
runtime or memory?
0
Find One Missing Number
from 1 to 10
Arrays
Given an list containing 9 numbers ranging from 1 to 10, write a function to find the missing number. Assume
you have 9 numbers between 1 to 10 and only one number is missing.
Example:
input_list: [1, 2, 4, 5, 6, 7, 8, 9, 10]
find_missing_number(input_list) => 3
Your solution
def find_missing_number(list_numbers):
return 55 - sum(list_numbers)
def find_missing_number(list_numbers):
# Add your code below this line. Do not modify any other code
return sum(list(range(1, 11))) - sum(list_numbers)
# Add your code above this line. Do not modify any other code
Comments
18
David Hayden - 03 Feb, 2017
Nice!
0
0
0
0
0
Gain Chang - 19 May, 2018
beautiful!
0
Fibonacci
Recursion Numbers
The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found
by adding up the two numbers before it.
Write a recursive method fib(n) that returns the nth Fibonacci number. n is 0 indexed, which means that
in the sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... , n == 0 should return 0 and n == 3 should return 2.
Assume n is less than 15.
Even though this problem asks you to use recursion, more efficient ways to solve it include using an Array, or
better still using 3 volatile variables to keep a track of all required values. Check out this blog post to examine
better solutions for this problem.
Examples:
fib(0) ==> 0
fib(1) ==> 1
fib(3) ==> 2
Your solution
def fib(n):
if n in [0,1]:
return n
def fib(n):
if n < 2:
return n
else:
return fib(n-1) + fib(n-2)
Comments
David Hayden - 03 Feb, 2017
Nice! You don't need the second 'else' though. Just the if statement and two return statements.
5
Flip it!
Multi Dimensional Arrays
You are given an m x n 2D image matrix ( List of Lists ) where each integer represents a pixel. Flip it in-place
along its vertical axis.
Example:
Input image :
10
10
Modified to :
01
01
Your solution
def flip_vertical_axis(matrix):
for i in range(len(matrix)):
matrix[i].reverse()
def flip_vertical_axis(matrix):
for i in range(len(matrix)):
matrix[i] = matrix[i][::-1]
Comments
1
Qiang Lu - 15 Nov, 2017
It is reversing every row by [::-1]
0
0
0
0