You are on page 1of 37

FuriousClown's Solutions Book

Copyright © 2016 - Firecode.io Inc.

All rights reserved, including the right to


reproduce this book or portions thereof in any
form whatsoever. For more information, address
the publisher at: info@firecode.io

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

return self.number_of_leaves(root.left_child) + self.number_of_leaves(root.right_ch


ild)

Top voted solution


class BinaryTree:
def __init__(self, root_node = None):
self.root = root_node

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

Sergio Puleri - 07 Nov, 2016


lol. i guess im a bit stinky 8)

1

Lokeshwaran K - 20 Jan, 2017


Why the else and elif after return? ;)

2
Reverse a Singly Linked List
Linked Lists

Given a singly linked list, write a method to perform In-place reversal.

Example:
1->2->3 ==> 3->2->1

Your solution

class SinglyLinkedList:
#constructor
def __init__(self):
self.head = None

#method for setting the head of the Linked List


def setHead(self,head):
self.head = head

def reverse(self):
current = self.head
prev_node = None

while current is not None:


next_node = current.getNext()
current.setNext(prev_node)
prev_node = current
current = next_node
self.setHead(prev_node)

Top voted solution


class SinglyLinkedList:
#constructor
def __init__(self):
self.head = None

#method for setting the head of the Linked List


def setHead(self,head):
self.head = head

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:

Input List : [1,2,5,5,8,8,10]


Input Number : 8
Output : [4,5]

Input List : [1,2,5,5,8,8,10]


Input Number : 2
Output : [1,1]

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)

Top voted solution


def bisect(xs, key, f):
left, right = 0, len(xs)

while left < right:


mid = left + (right - left)/2
if f(xs[mid], key): left = mid + 1
else: right = mid

return left

bisect_left = lambda xs,key: bisect(xs, key, lambda x,y: x<y)


bisect_right = lambda xs,key: bisect(xs, key, lambda x,y: x<=y)

def find_range(xs, key):


start = bisect_left(xs, key)
end = bisect_right(xs, key) - 1
return Range(start, end)

Comments
Madhu - 21 Jan, 2018
Great Man, what a logic and crisp code.

0

Char - 28 Feb, 2018


This guy Haskells...

1

Alex Buechele - 26 May, 2018


import bisect works, too

0
Inserting a Node at the End of
a Singly Linked List
Linked Lists

Write a function to insert a node at the end of a Singly Linked-List.


Click Use Me at the top to check the structure of Node .

Examples:
LinkedList: 1->2 , Head = 1

insertAtEnd(1) ==> 1->2->1

insertAtEnd(2) ==> 1->2->2

insertAtEnd(3) ==> 1->2->3

Your solution

class SinglyLinkedList:
#constructor
def __init__(self):
self.head = None

#method for setting the head of the Linked List


def setHead(self,head):
self.head = head

#method for inserting a new node at the end of a Linked List


def insertAtEnd(self,data):
new_node = Node()
last_node = Node()

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

#method for setting the head of the Linked List


def setHead(self,head):
self.head = head

#method for inserting a new node at the end of a Linked List


def insertAtEnd(self,data):
newNode = Node()
newNode.setData(data)

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

Top voted solution


def better_fibonacci(n):
x = 0
y = 1
for i in range(n):
x,y = y,y+x
return x

Comments
Kevin - 19 Dec, 2016
Wow, really elegant!

0

Cliff Xuan - 22 Feb, 2017


great solution

0

Suseela - 19 Aug, 2017


wow! you didn't even use conditionals for when n = 0, 1, 2

2

Max - 21 Aug, 2017


I love this solution

0
Kendy - 13 Nov, 2017
Nice!

0

Lucifer443 - 27 Apr, 2018


so cool!

0

Gain Chang - 22 May, 2018


concise!

0

Bennett Elder - 01 Jun, 2018


A little bit harder to reason through than the others, I'll admit. Definitely terse and to the point.

0
Insert Stars
Strings Recursion

Given a string , recursively compute a new string


where identical, adjacent characters
get separated with a "*".

Example:
insert_star_between_pairs("cac") ==> "cac"

insert_star_between_pairs("cc") ==> "c*c"

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:])

Top voted solution

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

Sreejith Menon - 16 Oct, 2016


I have the exact same approach, and I believed that the complexity is O(n) until I checked the
complexity tab and it says it is a O(n^2) solution. Is this true? If so, how?

2

Jose Villegas - 28 Dec, 2016


This is not a comment on your code, it's a comment on the problem. I don't understand why the
firecode people want a recursive solution, when an iterative solution is just as easy to understand, if
not more so and is more efficient by virtue that it doesn't use up memory in the call stack.

6

James Stoyell - 13 Mar, 2017


It's O(n^2) because string concatenation is O(n). The better solution would be to use a character
array that gets joined into a string at the end of the function

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

Auni Ahsan - 20 Aug, 2017


might be a nit, but else blocks are unnecessary when there's a return statement in the if block

3

Ayman - 16 May, 2018


return cancel need of elif

0
Bubble Sort
Arrays Numbers Sorting Algorithms

Write a function that takes in a list of int s and uses


the Bubble Sort algorithm to sort the list 'in place' in ascending order. The method should return the same, in-
place sorted list.
Note: Bubble sort is one of the most inefficient ways to sort a large list of integers. Nevertheless, it is an
interview favorite.
Bubble sort has a time complexity of O(n 2). However, if the
sample size is small, bubble sort provides a simple implementation of a classic sorting algorithm.

