Daily Coding Problem: Get Exceptionally Good at Coding Interviews by Solving One Problem Every Day Second Edition Lawrence Wu
Daily Coding Problem: Get Exceptionally Good at Coding Interviews by Solving One Problem Every Day Second Edition Lawrence Wu
com
https://textbookfull.com/product/daily-coding-
problem-get-exceptionally-good-at-coding-
interviews-by-solving-one-problem-every-day-
second-edition-lawrence-wu/
https://textbookfull.com/product/creative-thinking-and-problem-
solving-fabian/
textbookfull.com
https://textbookfull.com/product/problem-solving-with-c-walter-j-
savitch/
textbookfull.com
https://textbookfull.com/product/introduction-to-polymer-science-and-
chemistry-a-problem-solving-approach-second-edition-chanda/
textbookfull.com
https://textbookfull.com/product/fission-track-thermochronology-and-
its-application-to-geology-marco-g-malusa/
textbookfull.com
Military Strategy A Very Short Introduction 2nd Edition
Antulio J Echevarria Ii
https://textbookfull.com/product/military-strategy-a-very-short-
introduction-2nd-edition-antulio-j-echevarria-ii/
textbookfull.com
https://textbookfull.com/product/strategic-supply-management-
revisited-competing-in-an-era-of-rapid-change-and-disruption-robert-j-
trent/
textbookfull.com
https://textbookfull.com/product/computer-vision-and-image-analysis-
digital-image-processing-and-analysis-4th-edition-scott-e-umbaugh/
textbookfull.com
Technology and Global Public Health Padmini Murthy
https://textbookfull.com/product/technology-and-global-public-health-
padmini-murthy/
textbookfull.com
Daily Coding Problem
Alex Miller and Lawrence Wu
1
2
All rights reserved. No part of this book may be reproduced in any form or by any
electronic or mechanical means, including information storage and retrieval systems,
without permission in writing from the publisher, except in the case of brief quota-
tions embodied in critical reviews and certain other noncommercial uses permitted
by copyright law. For more information, email the authors at founders@dailycoding-
problem.com.
SECOND EDITION
ISBN 978-1-7932966-3-4
( '
10987654321
Alex: For Mom, Dad,Jordan, Hannah, and Zaddy
3
Contents
Contents 5
I Data Structures 17
1 Arrays 19
1.1 Get product of all other elements . 20
1.2 Locate smallest window to be sorted 22
1.3 Calculate maximum subarray sum . 24
1.4 Find number of smaller elements to the right . 26
2 Strings 29
2.1 Find anagram indices 29
2.2 Generate palindrome pairs 32
2.3 Print zigzag form . . . . . 34
2.4 Determine smallest rotated string . 36
3 Linked Lists 41
3.1 Reverse linked list . . . . . . . . . . . . . . 42
3.2 Add two linked lists that represent numbers 44
3.3 Rearrange a linked list to alternate high-low 46
3.4 Find intersecting nodes of linked lists . 48
5
CONTENTS 6
6 Trees 73
6.1 Count unival trees . 75
6.2 Reconstruct tree from pre-order and in-order traversals 79
6.3 Evaluate arithmetic tree . . . . . . 81
6.4 Get tree level with minimum sum 83
8 Tries 93
8.1 Implement autocomplete system 95
8.2 Create PrefixMapSum class . . . 98
8.3 Find Maximum XOR of element pairs 102
9 Heaps 105
9 .1 Compute the running median 107
9 .2 Find most similar websites 109
9 .3 Generate regular numbers . 111
9.4 Build a Huffman tree 113
10 Graphs 119
10.1 Determine if a cycle exists . 122
10.2 Remove edges to create even trees 124
10.3 Create stepword chain .. 126
10.4 Beat Snakes and Ladders 128
10.5 Topological sort . . . 130
II Algorithms 143
12 Recursion 145
12.1 Tower of Hanoi . . . . . . . . 146
12.2 Implement regular expressions 149
12.3 Find array extremes efficiently 151
12.4 Play Nim . . . . . . . . . . . 154
CONTENTS 7
14 Backtracking 167
14.1 Compute flight itinerary 169
14.2 Solve Sudoku . . . . . . 171
14.3 Count Android unlock combinations . 174
16 Pathfinding 189
16.1 Dijkstra's algorithm 190
16.2 Bellman-Ford . 193
16.3 Floyd-Warshall 195
20 Applications 237
20.1 Ghost . . . . . . 238
20.2 Connect 4 . . . . 241
20.3 Cryptarithmetic . 247
CONTENTS 8
IV Design 271
Glossary 299
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
About the authors
Lawrence Wu is a software engineer who has worked at Google, Twitter, and Yelp
and has gained deep insight into each company's hiring practices. Most recently,
he has worked at Lyft on their self-driving division. Lawrence holds a degree in
computer science from the University ofToronto.
11
About this book
You may have bought this book because you are studying for an upcoming interview.
Or possibly you anticipate having a coding interview in the future. Or perhaps you
are simply interested in improving your knowledge of algorithms and data structures
by working through a set of problems! Whatever your use case, we hope you enjoy it.
The questions in this book have been chosen with practicality, clarity, and self-
improvement in mind. Each one is based on a real question that was asked recently
by top tech companies. The problems and explanations were then carefully edited so
that each one communicates a key idea that you can apply more generally. Finally,
we have organized these problems into chapters by topic, to ensure that you can
methodically build up your skills in specific areas.
At the beginning of each chapter we provide a crash course on the topic that follows,
but this book is no substitute for years of coding experience or a course in computer
science. As such, we assume that readers have experience with at least one program-
ming language, and have a basic familiarity with concepts such as graphs, recursion,
and hash tables.
The structure of this book is as follows. First, we introduce you to the most essential
data structures that pop up in coding interviews, such as linked lists, arrays, strings,
and hash tables. For each data structure, we offer a refresher on its advantages and
disadvantages, the time and space complexities of its operations, its implementation,
and what themes and key words to look for in order to recognize it.
13
CONTENTS 14
Third, we present a set of more advanced problems that require you to use the pre-
ceding data structures and algorithms in novel ways in order to solve real-world
applications. From deriving a perfect blackjack strategy to deciphering an alien dic-
tionary, these questions are designed to challenge you and widen your understanding
of what can be achieved with the right concepts and implementation.
Lastly, we address the topic of design. Interviewers like to gauge the ability of
candidates to understand tradeoffs between different approaches. As a result, it is not
uncommon to see problems with time and space constraints that require formulating
novel data structures. It has also become increasingly frequent for candidates to be
asked to design a high-level system that meets a particular need. Our :final chapters
on data structure and system design walk through each of these question types,
respectively, and provide a general strategy for approaching similar problems in the
future.
Before you jump in, we offer some general advice for working through the problems.
1. First, really try to solve each problem, even if it seems challenging, and even
if you aren't sure where to begin! Look for key words in the question, and
write out some pseudocode to get things started. Use the topic groupings to
your advantage: review the chapter introduction to see how a particular data
structure or algorithm may be relevant. This process of brainstorming and
engaging with the question will help to build your problem solving muscle
memory.
2. After giving the problem your best shot, read through the solution, looking
for not just how the algorithm works but why. What are the core concepts,
and to what other problems might they apply? About an hour later, and then
a week after, try to implement it again, this time without the solution.
3. Finally, stay positive! Many of these concepts are challenging, and without
CONTENTS 15
practice these data structures and algorithms may not seem intuitive. For ex-
ample, dynamic programming, a now-common technique, was first developed
by top mathematicians during the Cold War to optimize military operations!
Rather than trying to understand it all at once, put aside some time each day
to work through one or two problems, and let the material sink in gradually.
Good luck!
Part I
Data Structures
17
Arrays
Arrays are without a doubt the most fundamental data structure in computer science.
Under the hood, an array is represented as a fixed-size, contiguous block of memory
with 0(1) time to store and access an element. Because of this efficiency, many other
data structures frequently use arrays for their implementation, such as strings, stacks,
queues, and hash tables.
You can picture an array as a bounded row of labeled containers, starting at 0, where
you can quickly put items in, take them out, or look up a value from an index (or
label).
0 1 2 3 4 5 6 7
For example, in the diagram above, we have an array of length 8. We can set and
get the value associated with the third index in constant time using the following
operations:
array[2] = 'foo'
x = array[2] # 'foo'
19
. CHAPTER 1. ARRAYS 20
Finally, arrays have a fixed bound, which means they may not be suitable for applica-
tions where the size of the collection of elements is not known ahead of time. In an
interview setting, you should be careful of off-by-one errors that lead to trying to
access an element outside the range of the array.
Python does not have native support for arrays; typically, you'll use the list data
structure, which dynamically resizes under the hood. What this means is that to you,
the developer, it seems like the list is unbounded. In reality, as the list grows, the
data structure may allocate a larger (typically twice the current size) array, copy all
its elements to the larger one, and then use that as the underlying array.
In this chapter, we'll look at some common interview questions involving arrays and
strategies for solving them. Let's get started!
Given an array of integers, return a new array such that each element at index i of
the new array is the product of all the numbers in the original array except the one
at i.
For example, if our input was [ 1, 2, 3, 4, 5], the expected output would be [ 120,
60, 40, 30, 24]. Ifourinputwas [3, 2, 1],theexpectedoutputwouldbe [2,
3, 6].
Solution
This problem would be easy with division: an optimal solution could just find the
product of all numbers in the array and then divide by each of the numbers. To
solve this without division, we will rely on a common technique in array problems:
precomputing results from subarrays, and building up a solution from these results.
First note that to find the value associated with the i th element, we must compute
the product of all numbers before i and the product of all numbers after i. If we
could efficiently calculate these two, we could then simply multiply them to get our
desired product.
In order to find the product of numbers before i, we can generate a list of prefix
products. Specifically, the i th element in the list will be a product of all numbers
including i. Similarly, we can generate a list of suffix products. Finally, for each index
we can multiply the appropriate prefix and suffix values to obtain our solution.
def products(nums):
# Generate prefix products.
prefix_products = []
for num in nums:
if prefix_products:
prefix_products.append(prefix_products[-1] * num)
else:
prefix_products.append(num)
result.append(suffix_products[i + 1])
etif i == len(nums) - 1:
result.append(prefix_products[i - 1])
else:
result.append(
prefix_products[i - 1] * suffix_products[i + 1]
return result
This runs in O(n) time and space, since iterating over the input array takes O(n)
time and the prefix and suffix arrays take up 0( n) space.
Given an array of integers that are out of order, determine the bounds of the smallest
window that must be sorted in order for the entire array to be sorted. For example,
given [ 3 , 7 , 5 , 6 , 9] , you should return ( 1 , 3 ) .
Solution
One method we can try is to first find out what the array elements would look like
when sorted. For example, [ 3, 7, 5, 6, 9], after sorting, becomes [ 3, 5, 6, 7,
9]. We can see that the first and last elements remain unchanged, whereas the middle
elements are altered. Therefore, it suffices to take the first and last altered elements
as our window.
def window(array):
left, right= None, None
s = sorted(array)
for i in range(len(array)):
if array[i] != s[i] and left is None:
left= i
etif array[i] != s[i]:
right= i
CHAPTER 1. ARRAYS 23
This solution takes 0( n log n) time and space, since we create a sorted copy of the
original array.
Often when dealing with arrays, a more efficient algorithm can be found by looping
through the elements and computing a running minimum, maximum, or count. Let's
see how we can apply this here.
Suppose instead that we traversed the array, from left to right, and took note of
whether each element was less than the maximum seen up to that point. This
element would have to be part of the sorting window, since we would have to move
the maximum element past it.
As a result, we can take the last element that is less than the running maximum, and
use it as our right bound. Similarly, for our left bound, we can traverse the array from
right to left, and find the last element that exceeds the running minimum.
This will take two passes over the array, operating in O(n) time and 0(1) space.
def window(array):
left, right= None, None
n = len(array)
max_seen, min_seen = -float("inf"), float("inf")
for i in range(n):
max_seen = max(max_seen, array[i])
if array[i] < max_seen:
right= i
Given an array of numbers, :find the maximum sum of any contiguous subarray of
the array. For example, given the array [34, -50, 42, 14, -5, 86], the maximum
sum would be 137, since we would take elements 42, 14, -5, and 86. Given the array
[ -5, -1, -8, -9], the maximum sum would be 0, since we would choose not to
take any elements.
Follow-up: What if the elements can wrap around? For example, given [ 8, -1, 3,
4], return 15, as we choose the numbers 3, 4, and 8 where the 8 is obtained from
wrapping around.
Solution
The brute force approach here would be to iterate over every contiguous subarray
and calculate its sum, keeping track of the largest one seen.
def max_subarray_sum(arr):
current_max = 0
for i in range(len(arr) - 1):
for j in range(i, len(arr)):
current_max = max(current_max, sum(arr[i:j]))
return current_max
This would run in O(n 3 ) time. How can we make this faster?
We can work backwards from our desired solution by iterating over the array and
looking at the maximum possible subarray that can be made ending at each index.
For each index, we can either include the corresponding element in our sum or
exclude it.
As we iterate over our array, we can keep track of the maximum subarray we've seen
so far in a variable called max_so_ far. Whenever we find a larger subarray ending at
CHAPTER 1. ARRAYS 25
def max_subarray_sum(arr):
max_ending_here = max_so_far = 0
for x in arr:
max_ending_here = max(x, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max so far
Th.is algorithm is known as Kadane's algorithm, and it runs in O(n) time and 0(1)
space.
We split the follow-up problem into two parts. The :first part is the same as before:
finding the maximum subarray sum that doesn't wrap around. Next, we compute the
maximum subarray sum that does wrap around, and take the maximum of the two.
To get the largest wrap-around sum, we can use a little trick. For any subarray that
wraps around, there must be some contiguous elements that are excluded, and these
elements actually form the minimum possible subarray! Therefore, we can :first :find
the minimum subarray sum using exactly the method above, and subtract this from
the array's total.
For example, in the example above, the minimum subarray is [ -1], with a total of
-1. We then subtract this from the array total, 14, to get 15.
def maximum_circular_subarray(arr):
max_subarray_sum_wraparound = sum(arr) - min_subarray_sum(arr)
def max_subarray_sum(arr):
max_ending_here max_so_far 0
for x in arr:
max_ending_here = max(x, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
⁂ The Publishers, upon receipt of the price, will send any of the
following books by mail, POSTAGE FREE, to any part of the United
States. In ordering books, the full name, post-office, county and
State should be plainly written.
Inquire Within for Anything You Want to Know; or, Over
3,500 Facts for the People. “Inquire Within” is one of the
most valuable and extraordinary volumes ever presented to the
American public, and embodies nearly 4,000 facts, in most of
which any person living will find instruction, aid and
entertainment. As a book to be kept in the family for reference it
is unequaled, comprising, as it does, all kinds of books of
information in a single volume.
A Happy Woman.
The Somnambulist.
Those Thompsons.
Playing School.
Tom and Sally.
Assisting Hezekiah.
A Visit to the Oil Regions.
Breaking up the Exhibition.
Turning Around.
A Little Boy’s Debate.
The Silver Lining.
Restraining Jotham.
A Shoemaker’s Troubles.
An Uncomfortable Predicament.
The Opening Speech.
The Cucumber Hill Debating Club.
Married by the New Justice.
Bread on the Waters.
An Unsuccessful Advance.
When Women Have Their Rights.
Only Another Footprint.
Rosabella’s Lovers.
A Smart Boy.
A Heavy Shower.
Master of the Situation.
The marked favor with which the four preceding volumes have been
received suggested the necessity for an increased variety of new
eccentric and characteristic pieces, to form an addition to the
repertoire contained in “McBride’s Comic Dialogues,” “McBride’s
All Kinds of Dialogues,” “McBride’s Humorous Dialogues,” and
“McBride’s Temperance Dialogues.” They are all written with a
view to develop dramatic talent, and abound in quaint humor,
Dialect Drolleries, and telling stage “situations.”
16mo, 178 pages, illuminated paper cover. 30 cts.
Bound in boards. 50 cts.
Public Dinners,
Social Dinners,
Convivial Gatherings,
Art and Professional Banquets,
Manufacturers’ Meetings,
Agricultural and Commercial Festivals,
Special Toasts for Ladies,
Christmas, Thanksgiving and other Festivals,
Friendly Meetings,
Weddings and their Anniversaries,
Army and Navy Banquets,
Patriotic and Political Occasions,
Trades’ Unions and Dinners,
Benedicts’ and Bachelors’ Banquets,
Masonic Celebrations,
Sporting Coteries,
All Kinds of Occasions.
The Life, Crime and Capture of John Wilkes Booth. With a full
Sketch of the Conspiracy of which he was the Leader, and the
Pursuit, Trial and Execution of his Accomplices, together with an
original Poem on Abraham Lincoln. By George Alfred Townsend, a
Special Correspondent. Illustrated on the cover with a fine
portrait of the Assassin and also containing Plans, Maps, etc.
Octavo.
25 cts.
FRENCH DIALECT.
YANKEE DIALECT.
Biddy’s Troubles.
Birth of St. Patrick, The.
Bridget O’Hoolegoin’s Letter.
Connor.
Dermot O’Dowd.
Dick Macnamara’s Matrimonial Adventures.
Dying Confession of Paddy M’Cabe.
Father Molloy.
Father Phil Blake’s Collection.
Father Roach.
Fight of Hell-Kettle, The.
Handy Andy’s Little Mistakes.
How Dennis Took the Pledge.
How Pat Saved his Bacon.
Irish Astronomy.
Irish Coquetry.
Irish Drummer, The.
Irish Letter, An.
Irish Philosopher, The.
Irish Traveler, The.
Irishman’s Panorama, The.
Jimmy McBride’s Letter.
Jimmy Butler and the Owl.
King O’Toole and St. Kevin.
Kitty Malone.
Love in the Kitchen.
Micky Free and the Priest.
Miss Malony on the Chinese Question.
Mr. O’Hoolahan’s Mistake.
Paddy Blake’s Echo.
Paddy Fagan’s Pedigree.
Paddy McGrath and the Bear.
Paddy O’Rafther.
Paddy the Piper.
Paddy’s Dream.
Pat and the Fox.
Pat and the Gridiron.
Pat and his Musket.
Pat and the Oysters.
Pat’s Criticism.
Pat’s Letter.
Pat O’Flanigan’s Colt.
Patrick O’Rouke and the Frogs.
Paudeen O’Rafferty’s Say Voyage.
Peter Mulrooney and the Black Filly.
Phaidrig Crohoore.
Rory O’More’s Present to the Priest.
St. Kevin.
Teddy O’Toole’s Six Bulls.
Wake of Tim O’Hara, The.
Widow Cummiskey, The.