Examples:
bubble_sort([5, 4, 3]) -> [3, 4, 5]

bubble_sort([3]) -> [3]

bubble_sort([]) -> []

[] -> [Empty] List

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

Top voted solution


def bubble_sort(a_list):
is_sorted = False
while not is_sorted:
is_sorted = True
for i in range(len(a_list)-1):
if a_list[i] > a_list[i+1]:
a_list[i], a_list[i+1] = a_list[i+1], a_list[i]
is_sorted = False
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:

reverse_string("abcde") -> "edcba"

reverse_string("1") -> "1"

reverse_string("") -> ""

reverse_string("madam") -> "madam"

Your solution

def reverse_string(a_string):
return a_string[::-1]

Top voted solution

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()

Top voted solution

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

Taylor Kline - 22 Aug, 2017


How does this one work? Columns are not mentioned at all?

0

Karoliina Oksanen - 09 Sep, 2017


@Taylor K. It's swapping entire rows of the matrix at a time, there's no need to do it separately for
each column.

0

Saikat Kumar Dey - 28 Sep, 2017


Neat

0

Emmanuel Afolayan - 26 Dec, 2017


clever solution

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

is_palindrome("aabb") -> False

is_palindrome("race car") -> False

is_palindrome("") -> 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

Top voted solution

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

Omri Gabay - 27 Oct, 2017


So pythonic! I love it

0

Hassam Sheikh - 15 Dec, 2017


let me hang myself. Absolutely sweet.

1

Dan Huynh - 07 Jan, 2018


Shortest solution here. However, the splicing syntax returns a new list for O(n) space complexity.
Use the firecode solution, but change range with xrange for O(1) space complexity.

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]

duplicate_items([1, 3, 4, 2, 1, 2, 4]) => [1, 2, 4]

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

Top voted solution

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

Brian Hung - 24 May, 2017


Damn I love me some list comprehension.

3

Jason - 27 Sep, 2017


This is efficient but is it implicitly a nested loop due to the count function being another loop to count
up the occurrences?

1

Brian Hung - 28 Sep, 2017


I think it would be of O(n^2) given that, you first loop through the whole set, and then the count
method implicitly loops through list_numbers.

2

Jason - 28 Sep, 2017


Exactly Brian, I also agree it's O(n^2)

0
George Chinedu Nwankwo - 07 Feb, 2018
I agree that this is an O(n^2) solution

0

MaxNRG - 28 Mar, 2018


nice, thanks! one-liner version: def duplicate_items(list_numbers): return [i for i in set(list_numbers)
if list_numbers.count(i)&gt;1]

0

Ayman - 15 May, 2018


is this solution works when the original list is not sorted say list is [33,33,22,22] this works and to
find in this is too long you can use dictionary

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"

dec_to_bin(5) ==> "101"


Note : Do not use in-built bin() function.

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)

Top voted solution

def dec_to_bin(n):
if n<2: return str(n)
else:
return dec_to_bin(n/2) + dec_to_bin(n%2)

Comments

Erika Dike - 11 Aug, 2016


Nice use of recursion there.

2
Ackshaey Singh - 15 Sep, 2016
Thanks!

0

Koo Zhengqun - 18 Apr, 2017


this is genius

0

Brian Hung - 24 May, 2017


I knew recursion could've been used!

0

Javier - 22 Aug, 2017


Very nice!

0

Bob - 22 Aug, 2017


awesome, btw for python 3 you have to use floor division // or the answer will be off.

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)

Top voted solution

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

Julia - 15 Jul, 2016


Great solution. :) I have a few tips. You don't need to surround range(1, 11) with list. Python knows
how to sum all the elements in a given range. Secondly you can drop the 1 off the range so that it is
simply range(11) (although I guess this is more of a nitpick.

 18
David Hayden - 03 Feb, 2017
Nice!

0

Tyler Noblett - 05 Dec, 2017


very simple - I like that you could do it all in one line

0

MaxNRG - 28 Mar, 2018


def find_missing_number(list_numbers): return sum(list(range(1, len(list_numbers) + 2))) -
sum(list_numbers) improve your solution to work correct on lists with any length

0

Rishi - 10 Apr, 2018


Good stuff :)

0

Ayman - 15 May, 2018


in theory it is O(n) solution like mine but in practice if you just iterate you will reach solution faster

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

return fib(n-1) + fib(n-2)

Top voted solution

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()

Top voted solution

def flip_vertical_axis(matrix):

for i in range(len(matrix)):
matrix[i] = matrix[i][::-1]

Comments

Kyle Cheng - 10 Nov, 2017


Hi, can someone explain how this solution works?

1
Qiang Lu - 15 Nov, 2017
It is reversing every row by [::-1]

0

Hassam Sheikh - 15 Dec, 2017


@Kyle C. a matrix is a bunch of lists so I will try to explain it for one list only. So you have list=
[1,2,3,4,5], If I reverse is column wise, it will just be a reverse of the original list [5,4,3,2,1]. In the
solution above, he basically doing the same

0

Anonymous - 07 Mar, 2018


Can you explain why the following does not work: def flip_vertical_axis(matrix): for m in matrix: m =
m[::-1]

0

Vincent Russo - 05 Jun, 2018


Nice, exactly how I did my solution as well. Good and clean :)

0

You might also like